Datasets:
GeoCarto v1: 6600 tiles, 4 continents (real GMNA + realistic synthetic)
Browse files- README.md +85 -0
- build_config.json +20 -0
- data/test-00000.parquet +3 -0
- data/test-00001.parquet +3 -0
- data/train-00000.parquet +3 -0
- data/train-00001.parquet +3 -0
- data/train-00002.parquet +3 -0
- data/train-00003.parquet +3 -0
- data/train-00004.parquet +3 -0
- data/train-00005.parquet +3 -0
- data/train-00006.parquet +3 -0
- data/train-00007.parquet +3 -0
- data/train-00008.parquet +3 -0
- data/train-00009.parquet +3 -0
- data/train-00010.parquet +3 -0
- data/validation-00000.parquet +3 -0
- data/validation-00001.parquet +3 -0
- geocarto.py +956 -0
- index.csv +0 -0
- preview.png +3 -0
README.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-sa-4.0
|
| 3 |
+
task_categories:
|
| 4 |
+
- image-segmentation
|
| 5 |
+
tags:
|
| 6 |
+
- geology
|
| 7 |
+
- geological-map
|
| 8 |
+
- cartography
|
| 9 |
+
- vectorization
|
| 10 |
+
- instance-segmentation
|
| 11 |
+
- remote-sensing
|
| 12 |
+
- synthetic
|
| 13 |
+
pretty_name: GeoCarto – geological map scans to vector units (4 continents)
|
| 14 |
+
size_categories:
|
| 15 |
+
- 1K<n<10K
|
| 16 |
+
configs:
|
| 17 |
+
- config_name: default
|
| 18 |
+
data_files:
|
| 19 |
+
- split: train
|
| 20 |
+
path: data/train-*.parquet
|
| 21 |
+
- split: validation
|
| 22 |
+
path: data/validation-*.parquet
|
| 23 |
+
- split: test
|
| 24 |
+
path: data/test-*.parquet
|
| 25 |
+
---
|
| 26 |
+
|
| 27 |
+
# GeoCarto – from geological map images to vector units and faults
|
| 28 |
+
|
| 29 |
+
512×512 tiles of **geological maps** with pixel-exact ground truth for **map-unit instances** and **faults**,
|
| 30 |
+
covering **4 continents** (North America, Europe, Africa, Oceania). Built to train models that turn a scanned
|
| 31 |
+
geological map back into GIS polygons (e.g. affinity / boundary prediction + watershed).
|
| 32 |
+
|
| 33 |
+
* **real** tiles: USGS *Geologic Map of North America* (GMNA) 300 dpi rasters, with the official GMNA vector units
|
| 34 |
+
and faults rasterised on the same grid (~423 m/px).
|
| 35 |
+
* **synthetic** tiles: the official vector maps of each region are **rendered as realistic printed geological maps**
|
| 36 |
+
(CGMW/ICS chronostratigraphic colours modulated by lithology, stipple/hatch/volcanic "v"/plutonic "+" patterns,
|
| 37 |
+
contacts (sometimes dashed), thick faults with thrust teeth or normal-fault ticks, unit labels with leader lines,
|
| 38 |
+
sea with isobaths and ocean names, graticule, rivers, political boundaries, place names), then optionally
|
| 39 |
+
"printed and scanned" (paper tint, uneven lighting, blur, noise, channel misregistration, JPEG).
|
| 40 |
+
20 % of the tiles use a random palette so a model cannot learn "colour = unit". Scale varies from ~80 to ~600 m/px.
|
| 41 |
+
|
| 42 |
+
## Splits (spatial, no leakage)
|
| 43 |
+
Each source is cut into geographic blocks (150–600 km); every block belongs to exactly one split and a tile is kept
|
| 44 |
+
only if it lies entirely inside blocks of its split. Real and synthetic GMNA tiles share the same blocks.
|
| 45 |
+
|
| 46 |
+
| continent | source | kind | train | validation | test | total |
|
| 47 |
+
|---|---|---|---|---|---|---|
|
| 48 |
+
| Africa | UNESCO-Ethiopia | synthetic | 560 | 70 | 70 | 700 |
|
| 49 |
+
| Europe | GEO-LiM | synthetic | 960 | 120 | 120 | 1200 |
|
| 50 |
+
| North America | GMNA | real | 1141 | 81 | 78 | 1300 |
|
| 51 |
+
| North America | GMNA | synthetic | 480 | 60 | 60 | 600 |
|
| 52 |
+
| North America | USGS-California | synthetic | 560 | 70 | 70 | 700 |
|
| 53 |
+
| North America | USGS-Nevada | synthetic | 480 | 60 | 60 | 600 |
|
| 54 |
+
| Oceania | GA-Australia | synthetic | 1200 | 150 | 150 | 1500 |
|
| 55 |
+
|
| 56 |
+
## Columns
|
| 57 |
+
| column | content |
|
| 58 |
+
|---|---|
|
| 59 |
+
| `image` | RGB map tile (PNG, 512×512) |
|
| 60 |
+
| `instances` | uint16 PNG: 0 = no mapped unit (sea, lake, outside the map), 1..N = connected components of one geological unit. Two touching polygons of the **same** unit form **one** instance (no boundary is visible between them on a map). |
|
| 61 |
+
| `faults` | PNG {0,255}: fault traces rasterised 1 px wide (concealed/inferred faults included) |
|
| 62 |
+
| `units` | JSON: for each instance id → unit code, age and lithology from the source map |
|
| 63 |
+
| `source`, `continent`, `kind` (`real`/`synthetic`), `split` | provenance |
|
| 64 |
+
| `px_size_m`, `crs`, `bounds` | ground resolution and georeferencing of the tile |
|
| 65 |
+
| `render` | JSON rendering parameters of synthetic tiles (palette, scan effects…) |
|
| 66 |
+
|
| 67 |
+
```python
|
| 68 |
+
from datasets import load_dataset
|
| 69 |
+
import numpy as np
|
| 70 |
+
ds = load_dataset("PerfectWin/geocarto", split="train")
|
| 71 |
+
x = ds[0]
|
| 72 |
+
rgb = np.array(x["image"]); inst = np.array(x["instances"]).astype(np.int32); faults = np.array(x["faults"]) > 0
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
## Sources & licences (attribution required)
|
| 76 |
+
| region | dataset | licence |
|
| 77 |
+
|---|---|---|
|
| 78 |
+
| North America | Garrity, C.P., Soller, D.R., 2009, *Database of the Geologic Map of North America*, USGS Data Series 424 | public domain (USGS) |
|
| 79 |
+
| California, Nevada | Ludington, S. et al., 2005, *Preliminary integrated geologic map databases for the United States – Western States*, USGS OFR 2005-1305 | public domain (USGS) |
|
| 80 |
+
| Europe | Donnini, M., Marchesini, I., Zucchini, A., *A new Geo-Lithological Map (Geo-LiM) for Central Europe*, Zenodo, doi:10.5281/zenodo.3530257 | CC BY 4.0 |
|
| 81 |
+
| Africa | *Geological Map of Ethiopia at 1:1,000,000 scale*, Verner et al., UNESCO IHP-WINS | CC BY-SA |
|
| 82 |
+
| Oceania | Geoscience Australia, *Surface geology of Australia 1:1M* (dataset 149179) | CC BY 4.0 |
|
| 83 |
+
|
| 84 |
+
Because the Ethiopian map is CC BY-SA, the whole dataset is released under **CC BY-SA 4.0**.
|
| 85 |
+
The generator code (`geocarto.py`) and its configuration (`build_config.json`) are included.
|
build_config.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"seed": 2026,
|
| 3 |
+
"counts": {
|
| 4 |
+
"GA-Australia": 1500,
|
| 5 |
+
"GEO-LiM": 1200,
|
| 6 |
+
"UNESCO-Ethiopia": 700,
|
| 7 |
+
"USGS-California": 700,
|
| 8 |
+
"USGS-Nevada": 600,
|
| 9 |
+
"GMNA": 600
|
| 10 |
+
},
|
| 11 |
+
"block_m": {
|
| 12 |
+
"GA-Australia": 300000.0,
|
| 13 |
+
"GEO-LiM": 250000.0,
|
| 14 |
+
"UNESCO-Ethiopia": 200000.0,
|
| 15 |
+
"USGS-California": 150000.0,
|
| 16 |
+
"USGS-Nevada": 150000.0,
|
| 17 |
+
"GMNA": 600000.0
|
| 18 |
+
},
|
| 19 |
+
"tile": 512
|
| 20 |
+
}
|
data/test-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c28b66dfe9681083b92cacf23308fa9efac6d237ac88ec3a7c2856e21e7d802e
|
| 3 |
+
size 194696969
|
data/test-00001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e9831e370bf55d2405b47b6f2edfd8e4af49675b287acaf6a4050e15210c2e40
|
| 3 |
+
size 43536351
|
data/train-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c1ace2fa8552f308668f3c4436dc04883d27f8ed4b7483b17a68e188b9f8832b
|
| 3 |
+
size 178906464
|
data/train-00001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2a903e9e5dadad3ae8678e4702d948b6c191ae3f43dc0c8ede5871aa1ec078d8
|
| 3 |
+
size 173755982
|
data/train-00002.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c66f206453296cf4cdbff40d56a6e8df7b3f2dcd3f256a42c68e5f967fda2680
|
| 3 |
+
size 180058236
|
data/train-00003.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:846138149e699a3659d431b72d4d59089cf4f462b11550cb0932d9f52e2a48da
|
| 3 |
+
size 191628634
|
data/train-00004.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:35e66cbb541497872d49405210485103a2ccd9c8ce2ee9ad20b86d7481d68807
|
| 3 |
+
size 186367909
|
data/train-00005.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f57b4ba7fd0dee47d64917fbf1ebae311606a8eb75195f94d96aa32c6c6888c3
|
| 3 |
+
size 189581528
|
data/train-00006.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:11323454980b50948c7386bbb3db5f5ad35fd1bce446631b4c10a08741e4d17e
|
| 3 |
+
size 198330675
|
data/train-00007.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7c66dabeffd9ab2f344b0b3cd950dbf13fbe36b14f9b5540cbe45c7de0ed1f48
|
| 3 |
+
size 196839863
|
data/train-00008.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8b0a4d121c7318e303a6b3c5df33b8d9704cb3f61446a91f2315cb087a350e34
|
| 3 |
+
size 197145443
|
data/train-00009.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:385c0cb0fa53e241a6e5b384a66fb775edfb3bc7336c7acb03fb9ef321fd987c
|
| 3 |
+
size 194952399
|
data/train-00010.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1e79ffef831b4b557a32246249d89481cc9bf71536f40cc21407836e71735dff
|
| 3 |
+
size 144005689
|
data/validation-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f10adfa2daffcf5aee5d21f7d4fa59bf26670aee15249fb04a5cb4ce5c25eee1
|
| 3 |
+
size 170016830
|
data/validation-00001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eb317a0aebb9981667245ef1ac01d6bf713ec51169694f482a5f94db774186c8
|
| 3 |
+
size 38375651
|
geocarto.py
ADDED
|
@@ -0,0 +1,956 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =====================================================================================
|
| 2 |
+
# GEOCARTO : sources vectorielles -> tuiles (scan réaliste, instances, failles)
|
| 3 |
+
# - tuiles RÉELLES : scan GMNA + vecteurs USGS alignés
|
| 4 |
+
# - tuiles SYNTHÉTIQUES : la carte est "imprimée" à partir des polygones, dans le style
|
| 5 |
+
# d'une vraie carte géologique (couleurs chronostratigraphiques, motifs, contacts,
|
| 6 |
+
# failles à dents, étiquettes, mer, graticule, rivières...) puis "scannée".
|
| 7 |
+
# Vérité terrain commune :
|
| 8 |
+
# inst : uint16, 0 = pas de polygone (mer / hors carte), 1..N = composantes connexes
|
| 9 |
+
# d'une MÊME unité (deux polygones voisins de la même unité = une seule instance,
|
| 10 |
+
# car aucune limite n'est visible entre eux sur la carte)
|
| 11 |
+
# faults : uint8 {0,1}, tracé des failles (1 px)
|
| 12 |
+
# =====================================================================================
|
| 13 |
+
import io, json, math, re, zlib, colorsys
|
| 14 |
+
from functools import lru_cache
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import geopandas as gpd
|
| 20 |
+
import matplotlib
|
| 21 |
+
from shapely.geometry import box
|
| 22 |
+
from shapely.validation import make_valid
|
| 23 |
+
from rasterio.features import rasterize
|
| 24 |
+
from rasterio.transform import from_origin
|
| 25 |
+
from scipy import ndimage as ndi
|
| 26 |
+
from skimage.measure import label as cc_label, find_contours
|
| 27 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 28 |
+
|
| 29 |
+
TILE, SS = 512, 2 # tuile finale 512 px, rendu interne sur-échantillonné x2 (anti-crénelage)
|
| 30 |
+
R = TILE * SS
|
| 31 |
+
|
| 32 |
+
# ------------------------------------------------------------------ polices
|
| 33 |
+
_FD = Path(matplotlib.get_data_path()) / "fonts" / "ttf"
|
| 34 |
+
FONTS = {
|
| 35 |
+
"sans": "DejaVuSans.ttf", "bold": "DejaVuSans-Bold.ttf", "ital": "DejaVuSans-Oblique.ttf",
|
| 36 |
+
"bital": "DejaVuSans-BoldOblique.ttf", "serif": "DejaVuSerif.ttf", "serifi": "DejaVuSerif-Italic.ttf",
|
| 37 |
+
"serifb": "DejaVuSerif-Bold.ttf", "cond": "DejaVuSansMono.ttf",
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@lru_cache(maxsize=256)
|
| 42 |
+
def font(name, size):
|
| 43 |
+
try:
|
| 44 |
+
return ImageFont.truetype(str(_FD / FONTS[name]), int(size))
|
| 45 |
+
except Exception:
|
| 46 |
+
return ImageFont.load_default()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _seed(*parts):
|
| 50 |
+
return zlib.crc32("|".join(map(str, parts)).encode())
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# ------------------------------------------------------------------ couleurs (charte chronostratigraphique CGMW/ICS)
|
| 54 |
+
AGE_COLORS = [
|
| 55 |
+
(r"holocene|recent", (254, 242, 224)), (r"pleistocene", (255, 242, 174)), (r"quaternary|kvart", (249, 249, 127)),
|
| 56 |
+
(r"pliocene", (255, 255, 153)), (r"miocene", (255, 255, 0)), (r"neogene", (255, 230, 25)),
|
| 57 |
+
(r"oligocene", (254, 192, 122)), (r"pal(a)?eocene", (253, 167, 95)), (r"eocene", (253, 180, 108)),
|
| 58 |
+
(r"pal(a)?eogene", (253, 154, 82)), (r"tertiary", (255, 200, 60)), (r"c(a)?enozoic", (242, 249, 29)),
|
| 59 |
+
(r"cretaceous", (127, 198, 78)), (r"jurassic", (52, 178, 201)), (r"triassic", (129, 43, 146)),
|
| 60 |
+
(r"mesozoic", (103, 197, 202)), (r"permian", (240, 64, 40)),
|
| 61 |
+
(r"carboniferous|pennsylvanian|mississippian", (103, 165, 153)), (r"devonian", (203, 140, 55)),
|
| 62 |
+
(r"silurian", (179, 225, 182)), (r"ordovician", (0, 146, 112)), (r"cambrian", (127, 160, 86)),
|
| 63 |
+
(r"pal(a)?eozoic", (153, 192, 141)),
|
| 64 |
+
(r"ediacaran|cryogenian|tonian|neoproterozoic|late proterozoic", (254, 179, 66)),
|
| 65 |
+
(r"mesoproterozoic|middle proterozoic", (253, 180, 98)),
|
| 66 |
+
(r"pal(a)?eoproterozoic|early proterozoic", (247, 67, 112)), (r"proterozoic", (247, 53, 99)),
|
| 67 |
+
(r"archean|archaean", (240, 4, 127)), (r"precambrian", (247, 67, 112)),
|
| 68 |
+
]
|
| 69 |
+
LITHO_COLORS = [ # quand l'âge est inconnu (ex. GEO-LiM) : carte lithologique
|
| 70 |
+
(r"water|lake", (190, 225, 245)), (r"\bice\b|glacier", (236, 246, 252)), (r"peat", (170, 140, 100)),
|
| 71 |
+
(r"gypsum|evaporite", (250, 200, 230)), (r"pure carbonate", (140, 195, 235)),
|
| 72 |
+
(r"carbonate|limestone|dolom", (175, 215, 225)), (r"sandstone", (250, 222, 150)),
|
| 73 |
+
(r"claystone|shale|mudstone|clay", (215, 195, 160)), (r"acid|granit|felsic", (240, 120, 140)),
|
| 74 |
+
(r"intermediate", (235, 160, 180)), (r"mafic|basalt", (90, 150, 100)),
|
| 75 |
+
(r"metamorph|schist|gneiss", (190, 160, 215)), (r"alluvi|sediment", (255, 240, 170)),
|
| 76 |
+
]
|
| 77 |
+
PLUTONIC = re.compile(r"plutonic|intrusive|granit|tonalit|diorit|gabbro|syenit|monzon|batholith|granodior|pluton", re.I)
|
| 78 |
+
VOLCANIC = re.compile(r"volcanic|basalt|andesit|rhyolit|tuff|lava|ignimbr|trachy|pyroclast", re.I)
|
| 79 |
+
METAMORPH = re.compile(r"metamorph|schist|gneiss|crystalline|quartzite|marble|migmat|amphibolit|slate|phyllit", re.I)
|
| 80 |
+
UNCONSOL = re.compile(r"alluvi|unconsolidated|sand dune|colluv|aeolian|eolian|surficial|regolith|playa|dune", re.I)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _match(table, text):
|
| 84 |
+
t = (text or "").lower()
|
| 85 |
+
for pat, rgb in table:
|
| 86 |
+
if re.search(pat, t):
|
| 87 |
+
return np.array(rgb, np.float32)
|
| 88 |
+
return None
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _mix(a, b, w):
|
| 92 |
+
return a * (1 - w) + np.asarray(b, np.float32) * w
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def base_color(age, lith):
|
| 96 |
+
"""Couleur de légende 'officielle' d'une unité : âge (charte CGMW), modulée par la lithologie."""
|
| 97 |
+
age = age if isinstance(age, str) else ""
|
| 98 |
+
lith = lith if isinstance(lith, str) else ""
|
| 99 |
+
c = _match(AGE_COLORS, age)
|
| 100 |
+
if c is None:
|
| 101 |
+
c = _match(LITHO_COLORS, lith)
|
| 102 |
+
if c is None:
|
| 103 |
+
h = (_seed(age, lith) % 1000) / 1000
|
| 104 |
+
c = np.array(colorsys.hsv_to_rgb(h, 0.45, 0.9), np.float32) * 255
|
| 105 |
+
if re.search(r"\bice\b|glacier", lith, re.I):
|
| 106 |
+
return np.array((236, 246, 252), np.float32)
|
| 107 |
+
if PLUTONIC.search(lith):
|
| 108 |
+
c = _mix(c, (232, 50, 110), 0.5)
|
| 109 |
+
elif METAMORPH.search(lith):
|
| 110 |
+
c = _mix(c, (165, 120, 185), 0.35)
|
| 111 |
+
return c
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def pattern_pref(lith):
|
| 115 |
+
lith = lith if isinstance(lith, str) else ""
|
| 116 |
+
if VOLCANIC.search(lith):
|
| 117 |
+
return "v"
|
| 118 |
+
if UNCONSOL.search(lith):
|
| 119 |
+
return "dots"
|
| 120 |
+
if PLUTONIC.search(lith):
|
| 121 |
+
return "cross"
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# =====================================================================================
|
| 126 |
+
# SOURCES
|
| 127 |
+
# =====================================================================================
|
| 128 |
+
class Source:
|
| 129 |
+
"""Unités (polygones + uid), table des unités, failles, CRS métrique, plage d'échelles."""
|
| 130 |
+
|
| 131 |
+
def __init__(self, name, continent, units, tab, faults, px_range, min_land=0.55):
|
| 132 |
+
self.name, self.continent = name, continent
|
| 133 |
+
self.units, self.tab, self.faults = units, tab, faults
|
| 134 |
+
self.px_range, self.min_land = px_range, min_land
|
| 135 |
+
self.crs = units.crs
|
| 136 |
+
_ = units.sindex
|
| 137 |
+
if faults is not None and len(faults):
|
| 138 |
+
_ = faults.sindex
|
| 139 |
+
self.lut_rgb = np.zeros((int(tab.index.max()) + 1, 3), np.float32)
|
| 140 |
+
for uid, r in tab.iterrows():
|
| 141 |
+
self.lut_rgb[uid] = r.rgb
|
| 142 |
+
self.codes = tab["code"].to_dict()
|
| 143 |
+
self.pref = tab["pref"].to_dict()
|
| 144 |
+
|
| 145 |
+
def unit_meta(self, uid):
|
| 146 |
+
r = self.tab.loc[uid]
|
| 147 |
+
return {"unit": str(r.code), "age": str(r.age or ""), "lithology": str(r.lith or "")[:120]}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _clean(g, crs, simplify_m=0.0):
|
| 151 |
+
g = g[g.geometry.notnull() & ~g.geometry.is_empty].to_crs(crs)
|
| 152 |
+
g["geometry"] = g.geometry.apply(lambda x: x if x.is_valid else make_valid(x))
|
| 153 |
+
if simplify_m:
|
| 154 |
+
g["geometry"] = g.geometry.simplify(simplify_m, preserve_topology=True)
|
| 155 |
+
g = g[~g.geometry.is_empty & g.geom_type.isin(["Polygon", "MultiPolygon", "GeometryCollection"])]
|
| 156 |
+
return g.reset_index(drop=True)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _read(path, **kw):
|
| 160 |
+
for mode in ("fix", "ignore"):
|
| 161 |
+
try:
|
| 162 |
+
return gpd.read_file(path, on_invalid=mode, **kw)
|
| 163 |
+
except Exception:
|
| 164 |
+
pass
|
| 165 |
+
return gpd.read_file(path, **kw)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def build_units(g, key, code, age, lith, order=None):
|
| 169 |
+
"""Attribue un uid par unité (clé) et construit la table des unités."""
|
| 170 |
+
g = g.copy()
|
| 171 |
+
g["_key"] = g[key].astype(str).fillna("?")
|
| 172 |
+
keys = pd.Index(sorted(g["_key"].unique()))
|
| 173 |
+
g["uid"] = keys.get_indexer(g["_key"]) + 1
|
| 174 |
+
g["order"] = order if order is not None else 0
|
| 175 |
+
first = g.drop_duplicates("uid").set_index("uid").sort_index()
|
| 176 |
+
tab = pd.DataFrame(index=first.index)
|
| 177 |
+
tab["code"] = (first[code] if code in first else first["_key"]).fillna("").astype(str).str.slice(0, 10)
|
| 178 |
+
tab["age"] = (first[age] if isinstance(age, str) else age(first)).fillna("").astype(str)
|
| 179 |
+
tab["lith"] = (first[lith] if isinstance(lith, str) else lith(first)).fillna("").astype(str)
|
| 180 |
+
tab["rgb"] = [base_color(a, l) for a, l in zip(tab.age, tab.lith)]
|
| 181 |
+
tab["pref"] = [pattern_pref(l) for l in tab.lith]
|
| 182 |
+
return g[["uid", "order", "geometry"]], tab
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def load_gmna(units_shp, faults_shp, crs):
|
| 186 |
+
u = _clean(_read(units_shp), crs)
|
| 187 |
+
agef = lambda d: d["MIN_AGE"].fillna("").astype(str) + " / " + d["MAX_AGE"].fillna("").astype(str)
|
| 188 |
+
lithf = lambda d: d["ROCKTYPE"].fillna("").astype(str) + " " + d["LITHOLOGY"].fillna("").astype(str)
|
| 189 |
+
units, tab = build_units(u, "UNIT_ABBRE", "UNIT_ABBRE", agef, lithf)
|
| 190 |
+
f = _read(faults_shp).to_crs(crs)
|
| 191 |
+
f = f[f.geometry.notnull()].reset_index(drop=True)
|
| 192 |
+
f["kind"] = "generic"
|
| 193 |
+
f["concealed"] = False
|
| 194 |
+
return Source("GMNA", "North America", units, tab, f[["kind", "concealed", "geometry"]], (300, 600))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def load_geolim(gpkg, simplify_m=40):
|
| 198 |
+
g = _clean(gpd.read_file(gpkg), "EPSG:3035", simplify_m)
|
| 199 |
+
abbr = {"mix carbonate rocks": "Cm", "sandstone": "Ss", "claystone": "Cl", "pure carbonate rocks": "Cp",
|
| 200 |
+
"acid rocks": "γ", "mafic rocks": "β", "peat": "Pt", "water": "", "metamorphic rocks": "M",
|
| 201 |
+
"intermediate rocks": "δ", "gypsum evaporite": "Ev"}
|
| 202 |
+
g["code"] = g["litho_irpi"].map(abbr).fillna("?")
|
| 203 |
+
units, tab = build_units(g, "litho_irpi", "code", lambda d: pd.Series("", index=d.index), "litho_irpi")
|
| 204 |
+
return Source("GEO-LiM", "Europe", units, tab, None, (90, 420))
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def load_ethiopia(shp, simplify_m=40):
|
| 208 |
+
g = _clean(_read(shp), "EPSG:32637", simplify_m)
|
| 209 |
+
agef = lambda d: (d["ODD2_od"].fillna("").astype(str) + " " + d["UTVAR2_od"].fillna("").astype(str) + " "
|
| 210 |
+
+ d["ERA2_od"].fillna("").astype(str) + " " + d["ERA1_do"].fillna("").astype(str))
|
| 211 |
+
lithf = lambda d: d["HOR_TYP"].fillna("").astype(str) + " " + d["HOR_KARTO"].fillna("").astype(str)
|
| 212 |
+
g["code"] = g["legend_loo"].fillna(g["IDX"]).astype(str)
|
| 213 |
+
units, tab = build_units(g, "N_LEG_ID", "code", agef, lithf)
|
| 214 |
+
return Source("UNESCO-Ethiopia", "Africa", units, tab, None, (90, 420))
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
GA_LAYERS = ["Pre_Neoproterozoic", "Neoproterozoic", "Paleozoic", "Mesozoic", "Cenozoic"] # du plus vieux au plus jeune
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def load_australia(folder, simplify_m=60):
|
| 221 |
+
"""Couches par ère EMPILÉES : on dessine la plus jeune par-dessus (ordre de peinture)."""
|
| 222 |
+
folder = Path(folder)
|
| 223 |
+
parts, flts = [], []
|
| 224 |
+
for i, era in enumerate(GA_LAYERS):
|
| 225 |
+
p = folder / f"{era}GeologicalUnitPolygons1M.shp"
|
| 226 |
+
if p.exists():
|
| 227 |
+
g = _clean(_read(p, columns=["MAPSYMBOL", "PLOTSYMBOL", "GEOLHIST", "LITHOLOGY"]), "EPSG:3577", simplify_m)
|
| 228 |
+
g["order"] = i
|
| 229 |
+
parts.append(g)
|
| 230 |
+
q = folder / f"{era}ShearDisplacementLines1M.shp"
|
| 231 |
+
if q.exists():
|
| 232 |
+
f = _read(q, columns=["EXPOSURE", "MVTTYPE"]).to_crs("EPSG:3577")
|
| 233 |
+
f["geometry"] = f.geometry.simplify(simplify_m)
|
| 234 |
+
flts.append(f)
|
| 235 |
+
g = pd.concat(parts, ignore_index=True)
|
| 236 |
+
units, tab = build_units(g, "MAPSYMBOL", "MAPSYMBOL", "GEOLHIST", "LITHOLOGY", order=g["order"].values)
|
| 237 |
+
f = pd.concat(flts, ignore_index=True)
|
| 238 |
+
f = f[f.geometry.notnull() & ~f.geometry.is_empty].reset_index(drop=True)
|
| 239 |
+
mv = f["MVTTYPE"].fillna("").str.lower()
|
| 240 |
+
f["kind"] = np.where(mv.str.contains("thrust|reverse"), "thrust", np.where(mv.str.contains("normal"), "normal", "generic"))
|
| 241 |
+
f["concealed"] = f["EXPOSURE"].fillna("").str.lower().str.contains("conceal|inferred|buried")
|
| 242 |
+
return Source("GA-Australia", "Oceania", units, tab, gpd.GeoDataFrame(f[["kind", "concealed"]], geometry=f.geometry, crs=f.crs),
|
| 243 |
+
(100, 450))
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# Codes de lignes des cartes d'état USGS OF 2005-1305 (métadonnées CAmetadata.txt)
|
| 247 |
+
ARC_FAULT = {4, 5, 10, 11, 30, 31, 32, 52, 53, 57, 58, 87, 88, 89, 90, 91, 92, 100, 109, 113, 114, 115, 116}
|
| 248 |
+
ARC_THRUST, ARC_NORMAL = {10, 11, 53}, {4, 5, 52}
|
| 249 |
+
ARC_CONCEALED = {32, 52, 53, 57, 58, 90, 92, 100, 115, 116}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def load_usgs_state(poly_shp, arc_shp, name, simplify_m=30):
|
| 253 |
+
g = _clean(_read(poly_shp), "EPSG:5070", simplify_m)
|
| 254 |
+
g = g[~g["ORIG_LABEL"].astype(str).str.lower().isin(["water", "h2o"])].reset_index(drop=True)
|
| 255 |
+
units, tab = build_units(g, "ORIG_LABEL", "ORIG_LABEL", "UNIT_AGE",
|
| 256 |
+
lambda d: d["ROCKTYPE1"].fillna("").astype(str) + " " + d["ROCKTYPE2"].fillna("").astype(str))
|
| 257 |
+
a = _read(arc_shp, columns=["ARC_CODE"]).to_crs("EPSG:5070")
|
| 258 |
+
a = a[a["ARC_CODE"].isin(ARC_FAULT)].reset_index(drop=True)
|
| 259 |
+
a["kind"] = np.where(a.ARC_CODE.isin(ARC_THRUST), "thrust", np.where(a.ARC_CODE.isin(ARC_NORMAL), "normal", "generic"))
|
| 260 |
+
a["concealed"] = a.ARC_CODE.isin(ARC_CONCEALED)
|
| 261 |
+
return Source(name, "North America", units, tab, a[["kind", "concealed", "geometry"]], (80, 380), min_land=0.8)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
# =====================================================================================
|
| 265 |
+
# RASTERISATION D'UNE FENÊTRE
|
| 266 |
+
# =====================================================================================
|
| 267 |
+
def raster_units(src, x0, y1, px, n):
|
| 268 |
+
"""Carte des uid (n x n) d'une fenêtre ; ordre de peinture respecté (jeune par-dessus)."""
|
| 269 |
+
tr = from_origin(x0, y1, px, px)
|
| 270 |
+
win = box(x0, y1 - n * px, x0 + n * px, y1)
|
| 271 |
+
idx = src.units.sindex.query(win, predicate="intersects")
|
| 272 |
+
if len(idx) == 0:
|
| 273 |
+
return np.zeros((n, n), np.int32), win
|
| 274 |
+
sel = src.units.iloc[idx]
|
| 275 |
+
if sel["order"].nunique() > 1:
|
| 276 |
+
sel = sel.sort_values("order", kind="stable")
|
| 277 |
+
U = rasterize(zip(sel.geometry.values, sel.uid.values), out_shape=(n, n), transform=tr, fill=0, dtype="int32")
|
| 278 |
+
return U, win
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def fault_lines_px(src, win, x0, y1, px, rng=None):
|
| 282 |
+
"""Failles de la fenêtre en coordonnées pixel (à l'échelle px)."""
|
| 283 |
+
out = []
|
| 284 |
+
if src.faults is None or not len(src.faults):
|
| 285 |
+
return out
|
| 286 |
+
f = src.faults.iloc[src.faults.sindex.query(win.buffer(px * 4), predicate="intersects")]
|
| 287 |
+
for geom, kind, conc in zip(f.geometry.values, f["kind"].values, f["concealed"].values):
|
| 288 |
+
geom = geom.intersection(win.buffer(px * 4))
|
| 289 |
+
for line in getattr(geom, "geoms", [geom]):
|
| 290 |
+
if line.geom_type != "LineString" or line.length < px:
|
| 291 |
+
continue
|
| 292 |
+
xy = np.asarray(line.coords)[:, :2]
|
| 293 |
+
out.append(((xy[:, 0] - x0) / px, (y1 - xy[:, 1]) / px, kind, bool(conc)))
|
| 294 |
+
return out
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def instances(U):
|
| 298 |
+
"""Composantes connexes d'une même unité -> instances (0 = vide)."""
|
| 299 |
+
inst = cc_label(U, background=0, connectivity=1).astype(np.int32)
|
| 300 |
+
return inst
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def faults_gt(lines, scale=1.0, n=TILE):
|
| 304 |
+
img = Image.new("L", (n, n), 0)
|
| 305 |
+
d = ImageDraw.Draw(img)
|
| 306 |
+
for xs, ys, _, _ in lines:
|
| 307 |
+
pts = list(zip(xs * scale, ys * scale))
|
| 308 |
+
if len(pts) > 1:
|
| 309 |
+
d.line(pts, fill=1, width=1)
|
| 310 |
+
return np.asarray(img, np.uint8)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
# =====================================================================================
|
| 314 |
+
# RENDU "CARTE GÉOLOGIQUE IMPRIMÉE"
|
| 315 |
+
# =====================================================================================
|
| 316 |
+
SEA_WORDS = ["PACIFIC OCEAN", "ATLANTIC OCEAN", "SEA", "GULF", "BAY", "BASIN", "LAKE", "STRAIT", "OCEAN",
|
| 317 |
+
"INDIAN OCEAN", "CORAL SEA", "MER", "GOLFE", "LAC", "SOUND", "CHANNEL", "TROUGH", "ABYSSAL PLAIN"]
|
| 318 |
+
LAND_WORDS = ["MOUNTAINS", "PLATEAU", "RANGE", "BASIN", "SHIELD", "PLAIN", "DESERT", "VALLEY", "HIGHLANDS", "MASSIF"]
|
| 319 |
+
SYL = ["ka", "ri", "mo", "ton", "ber", "ville", "lin", "sa", "na", "port", "ford", "dor", "ve", "la", "mar", "zan",
|
| 320 |
+
"gu", "el", "ash", "wa", "bur", "go", "ta", "ne", "kel", "an", "os", "ru", "mi", "hol"]
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def _rname(rng, k=None):
|
| 324 |
+
k = k or rng.integers(2, 4)
|
| 325 |
+
return "".join(rng.choice(SYL) for _ in range(k)).capitalize()
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def edition(rng):
|
| 329 |
+
"""Style d'une 'édition' de carte (tiré à chaque tuile)."""
|
| 330 |
+
e = {}
|
| 331 |
+
e["palette"] = "legend" if rng.random() < 0.8 else "random"
|
| 332 |
+
e["light"] = rng.uniform(0.0, 0.4)
|
| 333 |
+
e["sat"] = rng.uniform(0.7, 1.1)
|
| 334 |
+
e["hue"] = rng.uniform(-0.03, 0.03)
|
| 335 |
+
e["jit"] = rng.uniform(0.01, 0.06)
|
| 336 |
+
e["sea"] = [(228, 229, 238), (214, 233, 245), (255, 255, 255), (236, 240, 232), (200, 222, 240)][rng.integers(5)]
|
| 337 |
+
e["contacts"] = rng.random() > 0.06
|
| 338 |
+
e["c_w"] = int(rng.choice([1, 2, 2, 2, 3])) # en px internes (x2)
|
| 339 |
+
e["c_col"] = tuple(int(v) for v in rng.integers(20, 80, 3))
|
| 340 |
+
e["c_dash"] = rng.uniform(0, 0.15)
|
| 341 |
+
e["coast"] = rng.random() < 0.85
|
| 342 |
+
e["coast_col"] = (int(rng.integers(40, 110)), int(rng.integers(140, 190)), int(rng.integers(200, 240)))
|
| 343 |
+
e["f_w"] = int(rng.choice([3, 4, 5, 6]))
|
| 344 |
+
e["f_col"] = (0, 0, 0) if rng.random() < 0.75 else ((int(rng.integers(150, 220)), 0, 0) if rng.random() < .7 else (60, 60, 60))
|
| 345 |
+
e["pattern_p"] = rng.uniform(0.05, 0.35)
|
| 346 |
+
e["label_p"] = rng.uniform(0.3, 0.95) if rng.random() < 0.9 else 0.0
|
| 347 |
+
e["label_font"] = rng.choice(["sans", "sans", "bold", "serif", "ital"])
|
| 348 |
+
e["label_size"] = rng.uniform(11, 22)
|
| 349 |
+
e["label_col"] = tuple(int(v) for v in rng.integers(0, 70, 3))
|
| 350 |
+
e["scan"] = rng.random() < 0.35
|
| 351 |
+
return e
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _palette(src, uids, e, rng, ed_seed):
|
| 355 |
+
lut = {}
|
| 356 |
+
if e["palette"] == "random": # couleurs bien séparées, attribuées au hasard (le réseau n'apprend pas "couleur = unité")
|
| 357 |
+
n = max(len(uids), 1)
|
| 358 |
+
style = rng.choice(["pastel", "vif", "moyen"])
|
| 359 |
+
s_lo, s_hi, v_lo, v_hi = {"pastel": (0.25, 0.45, 0.85, 0.97), "vif": (0.5, 0.75, 0.8, 0.95),
|
| 360 |
+
"moyen": (0.35, 0.65, 0.65, 0.9)}[style]
|
| 361 |
+
off = rng.random()
|
| 362 |
+
hues = [(off + i / n) % 1.0 for i in range(n)]
|
| 363 |
+
rng.shuffle(hues)
|
| 364 |
+
for i, (u, h) in enumerate(zip(uids, hues)):
|
| 365 |
+
v = v_hi if i % 2 == 0 else v_lo
|
| 366 |
+
lut[u] = np.array(colorsys.hsv_to_rgb(h, rng.uniform(s_lo, s_hi), v), np.float32) * 255
|
| 367 |
+
return lut
|
| 368 |
+
for u in uids:
|
| 369 |
+
r = np.random.default_rng(_seed(ed_seed, src.name, u))
|
| 370 |
+
h, s, v = colorsys.rgb_to_hsv(*(src.lut_rgb[u] / 255))
|
| 371 |
+
h = (h + e["hue"] + r.normal(0, e["jit"] * 0.5)) % 1
|
| 372 |
+
s = np.clip(s * e["sat"] * r.uniform(1 - e["jit"] * 3, 1 + e["jit"] * 2), 0, 1)
|
| 373 |
+
v = np.clip(v * r.uniform(1 - e["jit"] * 2, 1 + e["jit"]), 0, 1)
|
| 374 |
+
c = np.array(colorsys.hsv_to_rgb(h, s, v), np.float32) * 255
|
| 375 |
+
lut[u] = _mix(c, (255, 255, 255), np.clip(e["light"] + r.normal(0, 0.05), 0, 0.7))
|
| 376 |
+
return lut
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _glyph_tile(kind, s, rng):
|
| 380 |
+
"""Motif élémentaire (s x s) répété par np.tile -> masque booléen R x R."""
|
| 381 |
+
im = Image.new("L", (s, s), 0)
|
| 382 |
+
d = ImageDraw.Draw(im)
|
| 383 |
+
c, k = s / 2, s * rng.uniform(0.18, 0.3)
|
| 384 |
+
if kind == "dots":
|
| 385 |
+
r = max(1.2, s * rng.uniform(0.07, 0.14))
|
| 386 |
+
d.ellipse([c - r, c - r, c + r, c + r], fill=1)
|
| 387 |
+
elif kind == "v":
|
| 388 |
+
d.line([(c - k, c - k), (c, c + k), (c + k, c - k)], fill=1, width=2)
|
| 389 |
+
elif kind == "tri":
|
| 390 |
+
d.polygon([(c - k, c + k), (c + k, c + k), (c, c - k)], fill=1)
|
| 391 |
+
elif kind == "cross":
|
| 392 |
+
d.line([(c - k, c), (c + k, c)], fill=1, width=2)
|
| 393 |
+
d.line([(c, c - k), (c, c + k)], fill=1, width=2)
|
| 394 |
+
elif kind == "dash":
|
| 395 |
+
d.line([(c - k, c), (c + k, c)], fill=1, width=2)
|
| 396 |
+
m = np.asarray(im, bool)
|
| 397 |
+
m2 = np.concatenate([m, np.roll(m, s // 2, axis=1)], 0) # rangées décalées
|
| 398 |
+
full = np.tile(m2, (R // (2 * s) + 2, R // s + 2))
|
| 399 |
+
oy, ox = rng.integers(0, 2 * s), rng.integers(0, s)
|
| 400 |
+
return full[oy:oy + R, ox:ox + R]
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def _pattern_mask(kind, rng):
|
| 404 |
+
yy, xx = np.mgrid[:R, :R]
|
| 405 |
+
if kind == "lines":
|
| 406 |
+
per, w = rng.integers(14, 30), rng.integers(2, 4)
|
| 407 |
+
a = rng.choice([np.pi / 4, -np.pi / 4, 0, np.pi / 2, np.pi / 3])
|
| 408 |
+
return ((xx * np.cos(a) + yy * np.sin(a)) % per) < w
|
| 409 |
+
if kind == "grid":
|
| 410 |
+
per = rng.integers(18, 34)
|
| 411 |
+
return ((xx % per) < 2) | ((yy % per) < 2)
|
| 412 |
+
return _glyph_tile(kind, int(rng.integers(14, 30)), rng)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def _resample(xs, ys, step):
|
| 416 |
+
seg = np.hypot(np.diff(xs), np.diff(ys))
|
| 417 |
+
L = np.concatenate([[0], np.cumsum(seg)])
|
| 418 |
+
if L[-1] < step:
|
| 419 |
+
return None
|
| 420 |
+
t = np.arange(0, L[-1], step)
|
| 421 |
+
return np.interp(t, L, xs), np.interp(t, L, ys)
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def _draw_fault(d, xs, ys, kind, concealed, w, col, rng, side):
|
| 425 |
+
pts = list(zip(xs, ys))
|
| 426 |
+
if concealed:
|
| 427 |
+
rs = _resample(xs, ys, 3)
|
| 428 |
+
if rs is None:
|
| 429 |
+
return
|
| 430 |
+
X, Y = rs
|
| 431 |
+
on, off = (8, 6) if rng.random() < 0.6 else (2, 4)
|
| 432 |
+
i = 0
|
| 433 |
+
while i < len(X) - 1:
|
| 434 |
+
j = min(i + on, len(X) - 1)
|
| 435 |
+
d.line(list(zip(X[i:j + 1], Y[i:j + 1])), fill=col, width=max(2, w - 1))
|
| 436 |
+
i = j + off
|
| 437 |
+
else:
|
| 438 |
+
d.line(pts, fill=col, width=w, joint="curve")
|
| 439 |
+
if kind in ("thrust", "normal"):
|
| 440 |
+
rs = _resample(xs, ys, 2)
|
| 441 |
+
if rs is None:
|
| 442 |
+
return
|
| 443 |
+
X, Y = rs
|
| 444 |
+
gap = int(rng.integers(14, 24)) if kind == "thrust" else int(rng.integers(30, 50))
|
| 445 |
+
for i in range(gap // 2, len(X) - 3, gap):
|
| 446 |
+
tx, ty = X[i + 2] - X[i], Y[i + 2] - Y[i]
|
| 447 |
+
n = math.hypot(tx, ty) or 1
|
| 448 |
+
tx, ty = tx / n, ty / n
|
| 449 |
+
nx, ny = -ty * side, tx * side
|
| 450 |
+
h = w * 1.9
|
| 451 |
+
if kind == "thrust":
|
| 452 |
+
d.polygon([(X[i] - tx * h * .7, Y[i] - ty * h * .7), (X[i] + tx * h * .7, Y[i] + ty * h * .7),
|
| 453 |
+
(X[i] + nx * h * 1.3, Y[i] + ny * h * 1.3)], fill=col)
|
| 454 |
+
else:
|
| 455 |
+
ex, ey = X[i] + nx * h * 1.6, Y[i] + ny * h * 1.6
|
| 456 |
+
d.line([(X[i], Y[i]), (ex, ey)], fill=col, width=max(2, w // 2))
|
| 457 |
+
r = w * 0.8
|
| 458 |
+
d.ellipse([ex - r, ey - r, ex + r, ey + r], fill=col)
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def _random_curve(rng, wiggle=0.12, step=6):
|
| 462 |
+
side = rng.integers(4)
|
| 463 |
+
p = rng.uniform(0, R)
|
| 464 |
+
x, y, a = [(p, 0, np.pi / 2), (R, p, np.pi), (p, R, -np.pi / 2), (0, p, 0)][side]
|
| 465 |
+
a += rng.uniform(-0.7, 0.7)
|
| 466 |
+
xs, ys, da = [x], [y], 0.0
|
| 467 |
+
for _ in range(4 * R // step):
|
| 468 |
+
da = 0.85 * da + rng.normal(0, wiggle)
|
| 469 |
+
a += da * 0.3
|
| 470 |
+
x, y = x + step * np.cos(a), y + step * np.sin(a)
|
| 471 |
+
xs.append(x); ys.append(y)
|
| 472 |
+
if not (-20 < x < R + 20 and -20 < y < R + 20):
|
| 473 |
+
break
|
| 474 |
+
return np.array(xs), np.array(ys)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def _dashed(d, xs, ys, col, w, on, off):
|
| 478 |
+
rs = _resample(xs, ys, 2)
|
| 479 |
+
if rs is None:
|
| 480 |
+
return
|
| 481 |
+
X, Y = rs
|
| 482 |
+
i = 0
|
| 483 |
+
while i < len(X) - 1:
|
| 484 |
+
j = min(i + on, len(X) - 1)
|
| 485 |
+
d.line(list(zip(X[i:j + 1], Y[i:j + 1])), fill=col, width=w)
|
| 486 |
+
i = j + off
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def _spaced(t):
|
| 490 |
+
return " ".join(t) if len(t) < 12 else t
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def render_map(src, U, lines, rng, px_m):
|
| 494 |
+
"""U : uid (R x R) ; lines : failles en px internes. Retourne l'image RGB uint8 (TILE x TILE)."""
|
| 495 |
+
e = edition(rng)
|
| 496 |
+
ed_seed = int(rng.integers(1 << 30))
|
| 497 |
+
uids = [int(u) for u in np.unique(U) if u > 0]
|
| 498 |
+
lut = _palette(src, uids, e, rng, ed_seed)
|
| 499 |
+
LUT = np.zeros((max(uids + [0]) + 1, 3), np.float32)
|
| 500 |
+
LUT[0] = e["sea"]
|
| 501 |
+
for u, c in lut.items():
|
| 502 |
+
LUT[u] = c
|
| 503 |
+
img = LUT[U]
|
| 504 |
+
land = U > 0
|
| 505 |
+
|
| 506 |
+
# --- motifs (pointillés, hachures, V volcaniques, croix plutoniques, triangles)
|
| 507 |
+
masks = {}
|
| 508 |
+
for u in uids:
|
| 509 |
+
pref = src.pref.get(u)
|
| 510 |
+
r = np.random.default_rng(_seed(ed_seed, "pat", u))
|
| 511 |
+
p = e["pattern_p"] * (2.2 if pref else 1)
|
| 512 |
+
if r.random() > p:
|
| 513 |
+
continue
|
| 514 |
+
kind = pref if (pref and r.random() < 0.7) else r.choice(["dots", "lines", "lines", "v", "tri", "dash", "grid", "cross"])
|
| 515 |
+
if kind not in masks:
|
| 516 |
+
masks[kind] = _pattern_mask(kind, rng)
|
| 517 |
+
m = (U == u) & masks[kind]
|
| 518 |
+
if kind == "tri" and r.random() < 0.5:
|
| 519 |
+
col = np.array([r.integers(180, 240), r.integers(0, 60), r.integers(40, 100)], np.float32)
|
| 520 |
+
elif r.random() < 0.3:
|
| 521 |
+
col = np.array([r.integers(120, 180), r.integers(60, 110), r.integers(20, 60)], np.float32)
|
| 522 |
+
else:
|
| 523 |
+
col = LUT[u] * r.uniform(0.45, 0.75)
|
| 524 |
+
img[m] = col
|
| 525 |
+
|
| 526 |
+
# --- contacts géologiques
|
| 527 |
+
if e["contacts"]:
|
| 528 |
+
b = np.zeros_like(land)
|
| 529 |
+
b[:, 1:] |= U[:, 1:] != U[:, :-1]
|
| 530 |
+
b[1:, :] |= U[1:, :] != U[:-1, :]
|
| 531 |
+
b &= land | np.roll(land, 1, 0) | np.roll(land, 1, 1)
|
| 532 |
+
coast = np.zeros_like(land)
|
| 533 |
+
coast[:, 1:] |= land[:, 1:] != land[:, :-1]
|
| 534 |
+
coast[1:, :] |= land[1:, :] != land[:-1, :]
|
| 535 |
+
b &= ~coast
|
| 536 |
+
if e["c_w"] > 1:
|
| 537 |
+
b = ndi.binary_dilation(b, iterations=e["c_w"] - 1)
|
| 538 |
+
if e["c_dash"] > 0.02:
|
| 539 |
+
dashed_units = [u for u in uids if np.random.default_rng(_seed(ed_seed, "d", u)).random() < e["c_dash"]]
|
| 540 |
+
if dashed_units:
|
| 541 |
+
yy, xx = np.mgrid[:R, :R]
|
| 542 |
+
dz = ndi.binary_dilation(np.isin(U, dashed_units), iterations=2)
|
| 543 |
+
b &= ~(dz & (((xx + yy) // 10) % 2 == 0))
|
| 544 |
+
img[b] = e["c_col"]
|
| 545 |
+
if e["coast"]:
|
| 546 |
+
cw = int(rng.integers(2, 5))
|
| 547 |
+
img[ndi.binary_dilation(coast, iterations=cw - 1) if cw > 1 else coast] = e["coast_col"]
|
| 548 |
+
|
| 549 |
+
sea_frac = 1 - land.mean()
|
| 550 |
+
im = Image.fromarray(np.clip(img, 0, 255).astype(np.uint8))
|
| 551 |
+
d = ImageDraw.Draw(im)
|
| 552 |
+
|
| 553 |
+
# --- mer : isobathes + grands noms bleus
|
| 554 |
+
if sea_frac > 0.1 and rng.random() < 0.6:
|
| 555 |
+
noise = ndi.gaussian_filter(rng.normal(size=(R // 8, R // 8)), rng.uniform(3, 7))
|
| 556 |
+
noise = ndi.zoom(noise, 8, order=1)
|
| 557 |
+
col = (int(rng.integers(90, 160)), int(rng.integers(170, 210)), int(rng.integers(215, 245)))
|
| 558 |
+
for lev in np.quantile(noise, rng.uniform(0.2, 0.8, rng.integers(1, 4))):
|
| 559 |
+
for c in find_contours(noise, lev):
|
| 560 |
+
if len(c) < 30:
|
| 561 |
+
continue
|
| 562 |
+
keep = ~land[np.clip(c[:, 0].astype(int), 0, R - 1), np.clip(c[:, 1].astype(int), 0, R - 1)]
|
| 563 |
+
c = c[keep]
|
| 564 |
+
if len(c) > 30:
|
| 565 |
+
_dashed(d, c[:, 1], c[:, 0], col, 2, 10, 6) if rng.random() < .5 else d.line(list(zip(c[:, 1], c[:, 0])), fill=col, width=2)
|
| 566 |
+
if sea_frac > 0.25 and rng.random() < 0.6:
|
| 567 |
+
ys, xs = np.nonzero(~land[::16, ::16])
|
| 568 |
+
if len(ys):
|
| 569 |
+
k = rng.integers(len(ys))
|
| 570 |
+
t = rng.choice(SEA_WORDS)
|
| 571 |
+
t = _spaced(t) if rng.random() < .7 else t
|
| 572 |
+
f = font(rng.choice(["bital", "serifi", "ital"]), rng.uniform(30, 70))
|
| 573 |
+
d.text((xs[k] * 16 - rng.uniform(0, 300), ys[k] * 16), t, font=f,
|
| 574 |
+
fill=(int(rng.integers(20, 80)), int(rng.integers(80, 140)), int(rng.integers(170, 220))))
|
| 575 |
+
|
| 576 |
+
# --- graticule (méridiens / parallèles) + degrés
|
| 577 |
+
for _ in range(rng.integers(0, 3)):
|
| 578 |
+
col = tuple(int(v) for v in (rng.integers(0, 90, 3) if rng.random() < .6 else (rng.integers(150, 210), 120, rng.integers(150, 210))))
|
| 579 |
+
a, b2 = rng.uniform(0, R, 2)
|
| 580 |
+
if rng.random() < 0.5:
|
| 581 |
+
d.line([(a, 0), (b2, R)], fill=col, width=int(rng.integers(1, 3)))
|
| 582 |
+
lab_xy = (a + 6, rng.uniform(20, R - 40))
|
| 583 |
+
else:
|
| 584 |
+
d.line([(0, a), (R, b2)], fill=col, width=int(rng.integers(1, 3)))
|
| 585 |
+
lab_xy = (rng.uniform(20, R - 80), a + 6)
|
| 586 |
+
if rng.random() < 0.5:
|
| 587 |
+
d.text(lab_xy, f"{rng.integers(0, 180)}°", font=font("bold", rng.uniform(22, 40)), fill=col)
|
| 588 |
+
|
| 589 |
+
# --- rivières
|
| 590 |
+
if rng.random() < 0.55:
|
| 591 |
+
col = (int(rng.integers(60, 130)), int(rng.integers(150, 200)), int(rng.integers(210, 245)))
|
| 592 |
+
for _ in range(rng.integers(1, 5)):
|
| 593 |
+
xs, ys = _random_curve(rng, wiggle=0.2, step=5)
|
| 594 |
+
d.line(list(zip(xs, ys)), fill=col, width=int(rng.integers(2, 4)), joint="curve")
|
| 595 |
+
|
| 596 |
+
# --- frontières politiques (tirets colorés)
|
| 597 |
+
if rng.random() < 0.35:
|
| 598 |
+
col = [(200, 120, 200), (170, 110, 60), (150, 90, 170), (230, 150, 60), (120, 120, 120)][rng.integers(5)]
|
| 599 |
+
xs, ys = _random_curve(rng, wiggle=0.08, step=8)
|
| 600 |
+
_dashed(d, xs, ys, col, int(rng.integers(4, 9)), int(rng.integers(8, 20)), int(rng.integers(4, 10)))
|
| 601 |
+
|
| 602 |
+
# --- failles
|
| 603 |
+
for xs, ys, kind, conc in lines:
|
| 604 |
+
r = np.random.default_rng(_seed(ed_seed, "f", round(float(xs[0]), 1), round(float(ys[0]), 1)))
|
| 605 |
+
if kind == "generic" and r.random() < 0.15:
|
| 606 |
+
kind = r.choice(["thrust", "normal"])
|
| 607 |
+
_draw_fault(d, xs, ys, kind, conc, e["f_w"], e["f_col"], r, 1 if r.random() < .5 else -1)
|
| 608 |
+
|
| 609 |
+
# --- étiquettes d'unités (au point le plus intérieur de chaque instance, + traits de rappel)
|
| 610 |
+
if e["label_p"] > 0 and uids:
|
| 611 |
+
inst = cc_label(U, background=0, connectivity=1)
|
| 612 |
+
n = inst.max()
|
| 613 |
+
if n:
|
| 614 |
+
dist = ndi.distance_transform_edt(inst > 0)
|
| 615 |
+
idx = np.arange(1, n + 1)
|
| 616 |
+
pos = ndi.maximum_position(dist, inst, idx)
|
| 617 |
+
val = ndi.maximum(dist, inst, idx)
|
| 618 |
+
uid_of = ndi.maximum(U, inst, idx)
|
| 619 |
+
fs = int(e["label_size"] * SS)
|
| 620 |
+
f = font(e["label_font"], fs)
|
| 621 |
+
placed = []
|
| 622 |
+
for (py, px), v, u in zip(pos, val, uid_of):
|
| 623 |
+
if rng.random() > e["label_p"]:
|
| 624 |
+
continue
|
| 625 |
+
t = str(src.codes.get(int(u), ""))[:8]
|
| 626 |
+
if not t or t == "nan":
|
| 627 |
+
continue
|
| 628 |
+
if e["label_font"] == "bold" and rng.random() < .3:
|
| 629 |
+
t = t.upper()
|
| 630 |
+
tw = d.textlength(t, font=f)
|
| 631 |
+
if v > fs * 0.8:
|
| 632 |
+
x, y = px - tw / 2, py - fs / 2
|
| 633 |
+
elif v > 3 and rng.random() < 0.35:
|
| 634 |
+
ang = rng.uniform(0, 2 * np.pi)
|
| 635 |
+
L = rng.uniform(25, 60)
|
| 636 |
+
x, y = px + L * np.cos(ang), py + L * np.sin(ang)
|
| 637 |
+
d.line([(px, py), (x, y + fs / 2)], fill=e["label_col"], width=2)
|
| 638 |
+
else:
|
| 639 |
+
continue
|
| 640 |
+
bb = (x - 2, y - 2, x + tw + 2, y + fs + 2)
|
| 641 |
+
if any(not (bb[2] < q[0] or bb[0] > q[2] or bb[3] < q[1] or bb[1] > q[3]) for q in placed):
|
| 642 |
+
continue
|
| 643 |
+
placed.append(bb)
|
| 644 |
+
if rng.random() < 0.15: # halo blanc
|
| 645 |
+
d.text((x, y), t, font=f, fill=e["label_col"], stroke_width=3, stroke_fill=(255, 255, 255))
|
| 646 |
+
else:
|
| 647 |
+
d.text((x, y), t, font=f, fill=e["label_col"])
|
| 648 |
+
|
| 649 |
+
# --- villes et grands noms de régions (distracteurs)
|
| 650 |
+
for _ in range(rng.integers(0, 4)):
|
| 651 |
+
x, y = rng.uniform(20, R - 200), rng.uniform(20, R - 40)
|
| 652 |
+
d.ellipse([x - 5, y - 5, x + 5, y + 5], fill=(0, 0, 0), outline=(255, 255, 255))
|
| 653 |
+
d.text((x + 10, y - 14), _rname(rng), font=font(rng.choice(["sans", "ital"]), rng.uniform(18, 26)), fill=(20, 20, 20))
|
| 654 |
+
if rng.random() < 0.15:
|
| 655 |
+
t = _spaced(rng.choice(LAND_WORDS))
|
| 656 |
+
d.text((rng.uniform(0, R / 2), rng.uniform(0, R - 60)), t, font=font("bold", rng.uniform(28, 50)),
|
| 657 |
+
fill=(int(rng.integers(80, 140)), int(rng.integers(50, 90)), int(rng.integers(20, 60))))
|
| 658 |
+
|
| 659 |
+
# --- réduction x2 (anti-crénelage d'impression)
|
| 660 |
+
im = im.resize((TILE, TILE), Image.LANCZOS if rng.random() < .5 else Image.BOX)
|
| 661 |
+
|
| 662 |
+
# --- impression / numérisation
|
| 663 |
+
if e["scan"]:
|
| 664 |
+
a = np.asarray(im, np.float32)
|
| 665 |
+
paper = np.array([rng.uniform(238, 255), rng.uniform(230, 252), rng.uniform(205, 240)], np.float32) / 255
|
| 666 |
+
a = a * paper
|
| 667 |
+
gy, gx = np.mgrid[:TILE, :TILE] / TILE
|
| 668 |
+
a *= (1 - rng.uniform(0, 0.08) * (rng.uniform(-1, 1) * gx + rng.uniform(-1, 1) * gy))[..., None]
|
| 669 |
+
a = ndi.gaussian_filter(a, (rng.uniform(0.2, 0.9),) * 2 + (0,))
|
| 670 |
+
a = 255 * (np.clip(a, 0, 255) / 255) ** rng.uniform(0.85, 1.15)
|
| 671 |
+
a += rng.normal(0, rng.uniform(0.5, 4), a.shape)
|
| 672 |
+
if rng.random() < 0.2:
|
| 673 |
+
ch = rng.integers(3)
|
| 674 |
+
a[..., ch] = np.roll(a[..., ch], rng.choice([-1, 1]), axis=rng.integers(2))
|
| 675 |
+
im = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))
|
| 676 |
+
q = int(rng.integers(50, 92))
|
| 677 |
+
else:
|
| 678 |
+
q = int(rng.integers(80, 98)) if rng.random() < .5 else None
|
| 679 |
+
if q:
|
| 680 |
+
buf = io.BytesIO()
|
| 681 |
+
im.save(buf, "JPEG", quality=q)
|
| 682 |
+
im = Image.open(buf).convert("RGB")
|
| 683 |
+
return np.asarray(im, np.uint8), {k: (v if isinstance(v, (int, float, str, bool)) else str(v)) for k, v in e.items()}
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
# =====================================================================================
|
| 687 |
+
# ÉCHANTILLONNAGE SPATIAL (split train / val / test par blocs géographiques)
|
| 688 |
+
# =====================================================================================
|
| 689 |
+
class BlockSplit:
|
| 690 |
+
def __init__(self, src, block_m, seed, val=0.1, test=0.1, min_land=0.3):
|
| 691 |
+
x0, y0, x1, y1 = src.units.total_bounds
|
| 692 |
+
self.x0, self.y0, self.b = x0, y0, block_m
|
| 693 |
+
nx, ny = int(np.ceil((x1 - x0) / block_m)), int(np.ceil((y1 - y0) / block_m))
|
| 694 |
+
rng = np.random.default_rng(seed)
|
| 695 |
+
# part de terre de chaque bloc, sur un masque grossier (5 km)
|
| 696 |
+
cell = 5000.0
|
| 697 |
+
k = int(round(block_m / cell))
|
| 698 |
+
mask = rasterize(((g, 1) for g in src.units.geometry.values), out_shape=(ny * k, nx * k),
|
| 699 |
+
transform=from_origin(x0, y0 + ny * block_m, cell, cell), fill=0, dtype="uint8")
|
| 700 |
+
frac = mask.reshape(ny, k, nx, k).mean(axis=(1, 3))[::-1] # ligne 0 = sud
|
| 701 |
+
land = [(i, j) for i in range(nx) for j in range(ny) if frac[j, i] >= min_land]
|
| 702 |
+
order = rng.permutation(len(land))
|
| 703 |
+
n_val, n_test = max(1, round(val * len(land))), max(1, round(test * len(land)))
|
| 704 |
+
self.split = {}
|
| 705 |
+
for k, o in enumerate(order):
|
| 706 |
+
self.split[land[o]] = "validation" if k < n_val else ("test" if k < n_val + n_test else "train")
|
| 707 |
+
self.blocks = {s: [b for b, v in self.split.items() if v == s] for s in ("train", "validation", "test")}
|
| 708 |
+
|
| 709 |
+
def window_split(self, x0, y0, x1, y1):
|
| 710 |
+
i0, i1 = int((x0 - self.x0) // self.b), int((x1 - self.x0) // self.b)
|
| 711 |
+
j0, j1 = int((y0 - self.y0) // self.b), int((y1 - self.y0) // self.b)
|
| 712 |
+
s = {self.split.get((i, j), "none") for i in range(i0, i1 + 1) for j in range(j0, j1 + 1)}
|
| 713 |
+
s.discard("none")
|
| 714 |
+
return s.pop() if len(s) == 1 else None
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
def synth_tile(src, bs, split, rng, max_tries=60):
|
| 718 |
+
"""Tire une fenêtre entièrement contenue dans des blocs du split demandé, et la rend."""
|
| 719 |
+
lo, hi = src.px_range
|
| 720 |
+
for _ in range(max_tries):
|
| 721 |
+
hi_eff = min(hi, 0.9 * bs.b / TILE) # la fenêtre doit pouvoir tenir dans un bloc
|
| 722 |
+
px = float(np.exp(rng.uniform(np.log(min(lo, hi_eff)), np.log(hi_eff))))
|
| 723 |
+
ext = TILE * px
|
| 724 |
+
bi, bj = bs.blocks[split][rng.integers(len(bs.blocks[split]))]
|
| 725 |
+
if rng.random() < 0.5: # entièrement dans le bloc tiré
|
| 726 |
+
x0 = bs.x0 + bi * bs.b + rng.random() * (bs.b - ext)
|
| 727 |
+
y1 = bs.y0 + bj * bs.b + ext + rng.random() * (bs.b - ext)
|
| 728 |
+
else: # libre (peut déborder sur des blocs du même split)
|
| 729 |
+
cx = bs.x0 + (bi + rng.random()) * bs.b
|
| 730 |
+
cy = bs.y0 + (bj + rng.random()) * bs.b
|
| 731 |
+
x0, y1 = cx - rng.uniform(0.1, 0.9) * ext, cy + rng.uniform(0.1, 0.9) * ext
|
| 732 |
+
if bs.window_split(x0, y1 - ext, x0 + ext, y1) != split:
|
| 733 |
+
continue
|
| 734 |
+
U, win = raster_units(src, x0, y1, px / SS, R)
|
| 735 |
+
land = (U > 0).mean()
|
| 736 |
+
if land < src.min_land:
|
| 737 |
+
continue
|
| 738 |
+
nu = len(np.unique(U[U > 0]))
|
| 739 |
+
if nu < 2 or (nu < 4 and rng.random() < 0.6):
|
| 740 |
+
continue
|
| 741 |
+
lines = fault_lines_px(src, win, x0, y1, px / SS)
|
| 742 |
+
rgb, ed = render_map(src, U, lines, rng, px)
|
| 743 |
+
Uf = U[SS // 2::SS, SS // 2::SS]
|
| 744 |
+
inst = instances(Uf)
|
| 745 |
+
flt = faults_gt(lines, 1 / SS)
|
| 746 |
+
meta = {"bounds": [x0, y1 - ext, x0 + ext, y1], "px_size_m": px, "edition": ed}
|
| 747 |
+
return rgb, inst, Uf, flt, meta
|
| 748 |
+
return None
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
def inst_units(src, inst, Uf):
|
| 752 |
+
"""Pour chaque instance : son unité (code, âge, lithologie)."""
|
| 753 |
+
n = int(inst.max())
|
| 754 |
+
if n == 0:
|
| 755 |
+
return {}
|
| 756 |
+
uid = ndi.maximum(Uf, inst, np.arange(1, n + 1)).astype(int)
|
| 757 |
+
return {str(i + 1): src.unit_meta(u) for i, u in enumerate(uid)}
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
# =====================================================================================
|
| 761 |
+
# ENCODAGE (format publiable : PNG dans Parquet)
|
| 762 |
+
# =====================================================================================
|
| 763 |
+
def png_bytes(arr, mode=None):
|
| 764 |
+
buf = io.BytesIO()
|
| 765 |
+
if arr.dtype == np.uint16 or mode == "I;16":
|
| 766 |
+
Image.fromarray(arr.astype(np.uint16)).save(buf, "PNG", optimize=False)
|
| 767 |
+
else:
|
| 768 |
+
Image.fromarray(arr).save(buf, "PNG", optimize=False)
|
| 769 |
+
return buf.getvalue()
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
def make_record(tid, source, continent, kind, split, crs, rgb, inst, flt, meta, units):
|
| 773 |
+
if inst.max() > 65535:
|
| 774 |
+
raise ValueError("trop d'instances")
|
| 775 |
+
return {
|
| 776 |
+
"id": tid, "source": source, "continent": continent, "kind": kind, "split": split,
|
| 777 |
+
"image": {"bytes": png_bytes(rgb), "path": f"{tid}.png"},
|
| 778 |
+
"instances": {"bytes": png_bytes(inst.astype(np.uint16)), "path": f"{tid}_inst.png"},
|
| 779 |
+
"faults": {"bytes": png_bytes((flt > 0).astype(np.uint8) * 255), "path": f"{tid}_faults.png"},
|
| 780 |
+
"n_instances": int(inst.max()),
|
| 781 |
+
"land_fraction": float((inst > 0).mean()),
|
| 782 |
+
"fault_pixels": int((flt > 0).sum()),
|
| 783 |
+
"px_size_m": float(meta["px_size_m"]),
|
| 784 |
+
"crs": str(crs),
|
| 785 |
+
"bounds": [float(v) for v in meta["bounds"]],
|
| 786 |
+
"units": json.dumps(units, ensure_ascii=False),
|
| 787 |
+
"render": json.dumps(meta.get("edition", {}), ensure_ascii=False),
|
| 788 |
+
}
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
# =====================================================================================
|
| 792 |
+
# CONSTRUCTION DU DATASET UNIQUE (réel + synthétique, 4 continents) -> Parquet
|
| 793 |
+
# =====================================================================================
|
| 794 |
+
import os, time, multiprocessing as mp
|
| 795 |
+
import pyarrow as pa
|
| 796 |
+
import pyarrow.parquet as pq
|
| 797 |
+
import rasterio
|
| 798 |
+
from rasterio.windows import Window
|
| 799 |
+
|
| 800 |
+
SPLITS = ("train", "validation", "test")
|
| 801 |
+
_IMG = pa.struct([("bytes", pa.binary()), ("path", pa.string())])
|
| 802 |
+
_FIELDS = [("id", pa.string()), ("source", pa.string()), ("continent", pa.string()), ("kind", pa.string()),
|
| 803 |
+
("split", pa.string()), ("image", _IMG), ("instances", _IMG), ("faults", _IMG),
|
| 804 |
+
("n_instances", pa.int32()), ("land_fraction", pa.float32()), ("fault_pixels", pa.int32()),
|
| 805 |
+
("px_size_m", pa.float32()), ("crs", pa.string()), ("bounds", pa.list_(pa.float64())),
|
| 806 |
+
("units", pa.string()), ("render", pa.string())]
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def arrow_schema():
|
| 810 |
+
"""Schéma Parquet + métadonnées 'huggingface' (le viewer HF affiche alors les images)."""
|
| 811 |
+
try:
|
| 812 |
+
from datasets import Features, Value, Image as HFImage, Sequence
|
| 813 |
+
f = Features({"id": Value("string"), "source": Value("string"), "continent": Value("string"),
|
| 814 |
+
"kind": Value("string"), "split": Value("string"), "image": HFImage(),
|
| 815 |
+
"instances": HFImage(), "faults": HFImage(), "n_instances": Value("int32"),
|
| 816 |
+
"land_fraction": Value("float32"), "fault_pixels": Value("int32"),
|
| 817 |
+
"px_size_m": Value("float32"), "crs": Value("string"), "bounds": Sequence(Value("float64")),
|
| 818 |
+
"units": Value("string"), "render": Value("string")})
|
| 819 |
+
return f.arrow_schema
|
| 820 |
+
except Exception as ex:
|
| 821 |
+
print("datasets indisponible, schéma sans métadonnées HF :", ex)
|
| 822 |
+
return pa.schema(_FIELDS)
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
class ShardWriter:
|
| 826 |
+
def __init__(self, out_dir, shard_rows=500):
|
| 827 |
+
self.dir = Path(out_dir) / "data"
|
| 828 |
+
self.dir.mkdir(parents=True, exist_ok=True)
|
| 829 |
+
self.schema, self.n = arrow_schema(), shard_rows
|
| 830 |
+
self.buf = {s: [] for s in SPLITS}
|
| 831 |
+
self.k = {s: 0 for s in SPLITS}
|
| 832 |
+
self.count = {s: 0 for s in SPLITS}
|
| 833 |
+
self.index = []
|
| 834 |
+
|
| 835 |
+
def add(self, rec):
|
| 836 |
+
s = rec["split"]
|
| 837 |
+
self.buf[s].append(rec)
|
| 838 |
+
self.count[s] += 1
|
| 839 |
+
self.index.append({k: rec[k] for k in ("id", "source", "continent", "kind", "split", "n_instances",
|
| 840 |
+
"land_fraction", "fault_pixels", "px_size_m")})
|
| 841 |
+
if len(self.buf[s]) >= self.n:
|
| 842 |
+
self.flush(s)
|
| 843 |
+
|
| 844 |
+
def flush(self, s):
|
| 845 |
+
if not self.buf[s]:
|
| 846 |
+
return
|
| 847 |
+
cols = {name: [r[name] for r in self.buf[s]] for name in self.schema.names}
|
| 848 |
+
tbl = pa.Table.from_pydict(cols, schema=self.schema)
|
| 849 |
+
pq.write_table(tbl, self.dir / f"{s}-{self.k[s]:05d}.parquet", compression="zstd")
|
| 850 |
+
self.k[s] += 1
|
| 851 |
+
self.buf[s] = []
|
| 852 |
+
|
| 853 |
+
def close(self):
|
| 854 |
+
for s in SPLITS:
|
| 855 |
+
self.flush(s)
|
| 856 |
+
df = pd.DataFrame(self.index)
|
| 857 |
+
df.to_csv(self.dir.parent / "index.csv", index=False)
|
| 858 |
+
return df
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
def real_tiles(raster_path, src, bs, name, writer, easy_frac=0.2, min_cover=0.5, seed=0):
|
| 862 |
+
"""Tuiles réelles (scan + vecteurs alignés), grille sans recouvrement, split par blocs géographiques."""
|
| 863 |
+
t0 = time.time()
|
| 864 |
+
rng = np.random.default_rng(seed)
|
| 865 |
+
with rasterio.open(raster_path) as s:
|
| 866 |
+
cands = []
|
| 867 |
+
for r in range(0, s.height - TILE + 1, TILE):
|
| 868 |
+
for c in range(0, s.width - TILE + 1, TILE):
|
| 869 |
+
win = Window(c, r, TILE, TILE)
|
| 870 |
+
x0, y0, x1, y1 = rasterio.windows.bounds(win, s.transform)
|
| 871 |
+
split = bs.window_split(x0, y0, x1, y1)
|
| 872 |
+
if split is None:
|
| 873 |
+
continue
|
| 874 |
+
rgb = np.transpose(s.read([1, 2, 3], window=win), (1, 2, 0))
|
| 875 |
+
if rgb.mean() > 248 or rgb.mean() < 5:
|
| 876 |
+
continue
|
| 877 |
+
tr = rasterio.windows.transform(win, s.transform)
|
| 878 |
+
U, w = raster_units(src, tr.c, tr.f, tr.a, TILE)
|
| 879 |
+
if (U > 0).mean() < min_cover:
|
| 880 |
+
continue
|
| 881 |
+
nu = len(np.unique(U[U > 0]))
|
| 882 |
+
lines = fault_lines_px(src, w, tr.c, tr.f, tr.a)
|
| 883 |
+
nf = int(faults_gt(lines, 1.0).sum())
|
| 884 |
+
cands.append((r, c, split, nu >= 3 or nf > 30))
|
| 885 |
+
rich = [k for k in cands if k[3]]
|
| 886 |
+
easy = [k for k in cands if not k[3]]
|
| 887 |
+
n_easy = min(len(easy), int(round(easy_frac / (1 - easy_frac) * len(rich))))
|
| 888 |
+
easy = [easy[i] for i in rng.choice(len(easy), n_easy, replace=False)] if n_easy else []
|
| 889 |
+
n = {sp: 0 for sp in SPLITS}
|
| 890 |
+
for r, c, split, _ in rich + easy:
|
| 891 |
+
win = Window(c, r, TILE, TILE)
|
| 892 |
+
tr = rasterio.windows.transform(win, s.transform)
|
| 893 |
+
rgb = np.ascontiguousarray(np.transpose(s.read([1, 2, 3], window=win), (1, 2, 0)))
|
| 894 |
+
U, w = raster_units(src, tr.c, tr.f, tr.a, TILE)
|
| 895 |
+
lines = fault_lines_px(src, w, tr.c, tr.f, tr.a)
|
| 896 |
+
inst, flt = instances(U), faults_gt(lines, 1.0)
|
| 897 |
+
meta = {"bounds": list(rasterio.windows.bounds(win, s.transform)), "px_size_m": abs(tr.a),
|
| 898 |
+
"edition": {"raster": Path(raster_path).name, "row": r, "col": c}}
|
| 899 |
+
writer.add(make_record(f"{name}_r{r}_c{c}", src.name, src.continent, "real", split, src.crs,
|
| 900 |
+
rgb, inst, flt, meta, inst_units(src, inst, U)))
|
| 901 |
+
n[split] += 1
|
| 902 |
+
print(f" {name} : {sum(n.values())} tuiles réelles {n} en {time.time() - t0:.0f} s", flush=True)
|
| 903 |
+
return n
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
_SOURCES, _SPLITTERS = {}, {}
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def _synth_job(job):
|
| 910 |
+
name, split, i, seed = job
|
| 911 |
+
src, bs = _SOURCES[name], _SPLITTERS[name]
|
| 912 |
+
rng = np.random.default_rng(seed)
|
| 913 |
+
for _ in range(30):
|
| 914 |
+
res = synth_tile(src, bs, split, rng)
|
| 915 |
+
if res is not None:
|
| 916 |
+
rgb, inst, Uf, flt, meta = res
|
| 917 |
+
tid = f"{src.name}_synth_{split}_{i:05d}"
|
| 918 |
+
return make_record(tid, src.name, src.continent, "synthetic", split, src.crs, rgb, inst, flt, meta,
|
| 919 |
+
inst_units(src, inst, Uf))
|
| 920 |
+
return None
|
| 921 |
+
|
| 922 |
+
|
| 923 |
+
def build_synthetic(sources, splitters, counts, writer, val=0.1, test=0.1, seed=2026, workers=None):
|
| 924 |
+
_SOURCES.update(sources)
|
| 925 |
+
_SPLITTERS.update(splitters)
|
| 926 |
+
jobs = []
|
| 927 |
+
for name, n in counts.items():
|
| 928 |
+
if name not in sources:
|
| 929 |
+
continue
|
| 930 |
+
per = {"validation": int(round(n * val)), "test": int(round(n * test))}
|
| 931 |
+
per["train"] = n - per["validation"] - per["test"]
|
| 932 |
+
for split, k in per.items():
|
| 933 |
+
jobs += [(name, split, i, _seed(seed, name, split, i)) for i in range(k)]
|
| 934 |
+
np.random.default_rng(seed).shuffle(jobs)
|
| 935 |
+
workers = workers or os.cpu_count()
|
| 936 |
+
t0, done, fail = time.time(), 0, 0
|
| 937 |
+
ctx = mp.get_context("fork")
|
| 938 |
+
with ctx.Pool(workers) as pool:
|
| 939 |
+
for rec in pool.imap_unordered(_synth_job, jobs, chunksize=4):
|
| 940 |
+
if rec is None:
|
| 941 |
+
fail += 1
|
| 942 |
+
continue
|
| 943 |
+
writer.add(rec)
|
| 944 |
+
done += 1
|
| 945 |
+
if done % 250 == 0:
|
| 946 |
+
el = time.time() - t0
|
| 947 |
+
print(f" synthétique : {done}/{len(jobs)} ({el:.0f} s, reste ~{el / done * (len(jobs) - done):.0f} s)", flush=True)
|
| 948 |
+
print(f" synthétique terminé : {done} tuiles, {fail} échecs, {time.time() - t0:.0f} s", flush=True)
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def decode(rec):
|
| 952 |
+
"""Ligne Parquet -> (rgb uint8 HxWx3, inst int32 HxW, faults uint8 HxW {0,1}). Utilisé à l'entraînement."""
|
| 953 |
+
rgb = np.asarray(Image.open(io.BytesIO(rec["image"]["bytes"])).convert("RGB"))
|
| 954 |
+
inst = np.asarray(Image.open(io.BytesIO(rec["instances"]["bytes"]))).astype(np.int32)
|
| 955 |
+
flt = (np.asarray(Image.open(io.BytesIO(rec["faults"]["bytes"]))) > 0).astype(np.uint8)
|
| 956 |
+
return rgb, inst, flt
|
index.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
preview.png
ADDED
|
Git LFS Details
|