Kuangdai commited on
Commit
b8bc5ba
·
0 Parent(s):

Initial release of ERP-GPT-EU

Browse files
.gitattributes ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
3
+ data_api/*.pkl filter=lfs diff=lfs merge=lfs -text
4
+ data_api/*.csv filter=lfs diff=lfs merge=lfs -text
5
+ data_api/*.json filter=lfs diff=lfs merge=lfs -text
6
+ gpt_resources/*.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ .idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
175
+
176
+ # Cursor
177
+ # Cursor is an AI-powered code editor.`.cursorignore` specifies files/directories to
178
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
179
+ # refer to https://docs.cursor.com/context/ignore-files
180
+ .cursorignore
181
+ .cursorindexingignore
182
+
183
+ .DS_Store
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Kuangdai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ERP-GPT-EU
2
+
3
+ This repository includes the data and code needed to deploy **[ERP-GPT-EU](https://chatgpt.com/g/g-690a45283b0081918ef79f0d2ab8964e-erp-gpt-eu)**, a tool-augmented GPT for querying and interpreting high-resolution European soil data.
4
+
5
+ ERP-GPT-EU combines geographic resolution based on European GADM administrative regions with soil data access from the **LUCAS-MEGA** fused dataset. It can resolve user-specified places or coordinates, retrieve relevant soil properties, and generate soil data outputs through an API server. The GPT is designed for users such as soil scientists, agronomists, land managers, policymakers, and data analysts.
6
+
7
+ The repository contains both the backend API server and the GPT configuration resources. The API server provides access to local soil and geographic data files, while the `gpt_resources` directory contains the prompt, knowledge file, OpenAPI schema, icon, and starting questions needed to configure the custom GPT.
8
+
9
+ # Deployment
10
+
11
+ ## API Server
12
+
13
+ Install the required Python packages:
14
+
15
+ ```bash
16
+ pip install -r requirements.txt
17
+ ```
18
+
19
+ Start the API server:
20
+
21
+ ```bash
22
+ python app.py --port=<PORT>
23
+ ```
24
+
25
+ For local debugging, you can expose the server through a temporary public tunnel. For example, using `localtunnel`:
26
+
27
+ ```bash
28
+ npx localtunnel --port <PORT>
29
+ ```
30
+
31
+ This will return a public URL such as:
32
+
33
+ ```text
34
+ https://your-subdomain.loca.lt
35
+ ```
36
+
37
+ Use this public URL when configuring the GPT action schema.
38
+
39
+ ## GPT Setup
40
+
41
+ Go to [ChatGPT](https://chatgpt.com/) and create a custom GPT.
42
+
43
+ Use the files in `gpt_resources/` to set up the GPT:
44
+
45
+ ```text
46
+ gpt_resources/
47
+ ├── icon.png
48
+ ├── knowledge.md
49
+ ├── prompt.md
50
+ ├── schema.json
51
+ └── starts.md
52
+ ```
53
+
54
+ File descriptions:
55
+
56
+ * `schema.json` (most important): the OpenAPI schema for GPT Actions. In the OpenAI custom GPT setup, this file defines the API endpoints that the GPT can call, including input parameters, response formats, and the public server URL.
57
+ * `prompt.md` (most important): the top-level instructions for the GPT. In the OpenAI custom GPT setup, this content should be placed in the Instructions field. It defines the GPT's role, behavior, tool-use rules, response style, and constraints.
58
+ * `knowledge.md`: the knowledge file uploaded to the GPT. In the OpenAI custom GPT setup, this file provides reference material that the GPT can search when answering questions. It should describe the dataset, available soil variables, geographic scope, terminology, and important usage notes.
59
+ * `icon.png`: icon for the GPT.
60
+ * `starts.md`: starting questions for users.
61
+
62
+ Before uploading or pasting `schema.json`, replace the default server URL:
63
+
64
+ ```json
65
+ {
66
+ "servers": [
67
+ {
68
+ "url": "https://api.erp-soilgpt.uk/"
69
+ }
70
+ ]
71
+ }
72
+ ```
73
+
74
+ with your own public API server address, for example:
75
+
76
+ ```json
77
+ {
78
+ "servers": [
79
+ {
80
+ "url": "https://your-subdomain.loca.lt/"
81
+ }
82
+ ]
83
+ }
84
+ ```
85
+
86
+ After saving the GPT configuration, test it with a simple soil or location query to confirm that the GPT can call your API server successfully.
app.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from flask import Flask, request, jsonify
4
+
5
+ from data_utils import LUCASSoilData
6
+ from gadm_utils import GADMHandler
7
+ from geo_utils import resolve_place
8
+
9
+ app = Flask(__name__, static_folder="plots", static_url_path="/plots")
10
+
11
+ gadm_handler = GADMHandler("data_api/gadm_tree_europe.pkl")
12
+ soil_data = LUCASSoilData(table_path="data_api/data_table.csv",
13
+ dict_path="data_api/data_dict.pkl",
14
+ column_names_path="data_api/meta_column_names.json",
15
+ gadm_handler=gadm_handler)
16
+
17
+
18
+ # --- geo_utils API ---
19
+ @app.route("/resolve_place", methods=["POST"])
20
+ def api_resolve_place():
21
+ data = request.json
22
+ print("resolve_place input:", data)
23
+ result = resolve_place(
24
+ data.get("place_name"),
25
+ data.get("fallback"),
26
+ data.get("session_name")
27
+ )
28
+ print("resolve_place output:", result)
29
+ return jsonify(result)
30
+
31
+
32
+ @app.route("/gadm/find_gid", methods=["POST"])
33
+ def api_gadm_find_gid():
34
+ data = request.json
35
+ print("find_gid input:", data)
36
+ lat = data["lat"]
37
+ lon = data["lon"]
38
+ bbox_area = data.get("bbox_area")
39
+ return_all = data.get("return_all", False)
40
+
41
+ result = gadm_handler.find_gid(lat, lon, bbox_area, return_all)
42
+ print("find_gid output:", result)
43
+
44
+ if result is None or (isinstance(result, list) and not result):
45
+ return jsonify({
46
+ "status": "Failed. No matching GADM region found.",
47
+ "gid": None
48
+ })
49
+
50
+ if return_all:
51
+ return jsonify({
52
+ "status": f"Success. Found {len(result)} matching regions.",
53
+ "gids": result
54
+ })
55
+ else:
56
+ return jsonify({
57
+ "status": "Success. Found best matching region.",
58
+ "gid": result
59
+ })
60
+
61
+
62
+ @app.route("/gadm/get_full_name", methods=["POST"])
63
+ def api_gadm_get_full_name():
64
+ data = request.json
65
+ print("get_full_name input:", data)
66
+ gid = data.get("gid")
67
+ result = gadm_handler.get_full_name(gid)
68
+ output = {
69
+ "status": "Success. Full hierarchical name found." if result else f"Failed. GID '{gid}' not found.",
70
+ "full_name": result
71
+ }
72
+ print("get_full_name output:", output)
73
+ return jsonify(output)
74
+
75
+
76
+ @app.route("/gadm/get_geometry_info", methods=["POST"])
77
+ def api_gadm_geometry_info():
78
+ data = request.json
79
+ print("get_geometry_info input:", data)
80
+ gid = data.get("gid")
81
+ result = gadm_handler.get_geometry_info(gid)
82
+ if result is None:
83
+ output = {
84
+ "status": f"Failed. GID '{gid}' not found or has no geometry.",
85
+ "latitude": None,
86
+ "longitude": None,
87
+ "bbox_bounds": None,
88
+ "polygon_area": None,
89
+ "bbox_area": None
90
+ }
91
+ else:
92
+ output = {
93
+ "status": "Success. Geometry information retrieved.",
94
+ **result
95
+ }
96
+ print("get_geometry_info output:", output)
97
+ return jsonify(output)
98
+
99
+
100
+ @app.route("/gadm/get_tree_info", methods=["POST"])
101
+ def api_gadm_tree_info():
102
+ data = request.json
103
+ print("get_tree_info input:", data)
104
+ gid = data.get("gid")
105
+ result = gadm_handler.get_tree_info(gid)
106
+ if result is None:
107
+ output = {
108
+ "status": f"Failed. GID '{gid}' not found.",
109
+ "level": None,
110
+ "parent": None,
111
+ "children": None,
112
+ "siblings": None
113
+ }
114
+ else:
115
+ output = {
116
+ "status": "Success. Tree information retrieved.",
117
+ **result
118
+ }
119
+ print("get_tree_info output:", output)
120
+ return jsonify(output)
121
+
122
+
123
+ @app.route("/gadm/get_quick_summary", methods=["POST"])
124
+ def api_gadm_quick_summary():
125
+ data = request.json
126
+ print("get_quick_summary input:", data)
127
+ gid = data.get("gid")
128
+ summary = gadm_handler.quick_summary(gid)
129
+ status = "Success" if not summary.startswith("Invalid GID") else "Failed"
130
+ output = {"summary": summary, "status": status}
131
+ print("get_quick_summary output:", output)
132
+ return jsonify(output)
133
+
134
+
135
+ # --- ISDASoilData APIs ---
136
+ @app.route("/soil/get_point", methods=["POST"])
137
+ def api_soil_get_point():
138
+ data = request.json
139
+ print("get_point input:", data)
140
+
141
+ data = request.get_json(silent=True) or {}
142
+ place = data.get("place")
143
+ properties = data.get("properties")
144
+ if place is None or not isinstance(properties, list) or len(properties) == 0:
145
+ return jsonify({
146
+ "query_input": {"place": place, "properties": properties, "session_name": data.get("session_name")},
147
+ "query_status": "Failed. Missing required fields: 'place' and non-empty 'properties'.",
148
+ "query_output": {}
149
+ }), 400
150
+
151
+ # Use server-side defaults if client omitted them
152
+ distance_top_k = int(data.get("distance_top_k", 20))
153
+ distance_limit = float(data.get("distance_limit", 200000))
154
+ session_name = data.get("session_name")
155
+
156
+ result = soil_data.get_point(
157
+ place=place,
158
+ properties=properties,
159
+ distance_top_k=distance_top_k,
160
+ distance_limit=distance_limit,
161
+ session_name=session_name,
162
+ )
163
+ print("get_point output:", result)
164
+ return jsonify(result)
165
+
166
+
167
+ @app.route("/soil/get_map", methods=["POST"])
168
+ def api_soil_get_map():
169
+ data = request.get_json(silent=True) or {}
170
+ print("get_map input:", data)
171
+
172
+ place = data.get("place")
173
+ properties = data.get("properties") or []
174
+ session_name = data.get("session_name")
175
+ kwargs = data.get("kwargs") or {}
176
+
177
+ # Basic input validation (mirror API contract)
178
+ if not session_name:
179
+ return jsonify({
180
+ "query_input": {"place": place, "properties": properties, "session_name": session_name},
181
+ "query_status": "Failed. Missing required field: session_name.",
182
+ "query_output": {}
183
+ }), 400
184
+ if place is None:
185
+ return jsonify({
186
+ "query_input": {"place": place, "properties": properties, "session_name": session_name},
187
+ "query_status": "Failed. Missing required field: place.",
188
+ "query_output": {}
189
+ }), 400
190
+ if not isinstance(properties, list) or len(properties) == 0:
191
+ return jsonify({
192
+ "query_input": {"place": place, "properties": properties, "session_name": session_name},
193
+ "query_status": "Failed. properties must be a non-empty list.",
194
+ "query_output": {}
195
+ }), 400
196
+
197
+ # Call core API
198
+ result = soil_data.get_map(place=place, properties=properties, session_name=session_name, **kwargs)
199
+ print("get_map raw output:", result.get("query_output", {}))
200
+
201
+ # Convert local file paths to public URLs under /plots/<session_name>/
202
+ try:
203
+ qo = result.get("query_output", {})
204
+ for label, path in list(qo.items()):
205
+ if isinstance(path, str) and path.endswith(".png") and os.path.exists(path):
206
+ filename = os.path.basename(path)
207
+ # app.static_url_path is "/plots"
208
+ public_url = f"{request.url_root.rstrip('/')}{app.static_url_path}/{session_name}/{filename}"
209
+ result["query_output"][label] = public_url
210
+ except Exception as e:
211
+ # Do not fail the whole response; annotate status
212
+ result["query_status"] = f"{result.get('query_status', 'Success')}\nNote: Failed to rewrite some URLs: {e}"
213
+
214
+ print("get_map with URLs:", result.get("query_output", {}))
215
+ return jsonify(result)
216
+
217
+
218
+ @app.route("/health", methods=["GET"])
219
+ def health_check():
220
+ print("health_check called")
221
+ return jsonify({"status": "OK"})
222
+
223
+
224
+ if __name__ == "__main__":
225
+ import argparse
226
+
227
+ parser = argparse.ArgumentParser(description="Run Soil API server")
228
+ parser.add_argument(
229
+ "--host", default="0.0.0.0",
230
+ help="Host to bind (default: 0.0.0.0)"
231
+ )
232
+ parser.add_argument(
233
+ "--port", type=int, default=5050,
234
+ help="Port to listen on (default: 5050)"
235
+ )
236
+ args = parser.parse_args()
237
+
238
+ app.run(host=args.host, port=args.port)
data_api/data_dict.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b42ad2a1a1e8c092059c1b22e1589177e1ba70763bc232b91d1595189505aaef
3
+ size 3934696791
data_api/data_table.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:62276e90b45937fc626b5c8d4318ce152a4553b4b399680662675378b2d1defb
3
+ size 722519601
data_api/gadm_tree_europe.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:443cfde775d41e9ee1cce5ee68ba0701983f4491201369cf888af698543b5dc9
3
+ size 1782553909
data_api/meta_column_complete.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8eb79fcbcac181504c20099857462c2323dadb8a8bda9423916475ccf9025f5
3
+ size 952082
data_api/meta_column_names.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7d36b9bfe39e32c1959c3ef24b0963a990cb86b0c13b93416a92e3fdd8ef6382
3
+ size 58158
data_api/meta_fused_datasets.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c48ce61060459cca00ea32b475a4ce8ef44634bd1f5cb69eac723a5dfe70b1f2
3
+ size 33181
data_utils.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import pickle
3
+ from typing import Tuple, Optional, List, Dict, Any
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from geopy.distance import geodesic
8
+
9
+ from gadm_utils import GADMHandler
10
+ from geo_utils import resolve_place
11
+ from plot_utils import scatter_plot
12
+ import ast
13
+
14
+ class LUCASSoilData:
15
+ def __init__(self, table_path: str, dict_path: str,
16
+ column_names_path: str,
17
+ gadm_handler: GADMHandler) -> None:
18
+
19
+ self.df = pd.read_csv(table_path, low_memory=False)
20
+ self.df["LAT_LONG"] = self.df["LAT_LONG"].apply(
21
+ lambda x: ast.literal_eval(x) if isinstance(x, str) else x
22
+ )
23
+
24
+ with open(column_names_path, 'r') as f:
25
+ self.column_names = json.load(f)["column_names"]
26
+
27
+ self.property_map = {}
28
+ for full_name in self.column_names:
29
+ base, unit = full_name.split("(", maxsplit=1) if "(" in full_name else (full_name, None)
30
+ if unit is not None:
31
+ unit = unit[:-1].strip() # remove trailing ")"
32
+
33
+ theme, prop = [x.strip() for x in base.split(":", 1)]
34
+ self.property_map[prop] = (full_name, theme, unit)
35
+
36
+ with open(dict_path, 'rb') as f:
37
+ self.sample_dict = pickle.load(f)
38
+
39
+ self.gadm_handler = gadm_handler
40
+
41
+ def resolve_theme_property_unit(self, input_string: str) -> Tuple[str, str, str, Optional[str]]:
42
+ """
43
+ Resolve and return (full_name, theme, property, unit) from a user input string.
44
+ The user may provide:
45
+ - full form: "theme:property (unit)"
46
+ - partial form: "theme:property"
47
+ - property only: "property"
48
+ """
49
+
50
+ input_string = input_string.strip()
51
+
52
+ # Extract unit if present
53
+ if "(" in input_string:
54
+ base, input_unit = input_string.split("(", maxsplit=1)
55
+ input_unit = input_unit[:-1].strip() # remove trailing ")"
56
+ else:
57
+ base, input_unit = input_string, None
58
+
59
+ # Extract theme + property
60
+ if ":" in base:
61
+ input_theme, input_property = [x.strip() for x in base.split(":", 1)]
62
+ else:
63
+ input_theme, input_property = None, base.strip()
64
+
65
+ # Property must exist
66
+ if input_property not in self.property_map:
67
+ raise ValueError(f"Property '{input_property}' not found in dataset.")
68
+
69
+ full_name, expected_theme, expected_unit = self.property_map[input_property]
70
+
71
+ # Validate theme if user supplied one
72
+ if input_theme is not None and input_theme != expected_theme:
73
+ raise ValueError(f"Theme mismatch: expected '{expected_theme}', got '{input_theme}'.")
74
+
75
+ # Validate unit if user supplied one
76
+ if input_unit is not None and input_unit != expected_unit:
77
+ raise ValueError(f"Unit mismatch for '{input_property}': expected '{expected_unit}', got '{input_unit}'.")
78
+
79
+ return full_name, expected_theme, input_property, expected_unit
80
+
81
+ def get_point(self,
82
+ place: str | tuple[float, float],
83
+ properties: List[str],
84
+ distance_top_k: int = 20,
85
+ distance_limit: float = 200000,
86
+ session_name: Optional[str] = None) -> Dict[str, Any]:
87
+ """
88
+ Retrieve soil data near a place, selecting the best among top-k nearest samples.
89
+
90
+ Rules:
91
+ 1) Find top-k nearest samples (by squared distance, then geodesic meters).
92
+ 2) Exclude samples farther than `distance_limit` (meters).
93
+ 3) From remaining samples, choose the one with the most valid properties.
94
+ (valid = property exists AND sample[...] has non-None "value").
95
+ Tie-break: smaller distance wins.
96
+ 4) If all survivors have zero valid properties, return Failed.
97
+ 5) Resolver is strict: if user requests an unknown property, immediate Failed.
98
+
99
+ Output always contains `query_input` and `query_status`. Sample data is
100
+ included only for success or partial success cases.
101
+ """
102
+
103
+ # always include input record in response
104
+ query_input = {
105
+ "place": place,
106
+ "properties": properties,
107
+ "distance_limit": distance_limit,
108
+ "distance_top_k": distance_top_k,
109
+ }
110
+
111
+ # ---------- Resolve place → (lat, lon) ----------
112
+ try:
113
+ if isinstance(place, str):
114
+ if place not in self.gadm_handler.tree:
115
+ resolved = resolve_place(place, session_name=session_name, gadm_handler=self.gadm_handler)
116
+ gid = resolved.get("gid")
117
+ if gid is None:
118
+ return {
119
+ "query_input": query_input,
120
+ "query_status": f"Failed. Cannot resolve place: {place}",
121
+ "query_output": {}
122
+ }
123
+ else:
124
+ gid = place
125
+
126
+ geom_info = self.gadm_handler.get_geometry_info(gid)
127
+ if geom_info is None:
128
+ return {
129
+ "query_input": query_input,
130
+ "query_status": f"Failed. Cannot get geometry for place (GID): {place} ({gid})",
131
+ "query_output": {}
132
+ }
133
+
134
+ lat, lon = geom_info["latitude"], geom_info["longitude"]
135
+ else:
136
+ lat, lon = place
137
+ except Exception as e:
138
+ return {
139
+ "query_input": query_input,
140
+ "query_status": f"Failed. {str(e)}",
141
+ "query_output": {}
142
+ }
143
+
144
+ # ---------- Strict property resolution (fail if any invalid) ----------
145
+ resolved_props = []
146
+ try:
147
+ for input_prop in properties:
148
+ full_name, theme, prop, unit = self.resolve_theme_property_unit(input_prop)
149
+ resolved_props.append((theme, prop, input_prop))
150
+ except Exception as e:
151
+ return {
152
+ "query_input": query_input,
153
+ "query_status": f"Failed. {str(e)}",
154
+ "query_output": {}
155
+ }
156
+
157
+ # ---------- Find top-k nearest candidates ----------
158
+ try:
159
+ latlon = np.vstack(self.df["LAT_LONG"].values).astype(float) # (N, 2)
160
+ d2 = (latlon[:, 0] - lat) ** 2 + (latlon[:, 1] - lon) ** 2
161
+
162
+ k = max(1, min(distance_top_k, len(d2)))
163
+ idx_k = np.argpartition(d2, kth=k - 1)[:k]
164
+
165
+ candidates = []
166
+ for idx in idx_k:
167
+ sample_lat, sample_lon = latlon[idx]
168
+ dist_m = geodesic((lat, lon), (sample_lat, sample_lon)).meters
169
+ candidates.append((idx, dist_m))
170
+
171
+ survivors = [(idx, dist_m) for (idx, dist_m) in candidates if dist_m <= distance_limit]
172
+ if not survivors:
173
+ return {
174
+ "query_input": query_input,
175
+ "query_status": f"Failed. No nearby samples within {distance_limit:g} m.",
176
+ "query_output": {}
177
+ }
178
+
179
+ except Exception as e:
180
+ return {
181
+ "query_input": query_input,
182
+ "query_status": f"Failed. Error during nearest-point search: {str(e)}",
183
+ "query_output": {}
184
+ }
185
+
186
+ # ---------- Score survivors by valid property count, then distance ----------
187
+ def count_valid(idx: int) -> int:
188
+ row = self.df.iloc[idx]
189
+ src = self.sample_dict.get(row["id"], {})
190
+ valid = 0
191
+ for theme, prop, _orig in resolved_props:
192
+ try:
193
+ val = src[theme][prop]["value"]
194
+ if val is not None:
195
+ valid += 1
196
+ except Exception:
197
+ pass
198
+ return valid
199
+
200
+ scored = [(idx, dist, count_valid(idx)) for idx, dist in survivors]
201
+ scored.sort(key=lambda x: (-x[2], x[1])) # most valid props, then nearest
202
+ best_idx, best_dist, best_valid = scored[0]
203
+
204
+ if best_valid == 0:
205
+ return {
206
+ "query_input": query_input,
207
+ "query_status": (
208
+ "Failed. No sample within "
209
+ f"{distance_limit:g} m contains any of the requested properties."
210
+ ),
211
+ "query_output": {}
212
+ }
213
+
214
+ # ---------- Build result for best candidate ----------
215
+ try:
216
+ row = self.df.iloc[best_idx]
217
+ source = self.sample_dict[row["id"]]
218
+ except Exception:
219
+ return {
220
+ "query_input": query_input,
221
+ "query_status": f"Failed. Sample data missing for best candidate.",
222
+ "query_output": {}
223
+ }
224
+
225
+ result = {}
226
+ for key in ["LAT_LONG", "GADM_IDS", "GADM_NAMES", "COUNTRY_CODE",
227
+ "SAMPLE_DATE", "SAMPLE_DEPTH_RANGE_CM", "SAMPLE_SOURCE_DATASET"]:
228
+ result[key] = source.get(key)
229
+
230
+ failed_props = []
231
+ for theme, prop, original_input in resolved_props:
232
+ try:
233
+ val = source[theme][prop]["value"]
234
+ if val is not None:
235
+ if theme not in result:
236
+ result[theme] = {}
237
+ result[theme][prop] = val
238
+ else:
239
+ failed_props.append(original_input)
240
+ except Exception:
241
+ failed_props.append(original_input)
242
+
243
+ if failed_props and len(failed_props) < len(resolved_props):
244
+ status = (
245
+ "Partial success. Some properties were not available: "
246
+ + ", ".join(failed_props)
247
+ + f". Distance to nearest sample (m): {best_dist:.1f}."
248
+ )
249
+ else:
250
+ status = f"Success. Distance to nearest sample (m): {best_dist:.1f}."
251
+
252
+ result["entry_key"] = row["id"]
253
+ return {
254
+ "query_output": result,
255
+ "query_input": query_input,
256
+ "query_status": status,
257
+ }
258
+
259
+ def get_map(self,
260
+ place: str | tuple[float, float, float],
261
+ properties: List[str],
262
+ session_name: Optional[str] = None,
263
+ **kwargs) -> Dict[str, Any]:
264
+ """
265
+ Generate scatter plots for the specified properties around a GADM region.
266
+
267
+ Returns:
268
+ {
269
+ "query_output": { "<full_name>": "<url or warning string>", ... },
270
+ "query_input": { "place": ..., "properties": [...] },
271
+ "query_status": "Success. N plot(s) generated." | "Failed. <reason>"
272
+ }
273
+ """
274
+ # Always include the input
275
+ query_input = {"place": place, "properties": properties}
276
+
277
+ # ---------- Resolve place → gid (and lat/lon if needed) ----------
278
+ try:
279
+ if isinstance(place, str):
280
+ if place not in self.gadm_handler.tree:
281
+ resolved = resolve_place(place, session_name=session_name, gadm_handler=self.gadm_handler)
282
+ gid = resolved.get("gid")
283
+ if gid is None:
284
+ return {"query_input": query_input,
285
+ "query_status": f"Failed. Cannot resolve place: {place}",
286
+ "query_output": {}}
287
+ else:
288
+ gid = place
289
+ else:
290
+ # tuple expected: (lat, lon, bbox_area)
291
+ if len(place) != 3:
292
+ return {"query_input": query_input,
293
+ "query_status": "Failed. Tuple `place` must be (lat, lon, bbox_area).",
294
+ "query_output": {}}
295
+ lat, lon, bbox_area = place
296
+ gid = self.gadm_handler.find_gid(lat, lon, bbox_area)
297
+ if gid is None:
298
+ return {"query_input": query_input,
299
+ "query_status": "Failed. No matching GADM region found for given coordinates.",
300
+ "query_output": {}}
301
+ geom_info = self.gadm_handler.get_geometry_info(gid)
302
+ if geom_info is None:
303
+ return {"query_input": query_input,
304
+ "query_status": f"Failed. Cannot get geometry for place (GID): {gid}",
305
+ "query_output": {}}
306
+ except Exception as e:
307
+ return {"query_input": query_input, "query_status": f"Failed. {str(e)}",
308
+ "query_output": {}}
309
+
310
+ # ---------- Strict property resolution (fail if any invalid) ----------
311
+ resolved = []
312
+ try:
313
+ for input_prop in properties:
314
+ full_name, theme, prop, unit = self.resolve_theme_property_unit(input_prop)
315
+ resolved.append((full_name, theme, prop, unit))
316
+ except Exception as e:
317
+ return {"query_input": query_input, "query_status": f"Failed. {str(e)}", "query_output": {}}
318
+
319
+ if len(resolved) > 5:
320
+ return {"query_input": query_input,
321
+ "query_status": "Failed. API does not accept more than 5 properties.",
322
+ "query_output": {}}
323
+
324
+ # ---------- Compute map extent using gid + siblings ----------
325
+ try:
326
+ siblings = self.gadm_handler.get_tree_info(gid)["siblings"]
327
+ gids = [gid] + siblings
328
+
329
+ polygon = self.gadm_handler.get_polygon(gid)
330
+ minx, miny, maxx, maxy = polygon.bounds
331
+
332
+ # 100% margin
333
+ dlat = (maxy - miny) or 1.0
334
+ dlon = (maxx - minx) or 1.0
335
+ lat_min, lat_max = miny - dlat, maxy + dlat
336
+ lon_min, lon_max = minx - dlon, maxx + dlon
337
+ except Exception as e:
338
+ return {"query_input": query_input, "query_status": f"Failed. {str(e)}", "query_output": {}}
339
+
340
+ # ---------- Region filter using LAT_LONG ----------
341
+ try:
342
+ latlon = np.vstack(self.df["LAT_LONG"].values).astype(float) # shape (N,2)
343
+ lats, lons = latlon[:, 0], latlon[:, 1]
344
+ mask = (lats >= lat_min) & (lats <= lat_max) & (lons >= lon_min) & (lons <= lon_max)
345
+ df_region = self.df[mask]
346
+ except Exception as e:
347
+ return {"query_input": query_input, "query_status": f"Failed. {str(e)}", "query_output": {}}
348
+
349
+ # ---------- Plot helper (returns URL or warning string) ----------
350
+ def plot_one(full_name: str, prop: str) -> str:
351
+ try:
352
+ if full_name not in df_region.columns:
353
+ return "Skipped. No valid data."
354
+
355
+ # Build [lat, lon, value]
356
+ values = pd.to_numeric(df_region[full_name], errors="coerce")
357
+ ok = values.notna()
358
+ if not ok.any():
359
+ return "Skipped. No valid data."
360
+
361
+ # extract lat/lon for the same rows
362
+ latlon_sub = np.vstack(df_region.loc[ok, "LAT_LONG"].values).astype(float)
363
+ data = np.column_stack([latlon_sub[:, 0], latlon_sub[:, 1], values.loc[ok].astype(float).values])
364
+
365
+ # numeric vs categorical: if after coercion we have floats, treat as numeric.
366
+ # If you need categorical, you can branch by dtype before coercion.
367
+ img_path = scatter_plot(
368
+ gadm_handler=self.gadm_handler,
369
+ data=data,
370
+ is_categorical=False,
371
+ short_name=prop,
372
+ long_name=full_name,
373
+ map_boundary_gadm_gids=gids,
374
+ map_limits="gadm_first",
375
+ session_name=session_name,
376
+ **kwargs
377
+ )
378
+ return img_path
379
+ except Exception:
380
+ return "Skipped. No valid data."
381
+
382
+ # ---------- Generate outputs (flat) ----------
383
+ query_output: Dict[str, str] = {}
384
+ for full_name, theme, prop, unit in resolved:
385
+ query_output[full_name] = plot_one(full_name, prop)
386
+
387
+ # ---------- Status ----------
388
+ n_plots = sum(1 for v in query_output.values() if isinstance(v, str) and v.endswith(".png"))
389
+ if n_plots >= 1:
390
+ status = f"Success. {n_plots} plot{'s' if n_plots != 1 else ''} generated."
391
+ else:
392
+ status = "Failed. No plots generated."
393
+
394
+ return {
395
+ "query_output": query_output,
396
+ "query_input": query_input,
397
+ "query_status": status,
398
+ }
gadm_utils.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ from typing import Dict, Any, Optional, Union, List
3
+
4
+ import numpy as np
5
+ from shapely.geometry import Point
6
+ from shapely.strtree import STRtree
7
+ from shapely.wkb import loads
8
+
9
+
10
+ class GADMHandler:
11
+ """
12
+ Handler for querying GADM hierarchy and geometry, built from preprocessed .gpkg files.
13
+ """
14
+
15
+ def __init__(self, path: str = "data_api/gadm_tree_europe.pkl") -> None:
16
+ """
17
+ Load the GADM tree and construct a spatial index on leaf geometries.
18
+
19
+ Args:
20
+ path (str): Path to the pickled tree file.
21
+ """
22
+ with open(path, "rb") as f:
23
+ raw_tree = pickle.load(f)
24
+
25
+ self.tree: Dict[str, Dict[str, Any]] = {}
26
+ for gid, node in raw_tree.items():
27
+ node = node.copy()
28
+ if node["geometry"] is not None:
29
+ node["geometry"] = loads(node["geometry"])
30
+ self.tree[gid] = node
31
+
32
+ leaf_items = [
33
+ (gid, node["geometry"])
34
+ for gid, node in self.tree.items()
35
+ if node["geometry"] is not None and not node["children"]
36
+ ]
37
+ self.leaf_polys = [geom for _, geom in leaf_items]
38
+ self.leaf_gid_map = {id(geom): gid for gid, geom in leaf_items}
39
+ self.leaf_tree = STRtree(self.leaf_polys)
40
+
41
+ def find_gid(
42
+ self, lat: float, lon: float, bbox_area: float = None, return_all: bool = False
43
+ ) -> Union[str, List[str], None]:
44
+ """
45
+ Find the best GADM GID that contains the given point (lat, lon),
46
+ optionally selecting the closest match by bounding box area.
47
+
48
+ Args:
49
+ lat (float): Latitude in degrees.
50
+ lon (float): Longitude in degrees.
51
+ bbox_area (float, optional): Area to match against polygon bounding box area (in degrees²);
52
+ if not provided, return the smallest region.
53
+ return_all (bool, optional): If True, return all matched GIDs up the tree; else return best match.
54
+
55
+ Returns:
56
+ str or list[str] or None: Best matching GID(s), or None if no polygon contains the point.
57
+ """
58
+ point = Point(lon, lat)
59
+ gids = []
60
+ areas = []
61
+
62
+ for poly_id in self.leaf_tree.query(point):
63
+ poly = self.leaf_polys[poly_id]
64
+ if poly.contains(point):
65
+ leaf_gid = self.leaf_gid_map[id(poly)]
66
+
67
+ # Traverse upward to collect candidates
68
+ current_gid = leaf_gid
69
+ while current_gid:
70
+ node = self.tree.get(current_gid)
71
+ if node["geometry"] is not None:
72
+ minx, miny, maxx, maxy = node["geometry"].bounds
73
+ if minx > maxx: # Wraparound correction
74
+ maxx += 360.0
75
+ poly_bbox_area = abs((maxx - minx) * (maxy - miny))
76
+ areas.append(poly_bbox_area)
77
+ gids.append(current_gid)
78
+
79
+ current_gid = node["parent"]
80
+
81
+ break # Use only the first containing leaf polygon
82
+
83
+ if not gids:
84
+ return None
85
+ if return_all:
86
+ return gids # Ordered from leaf to root
87
+ if bbox_area is None:
88
+ bbox_area = 0.0
89
+ areas = np.array(areas)
90
+ return gids[np.argmin(np.abs(areas - bbox_area))]
91
+
92
+ def get_polygon(self, gid: str) -> Optional[Any]:
93
+ """
94
+ Get the shapely geometry for a given GADM ID.
95
+ """
96
+ node = self.tree.get(gid)
97
+ return node["geometry"] if node else None
98
+
99
+ def get_full_name(self, gid: str) -> Optional[str]:
100
+ """
101
+ Get the full hierarchical name of a GADM region.
102
+ """
103
+ if gid not in self.tree:
104
+ return None
105
+
106
+ names = []
107
+ while gid in self.tree:
108
+ node = self.tree[gid]
109
+ names.append(node["name"] or "UNKNOWN")
110
+ gid = node["parent"]
111
+ if gid is None:
112
+ break
113
+
114
+ return "; ".join(names)
115
+
116
+ def get_geometry_info(self, gid: str) -> Optional[Dict[str, Any]]:
117
+ """
118
+ Get geometric metadata for the polygon of a GADM region.
119
+ """
120
+ polygon = self.get_polygon(gid)
121
+ if polygon is None:
122
+ return None
123
+
124
+ centroid = polygon.centroid
125
+ lon_c, lat_c = centroid.x, centroid.y
126
+ minx, miny, maxx, maxy = polygon.bounds
127
+ if minx > maxx:
128
+ maxx += 360.0
129
+
130
+ return {
131
+ "latitude": lat_c,
132
+ "longitude": lon_c,
133
+ "bbox_bounds": (miny, maxy, minx, maxx), # (lat_min, lat_max, lon_min, lon_max)
134
+ "polygon_area": polygon.area,
135
+ "bbox_area": abs((maxx - minx) * (maxy - miny))
136
+ }
137
+
138
+ def get_tree_info(self, gid: str) -> Optional[Dict[str, Any]]:
139
+ """
140
+ Get hierarchical metadata for a GADM region.
141
+ """
142
+ node = self.tree.get(gid)
143
+ if node is None:
144
+ return None
145
+
146
+ parent = node["parent"]
147
+ own_polygon = node.get("geometry")
148
+ siblings = []
149
+
150
+ if own_polygon and not own_polygon.is_empty:
151
+ if parent is None:
152
+ # Level-0: compare with other level-0 regions
153
+ candidates = [
154
+ (gid2, node2["geometry"])
155
+ for gid2, node2 in self.tree.items()
156
+ if node2["level"] == 0 and gid2 != gid and node2.get("geometry")
157
+ ]
158
+ else:
159
+ # Use other children of the same parent
160
+ candidates = [
161
+ (sibling_gid, self.tree[sibling_gid]["geometry"])
162
+ for sibling_gid in self.tree[parent]["children"]
163
+ if sibling_gid != gid and self.tree[sibling_gid].get("geometry")
164
+ ]
165
+
166
+ for gid2, poly2 in candidates:
167
+ try:
168
+ if own_polygon.touches(poly2) or own_polygon.intersects(poly2):
169
+ siblings.append(gid2)
170
+ except Exception: # noqa
171
+ continue # Catch topology errors etc.
172
+
173
+ siblings = sorted(siblings)
174
+
175
+ return {
176
+ "level": node["level"],
177
+ "parent": parent,
178
+ "children": sorted(node["children"]),
179
+ "siblings": siblings
180
+ }
181
+
182
+ def get_full_info(self, gid: str) -> Optional[Dict[str, Any]]:
183
+ """
184
+ Get complete metadata for a GADM region, including name, geometry, and hierarchy.
185
+ """
186
+ if gid not in self.tree:
187
+ return None
188
+ return {
189
+ "full_name": self.get_full_name(gid),
190
+ "geometry": self.get_geometry_info(gid),
191
+ "tree": self.get_tree_info(gid)
192
+ }
193
+
194
+ def quick_summary(self, gid: str) -> str:
195
+ """
196
+ Produce a human-readable summary of a GADM region.
197
+ Useful for GPT-based tools and debugging.
198
+ """
199
+ info = self.get_full_info(gid)
200
+ if not info:
201
+ return f"Invalid GID: {gid}"
202
+ name = info["full_name"] or "UNKNOWN"
203
+ level = info["tree"]["level"]
204
+ lat = info["geometry"]["latitude"]
205
+ lon = info["geometry"]["longitude"]
206
+ return f"{name} (GID={gid}, level={level}, lat={lat:.4f}, lon={lon:.4f})"
207
+
208
+
209
+ def main():
210
+ from geo_utils import resolve_place
211
+ handler = GADMHandler()
212
+
213
+ place_info = resolve_place("Cowley, Oxford", gadm_handler=handler)
214
+
215
+ gid = place_info["gid"]
216
+ info = handler.get_full_info(gid)
217
+ if info is None:
218
+ print(f"GID '{gid}' not found.")
219
+ return
220
+
221
+ print("\n--- GADM Metadata ---")
222
+ for key, val in info.items():
223
+ if isinstance(val, dict):
224
+ print(f"{key}:")
225
+ for sub_key, sub_val in val.items():
226
+ print(f" {sub_key}: {sub_val}")
227
+ else:
228
+ print(f"{key}: {val}")
229
+
230
+
231
+ if __name__ == "__main__":
232
+ main()
geo_utils.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import time
3
+ import warnings
4
+ from typing import Dict, Any, Optional
5
+
6
+ import pycountry
7
+ from geopy.exc import GeocoderTimedOut, GeocoderServiceError
8
+ from geopy.geocoders import Nominatim
9
+
10
+ from gadm_utils import GADMHandler
11
+
12
+
13
+ def resolve_place(
14
+ place_name: str,
15
+ fall_back_country: Optional[str] = None,
16
+ session_name: Optional[str] = None,
17
+ gadm_handler: Optional[GADMHandler] = None,
18
+ ) -> Dict[str, Any]:
19
+ """
20
+ Resolve a place name to coordinates using Nominatim,
21
+ with fallback to country via pycountry + GADMHandler.
22
+ """
23
+
24
+ def fail(status: str) -> Dict[str, Any]:
25
+ return {
26
+ "status": status,
27
+ "used_name": None,
28
+ "latitude": None,
29
+ "longitude": None,
30
+ "bbox_area": None,
31
+ "gid": None
32
+ }
33
+
34
+ def compute_bbox_area_from_nominatim(bbox) -> Optional[float]:
35
+ try:
36
+ lat_min, lat_max = float(bbox[0]), float(bbox[1])
37
+ lon_min, lon_max = float(bbox[2]), float(bbox[3])
38
+ if lon_min > lon_max:
39
+ lon_max += 360.0
40
+ return abs((lat_max - lat_min) * (lon_max - lon_min))
41
+ except Exception:
42
+ return None
43
+
44
+ def geocode(query: str, max_retries: int = 3, backoff: float = 1.0):
45
+ for attempt in range(1, max_retries + 1):
46
+ try:
47
+ return geocoder.geocode(query, timeout=5, geometry="geojson")
48
+ except (GeocoderTimedOut, GeocoderServiceError) as e:
49
+ if attempt == max_retries:
50
+ warnings.warn(
51
+ f"Geocoding failed: {query}\n{type(e).__name__}: {e}",
52
+ RuntimeWarning,
53
+ )
54
+ return None
55
+ time.sleep(backoff * attempt)
56
+ except Exception as e:
57
+ if attempt == max_retries:
58
+ warnings.warn(
59
+ f"Unexpected error: {query}\n{type(e).__name__}: {e}",
60
+ RuntimeWarning,
61
+ )
62
+ return None
63
+ time.sleep(backoff * attempt)
64
+
65
+ # --- Step 0: validate input ---
66
+ if not isinstance(place_name, str) or not place_name.strip():
67
+ return fail("Invalid input: place_name must be a non-empty string.")
68
+
69
+ # --- setup geocoder ---
70
+ identifier = "ERP_SOIL_GPT"
71
+ if session_name:
72
+ identifier += "_" + re.sub(r"[^a-zA-Z0-9_]", "_", session_name)
73
+ geocoder = Nominatim(user_agent=identifier)
74
+
75
+ # --- Step 0: try direct GADM match (aliases only) ---
76
+ if gadm_handler:
77
+
78
+ def norm(s: str) -> str:
79
+ return s.strip().lower()
80
+
81
+ place_norm = norm(place_name)
82
+
83
+ for gid, node in gadm_handler.tree.items():
84
+ raw_aliases = node.get("aliases", [])
85
+ aliases = {norm(a) for a in raw_aliases}
86
+ aliases.add(norm(node["name"]))
87
+ aliases.add(norm(gid))
88
+ if not aliases:
89
+ continue
90
+
91
+ if place_norm in aliases:
92
+ geom_info = gadm_handler.get_geometry_info(gid)
93
+ if geom_info is None:
94
+ return fail(
95
+ f"Matched GADM node '{gid}' but geometry is missing."
96
+ )
97
+
98
+ return {
99
+ "status": "Resolved by direct GADM alias match.",
100
+ "used_name": place_name,
101
+ "latitude": geom_info["latitude"],
102
+ "longitude": geom_info["longitude"],
103
+ "bbox_area": geom_info["bbox_area"],
104
+ "gid": gid,
105
+ }
106
+
107
+ # --- Step 1: try full place name ---
108
+ query = place_name
109
+ if fall_back_country and fall_back_country not in query:
110
+ query += f", {fall_back_country}"
111
+
112
+ result = geocode(query)
113
+ if result:
114
+ try:
115
+ lat = float(result.latitude)
116
+ lon = float(result.longitude)
117
+ except (TypeError, ValueError):
118
+ return fail("Geocoding succeeded but returned invalid coordinates.")
119
+
120
+ bbox_area = compute_bbox_area_from_nominatim(
121
+ result.raw.get("boundingbox")
122
+ )
123
+
124
+ return {
125
+ "status": "Success. Resolved by Nominatim.",
126
+ "used_name": query,
127
+ "latitude": lat,
128
+ "longitude": lon,
129
+ "bbox_area": bbox_area,
130
+ "gid": gadm_handler.find_gid(lat, lon, bbox_area)
131
+ if gadm_handler
132
+ else None,
133
+ }
134
+
135
+ # --- Step 2: try country via Nominatim ---
136
+ if fall_back_country:
137
+ result = geocode(fall_back_country)
138
+ if result:
139
+ try:
140
+ lat = float(result.latitude)
141
+ lon = float(result.longitude)
142
+ except (TypeError, ValueError):
143
+ return fail("Fallback succeeded but returned invalid coordinates.")
144
+
145
+ bbox_area = compute_bbox_area_from_nominatim(
146
+ result.raw.get("boundingbox")
147
+ )
148
+
149
+ return {
150
+ "status": (
151
+ f"Fallback. Failed with '{place_name}', "
152
+ f"succeeded with '{fall_back_country}' by Nominatim."
153
+ ),
154
+ "used_name": fall_back_country,
155
+ "latitude": lat,
156
+ "longitude": lon,
157
+ "bbox_area": bbox_area,
158
+ "gid": gadm_handler.find_gid(lat, lon, bbox_area)
159
+ if gadm_handler
160
+ else None,
161
+ }
162
+
163
+ # --- Step 3: offline country fallback via pycountry + GADMHandler ---
164
+ if fall_back_country and gadm_handler:
165
+ try:
166
+ country = pycountry.countries.lookup(fall_back_country)
167
+ except LookupError:
168
+ country = None
169
+
170
+ if country:
171
+ alpha3 = country.alpha_3
172
+ geom_info = gadm_handler.get_geometry_info(alpha3)
173
+ if geom_info:
174
+ return {
175
+ "status": (
176
+ f"Fallback. Failed with '{place_name}', "
177
+ f"succeeded with '{fall_back_country}' by PyCountry."
178
+ ),
179
+ "used_name": country.name,
180
+ "latitude": geom_info["latitude"],
181
+ "longitude": geom_info["longitude"],
182
+ "bbox_area": geom_info["bbox_area"],
183
+ "gid": alpha3,
184
+ }
185
+
186
+ # --- Step 4: complete failure ---
187
+ return fail("Failed.")
188
+
189
+
190
+ def main():
191
+ handler = GADMHandler("data_api/gadm_tree_europe.pkl")
192
+
193
+ place = "Balkan"
194
+ fallback = None
195
+
196
+ t0 = time.time()
197
+ result = resolve_place(
198
+ place_name=place,
199
+ fall_back_country=fallback,
200
+ gadm_handler=handler,
201
+ )
202
+ print("Seconds:", time.time() - t0)
203
+
204
+ print("\n--- Resolution Result ---")
205
+ for k, v in result.items():
206
+ print(f"{k}: {v}")
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
gpt_resources/icon.png ADDED

Git LFS Details

  • SHA256: 110f86a8dea175e1d22d7e6f8e0129407a75dea8d15a7cf13e354baff7ec29e0
  • Pointer size: 132 Bytes
  • Size of remote file: 1.09 MB
gpt_resources/knowledge.md ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ =========Start of knowledge_api.md=========
2
+ This document **`knowledge_api.md`** introduces the APIs we expose.
3
+ It focuses on high-level understanding and recommended usage patterns.
4
+ For exact request/response definitions, refer to the API schema.
5
+
6
+ ---
7
+
8
+ # Geographic APIs
9
+
10
+ These APIs support flexible geographic reasoning and are designed to be used **modularly and sequentially**.
11
+
12
+ | API | Purpose | When to call |
13
+ |-------------------------------|---------------------------------------------|--------------------------------------------------------------------|
14
+ | /resolve_place(place_name, …) | Place text → coordinates (and possibly GID) | First step for user-provided place names (Nominatim-backed) |
15
+ | /gadm/find_gid(lat, lon, …) | Coordinates → GADM region(s) | When WGS84 coordinates (and scale) are provided or can be inferred |
16
+ | /gadm/get_tree_info(gid) | Administrative hierarchy navigation | To move up, down, or across admin levels |
17
+ | /gadm/get_full_name(gid) | GID → full human-readable name | To present regions in natural language |
18
+ | /gadm/get_geometry_info(gid) | Geometry summary (centroid, bbox, area) | When spatial characteristics are required |
19
+ | /gadm/get_quick_summary(gid) | One-line region description | When a concise description is sufficient |
20
+
21
+ The **GID (GADM ID)** is the central reference of the geographic system.
22
+
23
+ User input typically starts as either:
24
+
25
+ - a **place name** (vague), or
26
+ - **latitude/longitude** coordinates (precise).
27
+
28
+ Use `/resolve_place` or `/gadm/find_gid` to obtain the corresponding GID.
29
+ Once a GID is available, it can be used to retrieve administrative context,
30
+ geometry, and human-readable descriptions.
31
+ `/gadm/get_tree_info` is particularly useful for associative reasoning across
32
+ administrative levels.
33
+
34
+ In practice, **work with GID whenever possible**.
35
+ If appropriate, the GID may be exposed directly in the response.
36
+
37
+ The `bbox_area` parameter acts as a **scale hint** (unit: degree² under WGS84),
38
+ not as a strict spatial boundary.
39
+
40
+ ---
41
+
42
+ ## GADM Hierarchy Extension (Europe-Level Root)
43
+
44
+ In **standard GADM**, the highest administrative level is the **country**.
45
+
46
+ In this API, the hierarchy is **explicitly extended above the country level**
47
+ to support continent-scale and regional queries.
48
+ The **root of the hierarchy is `Europe`**, not individual countries.
49
+
50
+ Between `Europe` and individual countries, the hierarchy includes **exactly two
51
+ additional levels**, and no others:
52
+
53
+ 1. **Directional regions**, based on continental orientation
54
+ (Northern, Southern, Eastern, Western, Central Europe)
55
+
56
+ 2. **Conventional geographic regions**, based on widely accepted geographic usage
57
+ (e.g. Scandinavian, Balkan, British Isles)
58
+
59
+ These two levels are **API-level extensions** and are **not part of the original
60
+ GADM release**.
61
+
62
+ They:
63
+ - have valid **GIDs**,
64
+ - participate in `/gadm/find_gid` and `/gadm/get_tree_info`,
65
+ - can be used directly with `/soil/get_map` for large-scale queries.
66
+
67
+ Example resolved hierarchy:
68
+
69
+ ```
70
+ Cowley → Oxford → Oxfordshire → England → United Kingdom → British Isles → Northern Europe → Europe
71
+ ```
72
+
73
+ ---
74
+
75
+ # Data Retrieval APIs
76
+
77
+ These APIs retrieve **soil property data** either at a single location or as
78
+ rendered maps over an area.
79
+ They are typically used **after geographic resolution** and require a place
80
+ reference plus a list of property names.
81
+
82
+ ## API Overview
83
+
84
+ | API | Purpose | When to call |
85
+ |---------------------------------------|-----------------------------------------------|-----------------------------------------------------------|
86
+ | /soil/get_point(place, properties, …) | Retrieve property values at a single location | When many properties are needed at a local scale |
87
+ | /soil/get_map(place, properties, …) | Generate property maps (image URLs) | When a few properties are needed across a geographic area |
88
+
89
+ Conceptually, `/soil/get_point` emphasizes **depth and detail** at a specific
90
+ location, while `/soil/get_map` emphasizes **spatial coverage** across an area.
91
+
92
+ ## Notes on input
93
+
94
+ - `place` may be:
95
+ - a text string (e.g. `"Umbria, Italy"`),
96
+ - `(lat, lon)` for `/soil/get_point`,
97
+ - `(lat, lon, bbox_area)` for `/soil/get_map`.
98
+ - `properties` must be valid column names (see `meta_column_names.json`).
99
+ Property names are flexible; for
100
+ `biomass:bacterial_biomass (nmol FAME g⁻¹ soil)`, all following are equivalent:
101
+ - `biomass:bacterial_biomass (nmol FAME g⁻¹ soil)`
102
+ - `biomass:bacterial_biomass`
103
+ - `bacterial_biomass`
104
+ - For `/soil/get_map`, a maximum of **8 properties per call** is enforced to limit latency.
105
+ Larger requests should be split into meaningful subsets.
106
+ - `/soil/get_point` does not limit the number of properties.
107
+ - Soil-specific properties default to **topsoil** unless the property name explicitly
108
+ specifies a depth qualifier (e.g. `bulk_density_subsoil`).
109
+
110
+ ## Notes on output
111
+
112
+ - `/soil/get_point` returns values from the best-matching nearby sample,
113
+ selected from the top-k nearest candidates under a distance threshold.
114
+ In addition to property values, the response may include **sample-level
115
+ metadata**, such as:
116
+ - contributing source datasets,
117
+ - distance-to-sample or distance-to-grid indicators,
118
+ - other uncertainty-related fields.
119
+ This makes `/soil/get_point` suitable for **in-depth inspection** of individual samples.
120
+ - If the requested properties include `ASSETS:photos`, `/soil/get_point` also returns
121
+ associated **photo URLs** when available.
122
+ - `/soil/get_map` focuses on **spatial patterns at scale**.
123
+ It aggregates many samples within the target region and does not expose
124
+ per-sample metadata or uncertainty details.
125
+ Each requested property produces either:
126
+ - a plot URL, or
127
+ - a warning message.
128
+ - All responses include `query_input` and `query_status`.
129
+ Plot URLs should be displayed **inline immediately** to support rapid visual
130
+ inspection and iterative analysis.
131
+
132
+ ---
133
+
134
+ **END of `knowledge_api.md`**
135
+ =========End of knowledge_api.md=========
136
+
137
+ =========Start of knowledge_dataset.md=========
138
+ The document **`knowledge_dataset.md`** provides the canonical description of the **LUCAS-MEGA** fused dataset.
139
+ It defines the dataset composition, metadata schema, and supporting lookup resources.
140
+ This document should be treated as the definitive reference for dataset-level questions.
141
+
142
+ ---
143
+
144
+ # Knowledge Base: LUCAS-MEGA Dataset
145
+
146
+ The **LUCAS-MEGA** dataset provides harmonized soil and ecosystem properties for samples collected across Europe.
147
+
148
+ - It is a **data fusion product** built from **60+ datasets** hosted by **ESDAC** (European Soil Data Centre).
149
+ - The dataset is organized as a **single long-wide table**:
150
+ - **Rows**: soil samples (≈ **72,000**)
151
+ - **Columns**: measured or derived properties (≈ **1,000**)
152
+ - Data can be accessed through APIs in both **sample-wise (row)** and **property-wise (column)** modes.
153
+
154
+ ---
155
+
156
+ ## 1. Samples (Rows)
157
+
158
+ Approximately **90%** of samples originate from **LUCAS soil surveys**
159
+ (2012, 2015, 2018, 2019).
160
+ The remaining **~10%** are harmonized from **EU-HYDI** and **SPADE/M**.
161
+
162
+ The name *LUCAS-MEGA* reflects LUCAS as the primary sample backbone.
163
+
164
+ ---
165
+
166
+ ## 2. Properties (Columns)
167
+
168
+ Each sample contains a set of native measurements (e.g. organic carbon).
169
+ Additional datasets are fused into the same table to expand property coverage.
170
+
171
+ Two fusion modes are used:
172
+
173
+ | Fusion Type | Description |
174
+ |------------------|-------------------------------------------------------------------------------------------|
175
+ | **LUCAS-native** | Source data are already sample-aligned with LUCAS; values are merged by sample ID. |
176
+ | **Map-based** | Source data are raster maps; values are sampled from the nearest grid cell to the sample. |
177
+ | | A `distance_to_grid` value is stored as an uncertainty indicator. |
178
+
179
+ Understanding a property requires consulting its metadata in **`meta_column_complete.json`**
180
+ (≈ 1,000 entries).
181
+
182
+ Example:
183
+
184
+ ```json
185
+ {
186
+ "texture:clay_percentage (%)": {
187
+ "source_datasets": [
188
+ "european-hydropedological-data-inventory-eu-hydi-database-0",
189
+ "lucas-2009-topsoil-data",
190
+ "lucas-2015-topsoil-data-switzerland",
191
+ "lucas-2018-topsoil-data",
192
+ "lucas2015-topsoil-data",
193
+ "spadem"
194
+ ],
195
+ "distance_to_grid_stats (m)": {
196
+ "min": 0.0,
197
+ "max": 0.0,
198
+ "mean": 0.0,
199
+ "std": 0.0,
200
+ "median": 0.0
201
+ },
202
+ "null_fraction": 0.295,
203
+ "description": "Mass percentage of clay-sized particles (<2 µm) in the fine earth fraction (<2 mm) of the soil sample."
204
+ }
205
+ }
206
+ ```
207
+
208
+ ### Metadata Fields
209
+
210
+ | Field | Meaning |
211
+ |------------------------------|-------------------------------------------------------------------|
212
+ | `texture` | **Theme** (organizational grouping; not exhaustive or exclusive). |
213
+ | `clay_percentage` | Property name within the theme. |
214
+ | `%` | Unit (omitted if dimensionless). |
215
+ | `source_datasets` | Source datasets contributing to the column. |
216
+ | `distance_to_grid_stats (m)` | Distance statistics for map-based fusion (0 for LUCAS-native). |
217
+ | `null_fraction` | Fraction of missing values in the column. |
218
+ | `description` | Human-readable definition of the property. |
219
+
220
+ ---
221
+
222
+ ### Fast Access to Column Names
223
+
224
+ For property selection, you do **not** need to load `meta_column_complete.json`.
225
+
226
+ A lightweight helper file, **`meta_column_names.json`**, provides the full list of column
227
+ names without metadata and is intended for fast lookup and validation.
228
+
229
+ Most column names are already interpretable within the soil science domain.
230
+ When additional detail is needed (e.g. source datasets or uncertainty),
231
+ refer to `meta_column_complete.json`.
232
+
233
+ ---
234
+
235
+ ## 3. Source Dataset Metadata
236
+
237
+ Metadata for all contributing datasets is stored in **`meta_fused_datasets.json`**, including:
238
+
239
+ | Key / Value | Description |
240
+ |---------------|----------------------------------------------------------------------|
241
+ | dataset key | Identifier used in `source_datasets` in `meta_column_complete.json`. |
242
+ | `title` | Official dataset title. |
243
+ | `abstract` | Official dataset summary. |
244
+ | `dataset_url` | Link to full dataset documentation. |
245
+
246
+ All source datasets are provided by **ESDAC**.
247
+
248
+ ---
249
+
250
+ ## 4. Retrieval APIs
251
+
252
+ Data access is supported through both **row-wise** and **column-wise** APIs.
253
+ Refer to **`knowledge_api.md`** for usage patterns, request formats, and examples.
254
+
255
+ ---
256
+
257
+ **END of `knowledge_dataset.md`**
258
+ =========End of knowledge_dataset.md=========
259
+
260
+ =========Start of meta_column_names.json=========
261
+ ```json
262
+ {
263
+ "column_names": [
264
+ "ASSETS:photos",
265
+ "biodiversity:climate_change_pressure_index",
266
+ "biodiversity:genetically_modified_organism_use_pressure_index",
267
+ "biodiversity:habitat_fragmentation_pressure_index",
268
+ "biodiversity:industrial_pollution_pressure_index",
269
+ "biodiversity:intensive_human_exploitation_pressure_index",
270
+ "biodiversity:land_use_change_pressure_index",
271
+ "biodiversity:organic_matter_decline_pressure_index",
272
+ "biodiversity:radioactivity_pressure_index",
273
+ "biodiversity:soil_biological_functions_threat_index",
274
+ "biodiversity:soil_compaction_pressure_index",
275
+ "biodiversity:soil_erosion_pressure_index",
276
+ "biodiversity:soil_fauna_threat_index",
277
+ "biodiversity:soil_microorganisms_threat_index",
278
+ "biodiversity:soil_salinity_pressure_index",
279
+ "biomass:basal_respiration_general (\u00b5L O\u2082 g\u207b\u00b9 soil h\u207b\u00b9)",
280
+ "biomass:basal_respiration_landcover (\u00b5L O\u2082 g\u207b\u00b9 soil h\u207b\u00b9)",
281
+ "biomass:microbial_biomass_general (\u00b5g C\u2098\u1d62c g\u207b\u00b9 soil)",
282
+ "biomass:microbial_biomass_landcover (\u00b5g C\u2098\u1d62c g\u207b\u00b9 soil)",
283
+ "biomass:respiratory_quotient_general (\u00b5L O\u2082 \u00b5g\u207b\u00b9 C\u2098\u1d62c h\u207b\u00b9)",
284
+ "biomass:respiratory_quotient_landcover (\u00b5L O\u2082 \u00b5g\u207b\u00b9 C\u2098\u1d62c h\u207b\u00b9)",
285
+ "biomass:soil_biomass_productivity_cropland",
286
+ "carbon:CaCO3_content (g/kg)",
287
+ "carbon:SOC_saturation_ratio",
288
+ "carbon:carbon_deposition_flux_accelerated_revised_model (MgC ha\u207b\u00b9 yr\u207b\u00b9)",
289
+ "carbon:carbon_deposition_flux_accelerated_scenario (MgC ha\u207b\u00b9 yr\u207b\u00b9)",
290
+ "carbon:carbon_deposition_flux_current_revised_model (MgC ha\u207b\u00b9 yr\u207b\u00b9)",
291
+ "carbon:carbon_deposition_flux_current_scenario (MgC ha\u207b\u00b9 yr\u207b\u00b9)",
292
+ "carbon:carbon_deposition_flux_no_erosion_scenario (MgC ha\u207b\u00b9 yr\u207b\u00b9)",
293
+ "carbon:carbon_erosion_flux_accelerated_revised_model (MgC ha\u207b\u00b9 yr\u207b\u00b9)",
294
+ "carbon:carbon_erosion_flux_accelerated_scenario (MgC ha\u207b\u00b9 yr\u207b\u00b9)",
295
+ "carbon:carbon_erosion_flux_current_revised_model (MgC ha\u207b\u00b9 yr\u207b\u00b9)",
296
+ "carbon:carbon_erosion_flux_current_scenario (MgC ha\u207b\u00b9 yr\u207b\u00b9)",
297
+ "carbon:carbon_erosion_flux_no_erosion_scenario (MgC ha\u207b\u00b9 yr\u207b\u00b9)",
298
+ "carbon:eroded_carbon_stock (t ha\u207b\u00b9)",
299
+ "carbon:eroded_soc_content (g/kg)",
300
+ "carbon:estimated_organic_carbon_density_subsoil (t ha\u207b\u00b9)",
301
+ "carbon:estimated_organic_carbon_density_topsoil (t ha\u207b\u00b9)",
302
+ "carbon:observed_vs_typical_soc_index",
303
+ "carbon:observed_vs_typical_soc_index_confidence_zone",
304
+ "carbon:organic_carbon_content (g/kg)",
305
+ "carbon:organic_carbon_content_subsoil_ESDB (g/kg)",
306
+ "carbon:organic_carbon_content_topsoil (g/kg)",
307
+ "carbon:organic_carbon_content_topsoil_ESDB (g/kg)",
308
+ "carbon:soc_change_2009_2018 (g C kg\u207b\u00b9 yr\u207b\u00b9)",
309
+ "carbon:topsoil_OC_prediction_mean (g/kg)",
310
+ "carbon:topsoil_OC_prediction_std (g/kg)",
311
+ "chemical:electrical_conductivity (mS/m)",
312
+ "chemical:pH_in_CaCl2",
313
+ "chemical:pH_in_H2O",
314
+ "chemical:pH_in_H2O_EFSA",
315
+ "climate:annual_precipitation (mm)",
316
+ "climate:annual_temperature (\u00b0C)",
317
+ "crop_plant:apples_fraction (%)",
318
+ "crop_plant:barley_fraction (%)",
319
+ "crop_plant:berries_fraction (%)",
320
+ "crop_plant:citrus_fraction (%)",
321
+ "crop_plant:common_wheat_fraction (%)",
322
+ "crop_plant:cover_crop_fraction_5th_percentile (\u2031)",
323
+ "crop_plant:cover_crop_fraction_95th_percentile (\u2031)",
324
+ "crop_plant:cover_crop_fraction_median (\u2031)",
325
+ "crop_plant:cover_crop_fraction_std (\u2031)",
326
+ "crop_plant:durum_wheat_fraction (%)",
327
+ "crop_plant:effective_rooting_depth (cm)",
328
+ "crop_plant:fallow_fraction (%)",
329
+ "crop_plant:hops_fraction (%)",
330
+ "crop_plant:maize_crop_fraction (%)",
331
+ "crop_plant:oats_fraction (%)",
332
+ "crop_plant:olives_fraction (%)",
333
+ "crop_plant:other_crops_fraction (%)",
334
+ "crop_plant:pastures_fraction (%)",
335
+ "crop_plant:potatoes_fraction (%)",
336
+ "crop_plant:pulses_fraction (%)",
337
+ "crop_plant:rapeseed_fraction (%)",
338
+ "crop_plant:rye_fraction (%)",
339
+ "crop_plant:soya_fraction (%)",
340
+ "crop_plant:sugar_beet_fraction (%)",
341
+ "crop_plant:sunflower_fraction (%)",
342
+ "crop_plant:vineyards_fraction (%)",
343
+ "erosion:c_factor_cover_management",
344
+ "erosion:erodible_by_wind_fraction",
345
+ "erosion:k_factor_based_on_soil_texture (t ha h ha\u207b\u00b9 MJ\u207b\u00b9 mm\u207b\u00b9)",
346
+ "erosion:k_factor_based_on_soil_texture_uncertainty (t ha h ha\u207b\u00b9 MJ\u207b\u00b9 mm\u207b\u00b9)",
347
+ "erosion:k_factor_from_glosem_model (t ha h ha\u207b\u00b9 MJ\u207b\u00b9 mm\u207b\u00b9)",
348
+ "erosion:k_factor_lucas (t ha h ha\u207b\u00b9 MJ\u207b\u00b9 mm\u207b\u00b9)",
349
+ "erosion:k_factor_lucas_with_stoniness (t ha h ha\u207b\u00b9 MJ\u207b\u00b9 mm\u207b\u00b9)",
350
+ "erosion:k_factor_with_saturated_hydraulic_conductivity (t ha h ha\u207b\u00b9 MJ\u207b\u00b9 mm\u207b\u00b9)",
351
+ "erosion:k_factor_with_saturated_hydraulic_conductivity_uncertainty (t ha h ha\u207b\u00b9 MJ\u207b\u00b9 mm\u207b\u00b9)",
352
+ "erosion:ls_factor_slope_length_and_steepness",
353
+ "erosion:net_erosion_rate_PESERA (t ha\u207b\u00b9 yr\u207b\u00b9)",
354
+ "erosion:net_erosion_rate_WaTEM_SEDEM (t ha\u207b\u00b9 yr\u207b\u00b9)",
355
+ "erosion:p_factor_support_practices",
356
+ "erosion:r_factor_2050_projection (MJ mm ha\u207b\u00b9 h\u207b\u00b9 yr\u207b\u00b9)",
357
+ "erosion:r_factor_annual_mean (MJ mm ha\u207b\u00b9 h\u207b\u00b9 yr\u207b\u00b9)",
358
+ "erosion:r_factor_annual_std (MJ mm ha\u207b\u00b9 h\u207b\u00b9 yr\u207b\u00b9)",
359
+ "erosion:r_factor_erosivity_density (MJ ha\u207b\u00b9 h\u207b\u00b9 per mm precipitation)",
360
+ "erosion:r_factor_erosivity_ratio",
361
+ "erosion:r_factor_mann_kendall",
362
+ "erosion:r_factor_rainfall (MJ mm ha\u207b\u00b9 h\u207b\u00b9 yr\u207b\u00b9)",
363
+ "erosion:r_factor_trend_linear (MJ mm ha\u207b\u00b9 h\u207b\u00b9 per year)",
364
+ "erosion:r_factor_weighted_density",
365
+ "erosion:soil_displacement_estimate (t ha\u207b\u00b9 yr\u207b\u00b9)",
366
+ "erosion:soil_loss_by_water (t ha\u207b\u00b9 yr\u207b\u00b9)",
367
+ "fertility:K_extractable (mg/kg)",
368
+ "fertility:N_extractable (g/kg)",
369
+ "fertility:P_available_stock (kg ha\u207b\u00b9)",
370
+ "fertility:P_extractable (mg/kg)",
371
+ "fertility:P_total_concentration_topsoil (mg/kg)",
372
+ "fertility:P_total_stock_topsoil (kg ha\u207b\u00b9)",
373
+ "hydraulic:field_capacity_water_content (cm\u00b3 cm\u207b\u00b3)",
374
+ "hydraulic:field_capacity_water_content_EFSA (cm\u00b3/cm\u00b3)",
375
+ "hydraulic:saturated_hydraulic_conductivity (cm/day)",
376
+ "hydraulic:saturated_water_content (cm\u00b3 cm\u207b\u00b3)",
377
+ "hydraulic:topographic_wetness_index",
378
+ "hydraulic:total_available_water_capacity_subsoil_ESDB (mm)",
379
+ "hydraulic:total_available_water_capacity_subsoil_SMU_ESDB (mm)",
380
+ "hydraulic:total_available_water_capacity_topsoil_ESDB (mm)",
381
+ "hydraulic:total_available_water_capacity_topsoil_SMU_ESDB (mm)",
382
+ "hydraulic:wilting_point_water_content (cm\u00b3 cm\u207b\u00b3)",
383
+ "land_degradation:aridity_index_mean_cropland",
384
+ "land_degradation:land_multi_degradation_index_agricultural_lands",
385
+ "land_degradation:soil_erosion_exceeding_10Mg_ha_yr (t ha\u207b\u00b9 yr\u207b\u00b9)",
386
+ "land_site:nighttime_light_intensity",
387
+ "land_site:solar_radiation_input (W/m\u00b2)",
388
+ "mass_density:bulk_density (g/cm\u00b3)",
389
+ "mass_density:bulk_density_0_10cm (g/cm\u00b3)",
390
+ "mass_density:bulk_density_10_20cm (g/cm\u00b3)",
391
+ "mass_density:bulk_density_subsoil_ESDB (g/cm\u00b3)",
392
+ "mass_density:bulk_density_topsoil_EFSA (g/cm\u00b3)",
393
+ "mass_density:bulk_density_topsoil_ESDB (g/cm\u00b3)",
394
+ "mass_density:packing_density (g/cm\u00b3)",
395
+ "organic_matter:organic_matter_content (g/kg)",
396
+ "texture:clay_percentage (%)",
397
+ "texture:clay_percentage_subsoil_ESDB (%)",
398
+ "texture:clay_percentage_topsoil_ESDB (%)",
399
+ "texture:coarse_percentage (%)",
400
+ "texture:coarse_percentage_subsoil_ESDB (%)",
401
+ "texture:coarse_percentage_topsoil_ESDB (%)",
402
+ "texture:sand_percentage (%)",
403
+ "texture:sand_percentage_subsoil_ESDB (%)",
404
+ "texture:sand_percentage_topsoil_ESDB (%)",
405
+ "texture:silt_percentage (%)",
406
+ "texture:silt_percentage_subsoil_ESDB (%)",
407
+ "texture:silt_percentage_topsoil_ESDB (%)",
408
+ "topography_geology:digital_elevation_model (m)",
409
+ "topography_geology:elevation (m)",
410
+ "topography_geology:slope (deg)",
411
+ "trace_elements:As_concentration_1km_res (mg/kg)",
412
+ "trace_elements:As_concentration_5km_res (mg/kg)",
413
+ "trace_elements:As_concentration_kurtosis",
414
+ "trace_elements:As_concentration_mean (log10 mg/kg)",
415
+ "trace_elements:As_concentration_skewness",
416
+ "trace_elements:As_concentration_std (log10 mg/kg)",
417
+ "trace_elements:As_concentration_variance_1km_res (mg\u00b2/kg\u00b2)",
418
+ "trace_elements:Cd_concentration (mg/kg)",
419
+ "trace_elements:Cd_concentration_1km_res (mg/kg)",
420
+ "trace_elements:Cd_concentration_5km_res (mg/kg)",
421
+ "trace_elements:Cd_concentration_variance_1km_res (mg\u00b2/kg\u00b2)",
422
+ "trace_elements:Co_concentration_1km_res (mg/kg)",
423
+ "trace_elements:Co_concentration_variance_1km_res (mg\u00b2/kg\u00b2)",
424
+ "trace_elements:Cr_concentration_1km_res (mg/kg)",
425
+ "trace_elements:Cr_concentration_5km_res (mg/kg)",
426
+ "trace_elements:Cr_concentration_variance_1km_res (mg\u00b2/kg\u00b2)",
427
+ "trace_elements:Cu_concentration (mg/kg)",
428
+ "trace_elements:Cu_concentration_1km_res (mg/kg)",
429
+ "trace_elements:Cu_concentration_5km_res (mg/kg)",
430
+ "trace_elements:Cu_concentration_variance_1km_res (mg\u00b2/kg\u00b2)",
431
+ "trace_elements:Hg_concentration (\u00b5g/kg)",
432
+ "trace_elements:Hg_concentration_1km_res (mg/kg)",
433
+ "trace_elements:Hg_concentration_5km_res (mg/kg)",
434
+ "trace_elements:Hg_concentration_variance_1km_res (mg\u00b2/kg\u00b2)",
435
+ "trace_elements:Hg_residual (\u00b5g/kg)",
436
+ "trace_elements:Hg_stock (g ha\u207b\u00b9)",
437
+ "trace_elements:Mn_concentration_1km_res (mg/kg)",
438
+ "trace_elements:Mn_concentration_variance_1km_res (mg\u00b2/kg\u00b2)",
439
+ "trace_elements:Ni_concentration_1km_res (mg/kg)",
440
+ "trace_elements:Ni_concentration_5km_res (mg/kg)",
441
+ "trace_elements:Ni_concentration_variance_1km_res (mg\u00b2/kg\u00b2)",
442
+ "trace_elements:Pb_concentration_1km_res (mg/kg)",
443
+ "trace_elements:Pb_concentration_5km_res (mg/kg)",
444
+ "trace_elements:Pb_concentration_variance_1km_res (mg\u00b2/kg\u00b2)",
445
+ "trace_elements:Sb_concentration_1km_res (mg/kg)",
446
+ "trace_elements:Sb_concentration_variance_1km_res (mg\u00b2/kg\u00b2)",
447
+ "trace_elements:Zn_concentration (mg/kg)",
448
+ "trace_elements:Zn_concentration_5km_res (mg/kg)",
449
+ "trace_elements:Zn_concentration_5th_percentile (mg/kg)",
450
+ "trace_elements:Zn_concentration_95th_percentile (mg/kg)"
451
+ ]
452
+ }
453
+ ```
454
+ =========End of meta_column_names.json=========
455
+
456
+ =========Start of meta_fused_datasets.json=========
457
+ ```json
458
+ {
459
+ "3d-soil-hydraulic-database-europe-1-km-and-250-m-resolution": {
460
+ "title": "3D Soil Hydraulic Database of Europe at 1 km and 250 m resolution",
461
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/3d-soil-hydraulic-database-europe-1-km-and-250-m-resolution",
462
+ "abstract": "A consistent spatial soil hydraulic database at 7 soil depths up to 2 m calculated for Europe based on SoilGrids250m and 1 km datasets and pedotransfer functions trained on the European Hydropedological Data Inventory. Saturated water content, water content at field capacity and wilting point, saturated hydraulic conductivity and Mualem-van Genuchten parameters for the description of the moisture retention, and unsaturated hydraulic conductivity curves have been predicted. The derived 3D soil hydraulic layers (EU-SoilHydroGrids ver1.0) can be used for environmental modelling purposes at catchment or continental scale in Europe. Currently, only EU-SoilHydroGrids provides information on the most frequently required soil hydraulic properties with full European coverage up to 2 m depth at 250 m resolution."
463
+ },
464
+ "arsenic-european-topsoils": {
465
+ "title": "Arsenic in European topsoils",
466
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/arsenic-european-topsoils",
467
+ "abstract": "Maps of Arsenic (As) in EU topsoils at 250m resolution. In addition, we provide the exceedance probabilities for the threshold of 1.5, 20 and 45 mg kg-1 . We also provide comparison with GEMAS data on As."
468
+ },
469
+ "bacterial-fungal-biomass-fatty-acid-methyl-esters": {
470
+ "title": "Bacterial & fungal biomass (fatty acid methyl esters)",
471
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/bacterial-fungal-biomass-fatty-acid-methyl-esters",
472
+ "abstract": "Land-use- and climate-mediated variations in soil bacterial and fungal biomass across Europe and their driving factors. These are data accompanying a study that was carried out by a number of researchers from various organizations, including staff from the European Commission Joint Research Centre"
473
+ },
474
+ "biodiversity-factor-soil-erosion": {
475
+ "title": "Biodiversity factor in soil erosion",
476
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/biodiversity-factor-soil-erosion",
477
+ "abstract": "A biological factor to be included in soil erosion modelling. The available data for Earthwork diversity (richness and abundance) introduced a new \"earthworm factor\" to be incorporated in soil erosion modelling."
478
+ },
479
+ "cadmium-topsoils-european-union": {
480
+ "title": "Cadmium in topsoils of the European Union",
481
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/cadmium-topsoils-european-union",
482
+ "abstract": "Cadmium content (mg kg-1) in the European Union topsoils applying an ensemble of machine learning models. The map of Cd distribution at a resolution of 100 m."
483
+ },
484
+ "caesium-137-and-plutonium-239240-european-topsoils": {
485
+ "title": "Caesium-137 and Plutonium-239+240 in European topsoils",
486
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/caesium-137-and-plutonium-239240-european-topsoils",
487
+ "abstract": "Plutonium and Cesium inventories in European topsoils. Includes also the Chernobyl-derived 137Cs and Global-derived 137Cs"
488
+ },
489
+ "carbon-budget-eu-agricultural-soils": {
490
+ "title": "Carbon budget in the EU agricultural soils",
491
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/carbon-budget-eu-agricultural-soils",
492
+ "abstract": "Cumulative C budget over the period 2016-20100 in the EU agricultural soils under the accelerated and current soil erosion scenarios."
493
+ },
494
+ "clay-mineral-inventory-soils-europe-based-lucas-2015-survey-soil-samples-2": {
495
+ "title": "Clay mineral inventory in soils of Europe based on LUCAS 2015 survey soil samples",
496
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/clay-mineral-inventory-soils-europe-based-lucas-2015-survey-soil-samples-2",
497
+ "abstract": "These data are the input for the report \"Clay mineral inventory in soils of Europe based on LUCAS 2015 survey soil samples\" (2024). Clay minerals are a key factor in mineral soils as they are controlling physic, chemical and biological soil properties. The X-ray diffraction (XRD) analysis has been widely used to identify and quantify minerals in earth science The aim of the research reported is to describe the clay minerals in soils of Europe and United Kingdom by using soil samples from the Land Use/Cover Area Frame Survey (LUCAS) topsoil database sampled in 2015. A subset of 388 soil samples were selected from LUCAS 2015 topsoil survey."
498
+ },
499
+ "copper-distribution-topsoils": {
500
+ "title": "Copper distribution in topsoils in the European Union",
501
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/copper-distribution-topsoils",
502
+ "abstract": "Copper distribution in European Union topsoils based on LUCAS points. The data are at 500m resolution and have been the result of advanced interpolation modelling."
503
+ },
504
+ "cover-crops-accross-europe": {
505
+ "title": "Cover Crops across Europe",
506
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/cover-crops-accross-europe",
507
+ "abstract": "Disaggregated map of cover crops occurrence for Europe and the United Kingdom. Using a disaggregation model, we combined satellite data (Sentinel-1) with aggregated survey data to generate a high-resolution map (100m) of cover crops for Europe and the United Kingdom for the reference year of 2016."
508
+ },
509
+ "cover-management-factor-c-factor-eu": {
510
+ "title": "Cover Management factor (C-factor) for the EU",
511
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/cover-management-factor-c-factor-eu",
512
+ "abstract": "This dataset (GIS map) (2015) represents the Cover Management factor (C-factor), one of the input layers when calculating the Universal Soil Loss Equation (USLE) model, which is the most frequently used model for soil erosion risk estimation; for EU28; resolution 100m. The C-factor was estimated for a) arable lands based on crop composition and for b) all other land uses (non-arable) based on the vegetation density and land cover type. The management practices (reduced tillage/no till, plant residues and winter cover crops) were taken into account in estimating C-factor in arable lands."
513
+ },
514
+ "estimate-net-erosion-and-sediment-transport-using-watemsedem-european-union": {
515
+ "title": "Net erosion and sediment transport using WaTEM/SEDEM (for EU)",
516
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/estimate-net-erosion-and-sediment-transport-using-watemsedem-european-union",
517
+ "abstract": "Dataset (GIS map) (218) that shows the net soil erosion and deposition in European Union as a result of an application WaTEM/SEDEM model; resolution 100m; EU28. Data are also available at 25m resolution and at catchment scale."
518
+ },
519
+ "european-food-safety-authority-efsa-data-persam-software-tool": {
520
+ "title": "European Food Safety Authority (EFSA) Data & PERSAM software tool",
521
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/european-food-safety-authority-efsa-data-persam-software-tool",
522
+ "abstract": "Data and software made public as the result of a collaboration between JRC and EFSA. It contains soil, weather and crop data collected by JRC and organised by EFSA for its purpose. The site also hosts the software tool PERSAM for Predicting Environmental Concentrations in soil in support of the: \"EFSA Guidance Document for predicting environmental concentrations of active substances of plant protection products and transformation products of these active substances in soil\" which EFSA was asked by the European Commission to prepare. The data/maps are provided as rasters (ASCII grid). The soil data are: Topsoil Organic Matter content, Topsoil pH water, Topsoil Bulk Density, Topsoil Texture Class, Topsoil Water Content at Field Capacity."
523
+ },
524
+ "european-hydropedological-data-inventory-eu-hydi-database-0": {
525
+ "title": "European Hydropedological Data Inventory (EU-HYDI) database",
526
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/european-hydropedological-data-inventory-eu-hydi-database-0",
527
+ "abstract": "The European Hydropedological Data Inventory (EU-HYDI) contains soil properties with a special focus on hydrological properties. It also includes various other measured soil characteristics associated to the same samples. It can hence serve multiple purposes, including scientific research, modelling and application of models at different geographical scales. The dataset consists of 10 interlinked CSV files."
528
+ },
529
+ "european-map-soil-suitability-provide-platform-most-human-activities-eu28": {
530
+ "title": "European map of soil suitability to provide a platform for most human activities (EU28)",
531
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/european-map-soil-suitability-provide-platform-most-human-activities-eu28",
532
+ "abstract": "This dataset (map)(2016) presents the suitability of soil as a platform for most human activities in the EU. Calculation of suitability was done using vaious properties of the European Soil database (soil type, soil water regime, limitation to agricultural use, depth to rock, land use) and slope of the terrain."
533
+ },
534
+ "european-soil-database-derived-data": {
535
+ "title": "European Soil Database Derived data",
536
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/european-soil-database-derived-data",
537
+ "abstract": "A number of layers for soil properties have been created based on data from the European Soil Database in combination with data from the Harmonized World Soil Database (HWSD) and Soil-Terrain Database (SOTER)."
538
+ },
539
+ "european-soil-database-v2-raster-library-1kmx1km": {
540
+ "title": "European Soil Database v2 Raster Library 1kmx1km",
541
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/european-soil-database-v2-raster-library-1kmx1km",
542
+ "abstract": "This database (2024) is a new set of raster data (GeoTIFF) that have been derived from the European soil Database v2, for most attributes. The values for the attributes are categorized (non-continuous). These rasters are an interpretation of the data that are contained in the ESDB v2.0."
543
+ },
544
+ "global-rainfall-erosivity": {
545
+ "title": "Global Rainfall Erosivity",
546
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/global-rainfall-erosivity",
547
+ "abstract": "Rainfall erosivity dataset (2017) is one of the input layers when calculating the Revised Universal Soil Loss Equation (RUSLE) model, which is the most frequently used model for soil erosion risk estimation; for the whole World; R-factor map at resolutions of 30 arc-sec ((~1 km at the Equator)."
548
+ },
549
+ "global-soil-erodibility": {
550
+ "title": "Global Soil Erodibility",
551
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/global-soil-erodibility",
552
+ "abstract": "This dataset encompasses global soil erodibility (K) factor maps, with the K factor being estimated through the Wischmeier and Smith (1978) method. In addition, measured values of saturated hydraulic conductivity (Ksat) have been incorporated into the original method to formulate the Ksat-based soil erodibility (Kksat factor) map. A third k-factor dataset which was included in the GloSEM (Borrelli et al., 2017) is also included."
553
+ },
554
+ "global-soil-organic-carbon-estimates": {
555
+ "title": "Global Soil Organic Carbon Estimates",
556
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/global-soil-organic-carbon-estimates",
557
+ "abstract": "Global estimates of soil organic carbon stocks have been produced in the past to support the calculation of potential emissions of CO2 from the soil under scenarios of change land use/cover and climatic conditions."
558
+ },
559
+ "glosem": {
560
+ "title": "High resolution cropland global soil erosion (GloSEM 1.3)",
561
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/glosem",
562
+ "abstract": "Global Soil Erosion Modelling (GloSEM) platform containts 4 datasets on global soil erosion in arable lands (at 100m resolution): Baseline data (2019), soil loss in 2070 for three climatic scenarios RCP2.6, RCP4.5, RCP8.5"
563
+ },
564
+ "gully-erosion-based-lucas": {
565
+ "title": "Gully Erosion based on LUCAS",
566
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/gully-erosion-based-lucas",
567
+ "abstract": "The LUCAS topsoil survey 2018 included a module for visual assessment of gully erosion. Gully erosion channels were detected in 1% of the visited LUCAS topsoil sites. Find the 211 points declared as gully erosion."
568
+ },
569
+ "heavy-metals-topsoils": {
570
+ "title": "Heavy Metals in topsoils",
571
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/heavy-metals-topsoils",
572
+ "abstract": "GIS Maps (2008) produced by mapping the concentrations of eight critical heavy metals (arsenic, cadmium, chromium, copper, mercury, nickel, lead and zinc) using the 1588 georeferenced topsoil samples from the FOREGS Geochemical database. The concentrations were interpolated using block regression-kriging over the 26 European countries that contributed to the database."
573
+ },
574
+ "land-degradation-europe": {
575
+ "title": "Land Degradation in Europe",
576
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/land-degradation-europe",
577
+ "abstract": "This dataset includes the Land Multi-degradation Index (LMI) for arable and agricultural lands and data for 12 indicators (land degradation processes) which were compiled to develop the LMI. The dataset includes the agricultural (~2 million km2) and the arable (~1.1 million km2) lands of the EU and other European countries."
578
+ },
579
+ "land-suitability-temperate-europe": {
580
+ "title": "Land suitability in temperate Europe",
581
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/land-suitability-temperate-europe",
582
+ "abstract": "This datasets includes land suitability maps for several crops and land uses (14 crops , 7 fruit trees, 3 land-use types) in the temperate continental climate of Europe. To model the land suitability we used geospatial data depicting seventeen eco-pedological indicators (e.g. soil texture, pH, porosity, temperature, precipitation, slope). To evaluate how the land is utilized, the suitability maps have been spatially cross-tabulated with a crop map."
583
+ },
584
+ "ls-factor-slope-length-and-steepness-factor-eu": {
585
+ "title": "LS-factor (Slope Length and Steepness factor) for the EU",
586
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/ls-factor-slope-length-and-steepness-factor-eu",
587
+ "abstract": "This dataset (GIS maps) (2015) represents the \"Slope Length and Steepness factor\" (LS-factor), one of the six input layers when calculating the Universal Soil Loss Equation (USLE) model, which is the most frequently used model for soil erosion risk estimation; for EU28; maps at resolutions of 25m (per country) and 100m (Europe-wide)."
588
+ },
589
+ "lucas-2009-topsoil-data": {
590
+ "title": "LUCAS 2009 TOPSOIL data",
591
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/lucas-2009-topsoil-data",
592
+ "abstract": "Data from the 2009 LUCAS campaign soil component containing soil properties data (clay, silt and sand content, coarse fragments, pH, organic carbon content, CaCO3, nitrogen, phosphorous, potassium, cation exchane capacity) and multispectral absorbance data."
593
+ },
594
+ "lucas-2015-topsoil-data-switzerland": {
595
+ "title": "LUCAS 2015 Topsoil data of Switzerland",
596
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/lucas-2015-topsoil-data-switzerland",
597
+ "abstract": "The dataset contains the data of physical and chemical properties analysed in samples taken in Switzerland within the context of LUCAS 2015 survey. These data have been used in the study “Comparison of sampling with a spade and gouge auger for topsoil monitoring at the continental scale”, published in the European Journal of Soil Science (https://onlinelibrary.wiley.com/doi/abs/10.1111/ejss.12862). The dataset format is an Excel file."
598
+ },
599
+ "lucas-2018-topsoil-data": {
600
+ "title": "LUCAS 2018 TOPSOIL data",
601
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/lucas-2018-topsoil-data",
602
+ "abstract": "Data from the 2018 LUCAS campaign soil component containing soil properties data for 18,984 samples: pH (CaCl2 and H2O), organic carbon content, CaCO3, nitrogen, phosphorous, potassium, EC (Electrical conductivity), Oxalate extractable Fe and Al ."
603
+ },
604
+ "lucas2015-topsoil-data": {
605
+ "title": "LUCAS 2015 TOPSOIL data",
606
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/lucas2015-topsoil-data",
607
+ "abstract": "Data from the 2015 LUCAS campaign soil component containing soil properties data (clay, silt and sand content, coarse fragments, pH (CaCl2 and H2O), organic carbon content, CaCO3, nitrogen, phosphorous, potassium, EC (Electrical conductivity) and multispectral reflectance data for 21,859 samples. These primary data are supplemented by reference ancillary data describing a range of environmental conditions for the LUCAS Soil locations."
608
+ },
609
+ "map-indicating-availability-raw-material-soils-european-union-organic-soil-material-b-soil": {
610
+ "title": "Maps indicating the availability of Raw Material from soils in the European Union",
611
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/map-indicating-availability-raw-material-soils-european-union-organic-soil-material-b-soil",
612
+ "abstract": "This dataset (maps)(2016) indicates the availability of Raw Material (organic soil material and soil material for constructions) from soils in the European Union."
613
+ },
614
+ "maps-heavy-metals-soils-eu-based-lucas-2009-hm-data-0": {
615
+ "title": "Maps of heavy metals in the soils of the EU, based on LUCAS 2009 HM data",
616
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/maps-heavy-metals-soils-eu-based-lucas-2009-hm-data-0",
617
+ "abstract": "Detailed maps of heavy metals in the EU27 (EU-28 except Croatia), based on topsoil HM data from LUCAS 2009"
618
+ },
619
+ "maps-indicators-soil-hydraulic-properties-europe": {
620
+ "title": "Maps of indicators of soil hydraulic properties for Europe",
621
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/maps-indicators-soil-hydraulic-properties-europe",
622
+ "abstract": "Soil hydraulic properties maps (2016) for Europe: for Water retention of topsoil: saturated water content (cm3/cm3), water content at field capacity (cm3/cm3), water content at wilting point (cm3/cm3); for Hydraulic conductivity of topsoil: saturated hydraulic conductivity (cm/day). Besides the true values in the units mentioned values scaled between 1 and 10 without measurement units were also calculated."
623
+ },
624
+ "maps-related-predicting-preservation-cultural-artefacts-and-buried-materials-soils-eu-0": {
625
+ "title": "Maps of preservation capacity of cultural artefacts and buried materials in soils in the EU",
626
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/maps-related-predicting-preservation-cultural-artefacts-and-buried-materials-soils-eu-0",
627
+ "abstract": "Maps (2016) that indicate the preservation capacity of cultural artefacts and buried materials in soils in the EU, for bones, teeth and shells (bones), organic materials (organics), metals (Cu, bronze and Fe) (metals), stratigraphic evidence (strati)."
628
+ },
629
+ "maps-storing-and-filtering-capacity-soils-europe": {
630
+ "title": "Maps of the Storing and Filtering Capacity of Soils in Europe",
631
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/maps-storing-and-filtering-capacity-soils-europe",
632
+ "abstract": "This dataset (2016) contains 10 maps that relate to the soil's storing and filtering capacity in Europe (the EU only): cation storing capacity (STOR_CAPCA), cation filtering capacity (FILT_CAPCA), anion storing capacity (STOR_CAPAN), anion filtering capacity (FILT_CAPAN), solids and pathogenic microorganisms storing capacity (STOR_CAPSO), solids and pathogenic microorganisms filtering capacity (FILT_CAPSO), non-polar organic chemicals storing capacity (STOR_CAPNP), non-polar organic chemicals filtering capacity (FILT_CAPNP), nonaqueous Phase Liquids (NAPL) storing capacity (STOR_NAPL), nonaqueous Phase Liquids (NAPL), filtering capacity (FILT_NAPL). As input, variables from the European Soil Database have been used."
633
+ },
634
+ "mercury-content-european-union-topsoil": {
635
+ "title": "Mercury content in the European Union topsoil",
636
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/mercury-content-european-union-topsoil",
637
+ "abstract": "Topsoil Hg concentrations (μg kg−1) across 26 EU countries estimated by deep neural network – regression kriging. We also provide Mercury stocks and mercury fluxes to main riverbasins and sea outlets. The assessment is based on 21591 LUCAS samples (0-20cm) from 26 European Union countries."
638
+ },
639
+ "multiple-concurrent-soil-erosion-processes": {
640
+ "title": "Multiple concurrent soil erosion processes",
641
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/multiple-concurrent-soil-erosion-processes",
642
+ "abstract": "A first-ever assessment at European scale combines the threat of water, wind, tillage and harvesting to reveal the cumulative impact on arable land. We present the datasets for each of the erosion process (water, wind, tillage, harvesting root crops) and their cumulative effect at 100m resolution for EU arable lands (110 Million ha)."
643
+ },
644
+ "n2o-emissions-agricultural-soils-europe": {
645
+ "title": "N2O emissions from agricultural soils in Europe",
646
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/n2o-emissions-agricultural-soils-europe",
647
+ "abstract": "This dataset derives from the integration of the LUCAS soil survey with the bio-geochemistry process-based model DayCent. The model was ran for more than 11,000 LUCAS sampling points under agricultural use, assessing also the model uncertainty. Meta-models based on model outcomes and the Random Forest algorithm were used to upscale the N2O emissions at 1km resolution."
648
+ },
649
+ "natural-susceptibility-soil-compaction-europe": {
650
+ "title": "Natural susceptibility to soil compaction in Europe",
651
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/natural-susceptibility-soil-compaction-europe",
652
+ "abstract": "Map (2008) showing the natural susceptibility of agricultural soils to compaction if they were to be exposed to compaction, based on the creation of logical connections between relevant parameters (using pedotransfer rules), taking as input parameters attributes of the European soil database (soil type, texture, etc.). For EU-27."
653
+ },
654
+ "observedtypical-soc-index": {
655
+ "title": "Observed/typical SOC index",
656
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/observedtypical-soc-index",
657
+ "abstract": "Observed/typical Soil Organic Carbon (SOC) index classes and associated pedo-climate zones across the EU and UK are presented in 2 GeoTiff files at 100 m resolution."
658
+ },
659
+ "octop-topsoil-organic-carbon-content-europe": {
660
+ "title": "OCTOP: Topsoil Organic Carbon Content for Europe",
661
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/octop-topsoil-organic-carbon-content-europe",
662
+ "abstract": "A 2004 GIS map of Soil Organic Carbon (SOC) content (%) in the surface horizon of soils in Europe, associated to a JRC internal report."
663
+ },
664
+ "pan-european-soc-stock-agricultural-soils": {
665
+ "title": "Pan-European SOC stock of agricultural soils",
666
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/pan-european-soc-stock-agricultural-soils",
667
+ "abstract": "Data (2014) related to Pan-European SOC stock of agricultural soils, containing GIS maps for a) Pan-European SOC stock of agricultural soils (shapefile), b) Potential carbon sequestration by modelling a comprehensive set of management practices (shapefile), c) Average Eroded SOC in agricultural soils (raster)."
668
+ },
669
+ "pan-european-soil-erosion-risk-assessment-pesera": {
670
+ "title": "Pan European Soil Erosion Risk Assessment - PESERA",
671
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/pan-european-soil-erosion-risk-assessment-pesera",
672
+ "abstract": "A 2003 GIS map of Soil erosion estimates (t/ha/yr) by applying the PESERA GRID (physical) model at 1km, using the European Soil Database, CORINE land cover, climate data from the MARS Project and a Digital Elevation Model. The resulting estimates of sediment loss are from erosion by water."
673
+ },
674
+ "phosphorus-budget-and-p-stocks": {
675
+ "title": "Phosphorus budget and P stocks",
676
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/phosphorus-budget-and-p-stocks",
677
+ "abstract": "Phosphorus (P) budget in the European agricultural soils. We provide shape files with main inputs (fertilizers, manure, chemical weathering, atmospheric deposition) and the losses by water erosion. In addition, we model the Total P and the relevant P stocks (available/Olsen, Total). We also make available 21,681 LUCAS point data with measured Total P."
678
+ },
679
+ "phosphorus-cycle-european-agricultural-soils": {
680
+ "title": "Phosphorus cycle in European agricultural soils",
681
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/phosphorus-cycle-european-agricultural-soils",
682
+ "abstract": "Process-based biogeochemical models are valuable instruments to monitor the P cycle and predict the effect of agricultural management policies. We upscale the calibrated DayCent model at European level using data-derived soil properties, advanced input data sets, and representative management practices. Available datasets include Current P Budget and Soil Pools, Projected P Budget and Soil Pools for the EU and UK as well the datasets corresponding to the figures of the related manuscript."
683
+ },
684
+ "potential-threats-soil-biodiversity-europe": {
685
+ "title": "Potential threats to soil biodiversity in Europe",
686
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/potential-threats-soil-biodiversity-europe",
687
+ "abstract": "Dataset that contains 3 GIS maps showing Potential threats to soil biodiversity in Europe (for soil microorganisms, for fauna,forbiological functions), along with 13 input layers (habitat fragmentation, climate change, soil erosion, etc.); resolution 500m."
688
+ },
689
+ "priming-effects-soils-across-europe": {
690
+ "title": "Glucose-induced priming effects in soils across Europe",
691
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/priming-effects-soils-across-europe",
692
+ "abstract": "Quantification and comparison of glucose-induced priming effects in soils with contrasting land uses and under different crop types"
693
+ },
694
+ "rainfall-erosivity-european-union-and-switzerland": {
695
+ "title": "Rainfall Erosivity in the EU and Switzerland (R-factor)",
696
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/rainfall-erosivity-european-union-and-switzerland",
697
+ "abstract": "Dataset (GIS map) (2015) and associated products for the \"Rainfall erosivity\" (R-factor), one of the input layers when calculating the Universal Soil Loss Equation (USLE) model, which is the most frequently used model for soil erosion risk estimation; for EU28+Switzerland; R-factor map at resolutions of 500m. Users can downloads Raw data, Baseline map (2010), Monthly erosivity, Future projections (2050), Past erosivity (1961-2000)."
698
+ },
699
+ "SOC-changes-2009-18": {
700
+ "title": "Changes in Soil Organic Carbon in Croplands and Grasslands between 2009 and 2018",
701
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/SOC-changes-2009-18",
702
+ "abstract": "This dataset (map) illustrates the variations in soil organic carbon (measured in g C kg y-1) within the 0-20 cm depth range for croplands and grasslands across the EU and UK between 2009 and 2018."
703
+ },
704
+ "soil-biomass-productivity-maps-grasslands-and-pasture-coplands-and-forest-areas-european": {
705
+ "title": "Soil Biomass Productivity maps of grasslands and pasture, of croplands and of forest areas in the European Union (EU27)",
706
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-biomass-productivity-maps-grasslands-and-pasture-coplands-and-forest-areas-european",
707
+ "abstract": "This dataset consists of 3 GIS maps that indicate the soil biomass productivity of grasslands and pasture, of croplands and of forest areas in the European Union (EU27)"
708
+ },
709
+ "soil-bulk-density-europe": {
710
+ "title": "Soil Bulk Density in Europe",
711
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-bulk-density-europe",
712
+ "abstract": "This dataset includes bulk density for Europe in 0-20cm, 0-10cm, 10-20cm layers generated with advanced Cubist rule-based regression model. We also provide the Packing density estimation based on bulk density and clay content. In addition, we make available the point data measurements of bulk density"
713
+ },
714
+ "soil-carbon-risk-index": {
715
+ "title": "Soil Carbon Risk Index",
716
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-carbon-risk-index",
717
+ "abstract": "This dataset includes the a) Soil organic carbon risk index b) SOC fractions predicted by visible near-infrared c) the mineral-associated organic carbon (MAOC) saturation.This repository accompanies the publication \"Revisiting the soil carbon saturation concept to inform a risk index in European agricultural soils\" and can be used to access the results and code."
718
+ },
719
+ "soil-degradation-indicators-eu": {
720
+ "title": "Soil degradation indicators in EU",
721
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-degradation-indicators-eu",
722
+ "abstract": "Pan-EU assessment of soil degradation based on the latest state-of-the-art indicators of soil degradation as demonstrated in the EU Soil Health Dashboard. This dataset includes the 19 Soil degradation indicators plus the sum of all processes."
723
+ },
724
+ "soil-erodibility-k-factor-high-resolution-dataset-europe": {
725
+ "title": "Soil Erodibility (K- Factor) High Resolution dataset for Europe",
726
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-erodibility-k-factor-high-resolution-dataset-europe",
727
+ "abstract": "Map at 500m resolution (2014) providing a complete picture of the soil erodibility in the European Union member states. It is derived on the basis of the LUCAS 2009 soil survey exercise and the European Soil Database."
728
+ },
729
+ "soil-erosion-forestland-europe-using-rusle2015": {
730
+ "title": "Soil erosion in forestland in Europe (using RUSLE2015)",
731
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-erosion-forestland-europe-using-rusle2015",
732
+ "abstract": "Dataset (2 GIS-maps) (2016) related to soil erosion in Forestland in Europe. One map is the soil loss potential for EU28; the other map is the European Forest Cover Change for 36 European countries."
733
+ },
734
+ "soil-erosion-water-rusle2015": {
735
+ "title": "Soil erosion by water (RUSLE2015)",
736
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-erosion-water-rusle2015",
737
+ "abstract": "Dataset (GIS map) (2015) that shows the Soil Loss by Water Erosion in Europe and is the result of applying a modified version of the Revised Universal Soil Loss Equation (RUSLE) model, RUSLE 2015; resolution 100m. EU28. Two data points are available: 2010 and 2016"
738
+ },
739
+ "soil-function-data-measured-lucas-2018-sites-across-eu": {
740
+ "title": "Soil function data measured in LUCAS 2018 sites across the EU",
741
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-function-data-measured-lucas-2018-sites-across-eu",
742
+ "abstract": "In the LUCAS 2018 survey, soil functions have been measured in the 881 sampling sites selected for the soil biodiversity assessment across Europe. These soil functions include * soil aggregates (i.e., mean width diameter and water-stable aggregates), * enzyme activities, * microbial respiration and biomass, and * measurement of ester-linked fatty acid methyl esters (FAMEs)."
743
+ },
744
+ "soil-ghg-fluxes-using-lucas-soil-daycent": {
745
+ "title": "Soil GHG fluxes using LUCAS soil-DayCent (for EU)",
746
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-ghg-fluxes-using-lucas-soil-daycent",
747
+ "abstract": "Soil fluxes (CO2 and N2O ) under mitigation scenarios using the LUCAS soil-DayCent model integration framework"
748
+ },
749
+ "soil-loss-due-crop-harvesting-european-union": {
750
+ "title": "Soil loss due to crop harvesting in the European Union",
751
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-loss-due-crop-harvesting-european-union",
752
+ "abstract": "Soil loss due to crop harvesting in the European Union. The regional estimates of total Soil Loss by Crop Harvesting (SLCH) are presented at country and regional level."
753
+ },
754
+ "soil-microbial-biomass-and-respiration": {
755
+ "title": "Soil microbial biomass and respiration",
756
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-microbial-biomass-and-respiration",
757
+ "abstract": "Maps of potential soil microbial basal respiration (bas), microbial biomass (Cmic), and respiratory quotient (qO2) predicted across Europe. Monthly maps for bas and Cmic are also available"
758
+ },
759
+ "soil-organic-carbon-saturation-capacity": {
760
+ "title": "Soil Organic Carbon - Saturation Capacity in Europe",
761
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-organic-carbon-saturation-capacity",
762
+ "abstract": "This dataset (map) (2016) shows the Soil Organic Carbon (SOC) saturation capacity, expressed as the ratio between the actual and the potential SOC stock in each pixel. Values close to 0 indicate a great potential of soil to store more carbon."
763
+ },
764
+ "soil-organic-matter-som-fractions": {
765
+ "title": "Soil Organic Matter (SOM) fractions",
766
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/soil-organic-matter-som-fractions",
767
+ "abstract": "This dataset contains the original measured Soil Organic Matter (SOM) fractions of a subset of the LUCAS 2009 topsoil dataset. This dataset includes 352 samples for all land uses and 186 samples only for grassland and fores used to derived maps on Particulate Organic Matter (POM) and Mineral-Associated Organic Matter (MAOM)"
768
+ },
769
+ "Soil_erosion_by_wind": {
770
+ "title": "Soil erosion by wind",
771
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/Soil_erosion_by_wind",
772
+ "abstract": "This dataset consists of various elements related to soil erosion by wind: 1) Soil loss by wind erosion in European agricultural soils (2016); 1km resolution, 2) Land susceptibility to wind erosion (2014), 500m resolution, 3) Wind erosion susceptibility of European soils (2014); 500m resolutiomn, and 4) Agriculture Field Parameters data (containing averaged Field Size, Field Orientation, Field Length, Average Number of Images, Percentage of Large Fields and Length to Width Ratios) for the EU 27 Member states and Switzerland, aggregated to NUTS region."
773
+ },
774
+ "spadem": {
775
+ "title": "SPADE/M",
776
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/spadem",
777
+ "abstract": "Database (2004) developed from the measured profiles; present in the Soil Profile Analytical Database of Europe of the European Soil Database v2. It counts 560 profiles within the EU."
778
+ },
779
+ "support-practices-factor-p-factor-eu": {
780
+ "title": "Support Practices factor (P-factor) for the EU",
781
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/support-practices-factor-p-factor-eu",
782
+ "abstract": "This GIS map (2015) represents the \"Support Practices factor\" (P-factor) for the EU. At European level, the effect of support practices (compulsory for farmers to receive incentives under the CAP-GAEC) on soil loss were assessed by P-factor estimation taking into account a) contour farming b) maintenance of stone walls and c) grass margins. Resolution 1km."
783
+ },
784
+ "topsoil-soil-organic-carbon-lucas-eu25": {
785
+ "title": "Topsoil Soil Organic Carbon (LUCAS) for EU25",
786
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/topsoil-soil-organic-carbon-lucas-eu25",
787
+ "abstract": "This dataset (2015) provides maps for Topsoil Soil Organic Carbon in EU-25 that are based on LUCAS 2009 soil poibnt data through a generalized additive model. Map of predicted topsoil organic carbon content (g C kg-1) : The map of predicted topsoil organic carbon content (g C kg-1) was produced by fitting a generalised additive model between organic carbon measurements from the LUCAS survey (dependent variable) and a set of selected environmental covariates; namely slope, land cover, annual accumulated temperature, net primary productivity, latitude and longitude. It also includes a Map of standard error of the OC model predictions (g C kg-1)."
788
+ },
789
+ "un-sustainable-development-goal-1531-assessment-land-degradation-indicator-eu-scale": {
790
+ "title": "UN Sustainable Development Goal 15.3.1: Assessment of the land degradation indicator at EU scale",
791
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/un-sustainable-development-goal-1531-assessment-land-degradation-indicator-eu-scale",
792
+ "abstract": "This dataset covers 9 maps associated to the assessment of the land degradation indicator at EU scale in the context of the UN Sustainable Development Goal 15.3.1, and corresponding to the output reported in a peer-reviewed publication. The main map is the one that expresses land degradation on the basis of soil organic carbon and soil erosion values."
793
+ },
794
+ "zn-concentrations-eu-topsoils": {
795
+ "title": "Zinc concentrations in EU topsoils",
796
+ "dataset_url": "https://esdac.jrc.ec.europa.eu/content/zn-concentrations-eu-topsoils",
797
+ "abstract": "Zinc (Zn) is essential to sustain crop production and human health, while it can be toxic when present in excess. The Zn concentration (mg kg-1) in European topsoils as predicted by the quantile regression forest using the 21,682 samples of LUCAS. The resolution of this map is 250 m by 250 m."
798
+ }
799
+ }
800
+ ```
801
+ =========End of meta_fused_datasets.json=========
802
+
gpt_resources/prompt.md ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are **ERP-GPT-EU**, an expert AI assistant for querying, analyzing, and interpreting high-resolution soil data across Europe.
2
+
3
+ Your behavior, data access, and tool usage are governed by two authoritative knowledge bases:
4
+
5
+ - **`knowledge_dataset.md`** — defines the LUCAS-MEGA fused dataset, including its origin, scale, structure, properties, metadata, and terminology.
6
+ - **`knowledge_api.md`** — defines the geographic resolution and soil data-retrieval APIs, including recommended usage patterns and sequencing.
7
+
8
+ These documents are **authoritative**.
9
+ Do not invent new dataset fields, APIs, or dataset semantics.
10
+ If requested information is not present in the dataset or APIs, state this explicitly.
11
+
12
+ Your users include scientists, agronomists, land managers, policy makers, and data analysts.
13
+ Your responses must be scientifically accurate, explicit about uncertainty, and clearly structured.
14
+
15
+ ---
16
+
17
+ ## 🔧 Technical Specifications
18
+
19
+ ### 1. Session Handling
20
+ - At the start of each conversation, silently generate a random ASCII-only session name
21
+ (UUID-like, no spaces; e.g. `soil-gpt-session-h3k92fa7`).
22
+ - Use the same session name for **all tool calls** in the conversation so that generated map files remain isolated per user.
23
+ - The session name is **internal only** and must never be revealed or mentioned.
24
+
25
+ ---
26
+
27
+ ### 2. Dataset Awareness & Scientific Reasoning
28
+ - You have structured access to the **LUCAS-MEGA** dataset, comprising:
29
+ - tens of thousands of soil samples (rows),
30
+ - up to ~1,000 soil and ecosystem properties (columns).
31
+ - You may explain soil science concepts using general scientific knowledge.
32
+ - **All numerical values, statistics, sample attributes, or maps must be retrieved via the APIs**, never inferred from memory or assumption.
33
+ - Dataset metadata provides context (e.g. sources, uncertainty, missingness) but does not replace data retrieval.
34
+ - When scientific interpretation is uncertain, rely on widely accepted, non-speculative knowledge.
35
+
36
+ ---
37
+
38
+ ### 3. API-Driven Data Access
39
+ - All **authoritative geographic resolution** and **soil data access** must use the APIs defined in `knowledge_api.md`, including:
40
+ - resolving place names or coordinates to GADM regions,
41
+ - retrieving point-based (sample-level) soil properties,
42
+ - generating spatial property maps.
43
+ - Never simulate, fabricate, or bypass an API when retrieving data.
44
+ - If requested data does not exist in the dataset, say so clearly.
45
+ - **[Very Important]** You must infer the most relevant soil property names from user input. For example, if the user asks for soil texture, you should use these properties:
46
+ - clay_percentage
47
+ - silt_percentage
48
+ - sand_percentage
49
+ - coarse_percentage
50
+
51
+ The full property list is given in Knowledge (`meta_column_names.json`). The following are selected ones that are more likely to be requested than others:
52
+
53
+ ```json
54
+ {
55
+ "properties": [
56
+ "photos",
57
+ "climate_change_pressure_index",
58
+ "genetically_modified_organism_use_pressure_index",
59
+ "habitat_fragmentation_pressure_index",
60
+ "industrial_pollution_pressure_index",
61
+ "intensive_human_exploitation_pressure_index",
62
+ "land_use_change_pressure_index",
63
+ "organic_matter_decline_pressure_index",
64
+ "radioactivity_pressure_index",
65
+ "soil_biological_functions_threat_index",
66
+ "soil_compaction_pressure_index",
67
+ "soil_erosion_pressure_index",
68
+ "soil_fauna_threat_index",
69
+ "soil_microorganisms_threat_index",
70
+ "soil_salinity_pressure_index",
71
+ "basal_respiration_general",
72
+ "basal_respiration_landcover",
73
+ "microbial_biomass_general",
74
+ "microbial_biomass_landcover",
75
+ "respiratory_quotient_general",
76
+ "respiratory_quotient_landcover",
77
+ "soil_biomass_productivity_cropland",
78
+ "CaCO3_content",
79
+ "SOC_saturation_ratio",
80
+ "eroded_carbon_stock",
81
+ "eroded_soc_content",
82
+ "estimated_organic_carbon_density_subsoil",
83
+ "estimated_organic_carbon_density_topsoil",
84
+ "observed_vs_typical_soc_index",
85
+ "observed_vs_typical_soc_index_confidence_zone",
86
+ "organic_carbon_content",
87
+ "organic_carbon_content_subsoil_ESDB",
88
+ "organic_carbon_content_topsoil",
89
+ "organic_carbon_content_topsoil_ESDB",
90
+ "soc_change_2009_2018",
91
+ "topsoil_OC_prediction_mean",
92
+ "topsoil_OC_prediction_std",
93
+ "electrical_conductivity",
94
+ "pH_in_CaCl2",
95
+ "pH_in_H2O",
96
+ "pH_in_H2O_EFSA",
97
+ "annual_precipitation",
98
+ "annual_temperature",
99
+ "cover_crop_fraction_5th_percentile",
100
+ "cover_crop_fraction_95th_percentile",
101
+ "cover_crop_fraction_median",
102
+ "cover_crop_fraction_std",
103
+ "durum_wheat_fraction",
104
+ "effective_rooting_depth",
105
+ "fallow_fraction",
106
+ "ls_factor_slope_length_and_steepness",
107
+ "net_erosion_rate_PESERA",
108
+ "net_erosion_rate_WaTEM_SEDEM",
109
+ "soil_displacement_estimate",
110
+ "soil_loss_by_water",
111
+ "K_extractable",
112
+ "N_extractable",
113
+ "P_available_stock",
114
+ "P_extractable",
115
+ "P_total_concentration_topsoil",
116
+ "P_total_stock_topsoil",
117
+ "field_capacity_water_content",
118
+ "field_capacity_water_content_EFSA",
119
+ "saturated_hydraulic_conductivity",
120
+ "saturated_water_content",
121
+ "topographic_wetness_index",
122
+ "total_available_water_capacity_subsoil_ESDB",
123
+ "total_available_water_capacity_subsoil_SMU_ESDB",
124
+ "total_available_water_capacity_topsoil_ESDB",
125
+ "total_available_water_capacity_topsoil_SMU_ESDB",
126
+ "wilting_point_water_content",
127
+ "aridity_index_mean_cropland",
128
+ "land_multi_degradation_index_agricultural_lands",
129
+ "soil_erosion_exceeding_10Mg_ha_yr",
130
+ "nighttime_light_intensity",
131
+ "solar_radiation_input",
132
+ "bulk_density",
133
+ "bulk_density_0_10cm",
134
+ "bulk_density_10_20cm",
135
+ "bulk_density_subsoil_ESDB",
136
+ "bulk_density_topsoil_EFSA",
137
+ "bulk_density_topsoil_ESDB",
138
+ "packing_density",
139
+ "organic_matter_content",
140
+ "clay_percentage",
141
+ "clay_percentage_subsoil_ESDB",
142
+ "clay_percentage_topsoil_ESDB",
143
+ "coarse_percentage",
144
+ "coarse_percentage_subsoil_ESDB",
145
+ "coarse_percentage_topsoil_ESDB",
146
+ "sand_percentage",
147
+ "sand_percentage_subsoil_ESDB",
148
+ "sand_percentage_topsoil_ESDB",
149
+ "silt_percentage",
150
+ "silt_percentage_subsoil_ESDB",
151
+ "silt_percentage_topsoil_ESDB",
152
+ "digital_elevation_model",
153
+ "elevation",
154
+ "slope",
155
+ "As_concentration_1km_res",
156
+ "Cd_concentration",
157
+ "Co_concentration_1km_res",
158
+ "Cr_concentration_variance_1km_res",
159
+ "Cu_concentration",
160
+ "Hg_concentration",
161
+ "Hg_residual",
162
+ "Hg_stock",
163
+ "Mn_concentration_1km_res",
164
+ "Pb_concentration_1km_res",
165
+ "Sb_concentration_1km_res",
166
+ "Zn_concentration"
167
+ ]
168
+ }
169
+ ```
170
+
171
+ **[Critical Instruction]**
172
+
173
+ If any API response includes direct image URLs (e.g., `.png`, `.jpg`, `.jpeg`, `.webp`), you must output each image URL **exactly as plain text** in the chat immediately after receiving it.
174
+
175
+ Do **not** wrap the URL in Markdown links:
176
+
177
+ ✅ Correct:
178
+ https://example.com/image.png
179
+
180
+ ❌ Incorrect:
181
+ [View Image](https://example.com/image.png)
182
+ ![img](https://example.com/image.png)
183
+
184
+ ---
185
+
186
+ ## 🧠 Scientific Assistant Role
187
+
188
+ You are not merely an API interface.
189
+
190
+ Your role includes:
191
+ - interpreting retrieved soil data,
192
+ - explaining uncertainty, spatial scale, and data limitations,
193
+ - comparing properties, regions, or scenarios when appropriate,
194
+ - synthesizing insights across multiple soil attributes,
195
+ - helping users understand **what the data implies**, not just what it returns.
196
+
197
+ Always distinguish clearly between:
198
+ - **observed data** (retrieved values),
199
+ - **metadata-based context** (sources, uncertainty, coverage),
200
+ - and **scientific interpretation**.
201
+
202
+ **Maintain the big picture**:
203
+ soil data gains value only when it is **contextualized, qualified, and communicated clearly**.
204
+
205
+ **Author**
206
+ Dr. Kuangdai Leng
207
+ Earth Rover Program (ERP)
gpt_resources/schema.json ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "openapi": "3.1.1",
3
+ "info": {
4
+ "title": "ERP-GPT-Europe Tool API",
5
+ "version": "1.0.0"
6
+ },
7
+ "servers": [
8
+ {
9
+ "url": "https://api.erp-soilgpt.uk/"
10
+ }
11
+ ],
12
+ "paths": {
13
+ "/resolve_place": {
14
+ "post": {
15
+ "summary": "Resolve a place name to coordinates, bounding box, and GADM region",
16
+ "description": "Use this tool to resolve a place name or fallback country into coordinates, bounding box, and GADM ID using Nominatim and hierarchical region matching. Useful as the first step before spatial or soil queries.",
17
+ "operationId": "resolve_place",
18
+ "requestBody": {
19
+ "required": true,
20
+ "content": {
21
+ "application/json": {
22
+ "schema": {
23
+ "type": "object",
24
+ "properties": {
25
+ "place_name": {
26
+ "type": "string",
27
+ "description": "The name of the place to resolve, such as 'Kisumu' or 'Lake Victoria'."
28
+ },
29
+ "fallback": {
30
+ "type": "string",
31
+ "description": "Optional fallback country to help disambiguate the place, e.g., 'Kenya'."
32
+ },
33
+ "session_name": {
34
+ "type": "string",
35
+ "description": "A required session identifier (random, internal) to ensure output file isolation."
36
+ }
37
+ },
38
+ "required": [
39
+ "place_name",
40
+ "session_name"
41
+ ]
42
+ }
43
+ }
44
+ }
45
+ },
46
+ "responses": {
47
+ "200": {
48
+ "description": "Successful place resolution with coordinates, bounding box, and GADM region",
49
+ "content": {
50
+ "application/json": {
51
+ "schema": {
52
+ "type": "object",
53
+ "properties": {
54
+ "status": {
55
+ "type": "string",
56
+ "description": "Text message describing the result or fallback used"
57
+ },
58
+ "used_name": {
59
+ "type": [
60
+ "string",
61
+ "null"
62
+ ],
63
+ "description": "The actual query string used, possibly with fallback country appended"
64
+ },
65
+ "latitude": {
66
+ "type": [
67
+ "number",
68
+ "null"
69
+ ],
70
+ "description": "Latitude in decimal degrees (WGS84)"
71
+ },
72
+ "longitude": {
73
+ "type": [
74
+ "number",
75
+ "null"
76
+ ],
77
+ "description": "Longitude in decimal degrees (WGS84)"
78
+ },
79
+ "bbox_area": {
80
+ "type": [
81
+ "number",
82
+ "null"
83
+ ],
84
+ "description": "Approximate area of the bounding box in square degrees"
85
+ },
86
+ "gid": {
87
+ "type": [
88
+ "string",
89
+ "null"
90
+ ],
91
+ "description": "Best matching GADM ID (e.g., 'KEN.1.3_1') or null if not found"
92
+ }
93
+ }
94
+ }
95
+ }
96
+ }
97
+ }
98
+ }
99
+ }
100
+ },
101
+ "/gadm/find_gid": {
102
+ "post": {
103
+ "summary": "Find the best matching GADM region for a location",
104
+ "description": "Given a geographic point (latitude and longitude), this tool returns the most likely GADM administrative region ID (GID). If `return_all` is true, it returns a list of all matching regions (from leaf to higher levels), sorted by bounding-box similarity. Typically used after /resolve_place.",
105
+ "operationId": "gadm_find_gid",
106
+ "requestBody": {
107
+ "required": true,
108
+ "content": {
109
+ "application/json": {
110
+ "schema": {
111
+ "type": "object",
112
+ "properties": {
113
+ "lat": {
114
+ "type": "number",
115
+ "description": "Latitude of the location (in decimal degrees)"
116
+ },
117
+ "lon": {
118
+ "type": "number",
119
+ "description": "Longitude of the location (in decimal degrees)"
120
+ },
121
+ "bbox_area": {
122
+ "type": "number",
123
+ "nullable": true,
124
+ "description": "Optional bounding box area (in square degrees) used to select the best matching GADM region when multiple regions contain the point"
125
+ },
126
+ "return_all": {
127
+ "type": "boolean",
128
+ "default": false,
129
+ "description": "If true, returns a list of all matching GADM regions; otherwise returns only the best match"
130
+ }
131
+ },
132
+ "required": [
133
+ "lat",
134
+ "lon"
135
+ ]
136
+ }
137
+ }
138
+ }
139
+ },
140
+ "responses": {
141
+ "200": {
142
+ "description": "Matching region(s) with status",
143
+ "content": {
144
+ "application/json": {
145
+ "schema": {
146
+ "oneOf": [
147
+ {
148
+ "type": "object",
149
+ "properties": {
150
+ "status": {
151
+ "type": "string",
152
+ "description": "Message describing result — e.g., success or failure"
153
+ },
154
+ "gid": {
155
+ "type": [
156
+ "string",
157
+ "null"
158
+ ],
159
+ "description": "Best matching GADM ID (e.g., 'UGA.2.5_1'), or null if no match"
160
+ }
161
+ },
162
+ "required": [
163
+ "status",
164
+ "gid"
165
+ ]
166
+ },
167
+ {
168
+ "type": "object",
169
+ "properties": {
170
+ "status": {
171
+ "type": "string",
172
+ "description": "Message describing result — e.g., success or failure"
173
+ },
174
+ "gids": {
175
+ "type": "array",
176
+ "items": {
177
+ "type": "string"
178
+ },
179
+ "description": "List of all matching GADM region IDs"
180
+ }
181
+ },
182
+ "required": [
183
+ "status",
184
+ "gids"
185
+ ]
186
+ }
187
+ ]
188
+ }
189
+ }
190
+ }
191
+ }
192
+ }
193
+ }
194
+ },
195
+ "/gadm/get_full_name": {
196
+ "post": {
197
+ "summary": "Get the full hierarchical name of a GADM region",
198
+ "description": "Returns a semicolon-separated string of the full hierarchy for a given GADM ID (e.g., 'Subcounty; County; Country'). This is useful for showing human-readable names after identifying a region by GID.",
199
+ "operationId": "gadm_get_full_name",
200
+ "requestBody": {
201
+ "required": true,
202
+ "content": {
203
+ "application/json": {
204
+ "schema": {
205
+ "type": "object",
206
+ "properties": {
207
+ "gid": {
208
+ "type": "string",
209
+ "description": "The GADM ID to query, e.g., 'KEN.1.2_1'"
210
+ }
211
+ },
212
+ "required": [
213
+ "gid"
214
+ ]
215
+ }
216
+ }
217
+ }
218
+ },
219
+ "responses": {
220
+ "200": {
221
+ "description": "Full name result with status",
222
+ "content": {
223
+ "application/json": {
224
+ "schema": {
225
+ "type": "object",
226
+ "properties": {
227
+ "status": {
228
+ "type": "string",
229
+ "description": "Indicates whether the GADM ID was found"
230
+ },
231
+ "full_name": {
232
+ "type": [
233
+ "string",
234
+ "null"
235
+ ],
236
+ "description": "Hierarchical name from smallest to country level (semicolon-separated), or null if not found"
237
+ }
238
+ },
239
+ "required": [
240
+ "status",
241
+ "full_name"
242
+ ]
243
+ }
244
+ }
245
+ }
246
+ }
247
+ }
248
+ }
249
+ },
250
+ "/gadm/get_geometry_info": {
251
+ "post": {
252
+ "summary": "Get spatial metadata of a GADM region",
253
+ "description": "Returns the centroid and bounding box of the polygon associated with a given GADM ID. Results are flattened at the top level for easier access. Useful for map settings, distance reasoning, or visualisation.",
254
+ "operationId": "gadm_get_geometry_info",
255
+ "requestBody": {
256
+ "required": true,
257
+ "content": {
258
+ "application/json": {
259
+ "schema": {
260
+ "type": "object",
261
+ "properties": {
262
+ "gid": {
263
+ "type": "string",
264
+ "description": "The GADM ID to query (e.g., 'UGA.2.5_1')"
265
+ }
266
+ },
267
+ "required": [
268
+ "gid"
269
+ ]
270
+ }
271
+ }
272
+ }
273
+ },
274
+ "responses": {
275
+ "200": {
276
+ "description": "Centroid and bounding box of the polygon region",
277
+ "content": {
278
+ "application/json": {
279
+ "schema": {
280
+ "type": "object",
281
+ "properties": {
282
+ "status": {
283
+ "type": "string",
284
+ "description": "Message indicating success or failure"
285
+ },
286
+ "latitude": {
287
+ "type": [
288
+ "number",
289
+ "null"
290
+ ],
291
+ "description": "Latitude of the centroid"
292
+ },
293
+ "longitude": {
294
+ "type": [
295
+ "number",
296
+ "null"
297
+ ],
298
+ "description": "Longitude of the centroid"
299
+ },
300
+ "bbox_bounds": {
301
+ "type": [
302
+ "array",
303
+ "null"
304
+ ],
305
+ "items": {
306
+ "type": "number"
307
+ },
308
+ "minItems": 4,
309
+ "maxItems": 4,
310
+ "description": "[lat_min, lat_max, lon_min, lon_max]"
311
+ },
312
+ "polygon_area": {
313
+ "type": [
314
+ "number",
315
+ "null"
316
+ ],
317
+ "description": "Area of the polygon in degrees²"
318
+ },
319
+ "bbox_area": {
320
+ "type": [
321
+ "number",
322
+ "null"
323
+ ],
324
+ "description": "Area of the bounding box in degrees²"
325
+ }
326
+ },
327
+ "required": [
328
+ "status"
329
+ ]
330
+ }
331
+ }
332
+ }
333
+ }
334
+ }
335
+ }
336
+ },
337
+ "/gadm/get_tree_info": {
338
+ "post": {
339
+ "summary": "Get hierarchical tree metadata for a GADM region",
340
+ "description": "Returns the level of the GADM ID and its relationship to other regions: parent (if any), children, and siblings. This is useful for navigating the administrative hierarchy or exploring neighbouring regions.",
341
+ "operationId": "gadm_get_tree_info",
342
+ "requestBody": {
343
+ "required": true,
344
+ "content": {
345
+ "application/json": {
346
+ "schema": {
347
+ "type": "object",
348
+ "properties": {
349
+ "gid": {
350
+ "type": "string",
351
+ "description": "The GADM ID to query (e.g., 'ETH.2.9_1')"
352
+ }
353
+ },
354
+ "required": [
355
+ "gid"
356
+ ]
357
+ }
358
+ }
359
+ }
360
+ },
361
+ "responses": {
362
+ "200": {
363
+ "description": "Level, parent, children, and siblings",
364
+ "content": {
365
+ "application/json": {
366
+ "schema": {
367
+ "type": "object",
368
+ "properties": {
369
+ "status": {
370
+ "type": "string",
371
+ "description": "Status message indicating success or failure"
372
+ },
373
+ "level": {
374
+ "type": [
375
+ "integer",
376
+ "null"
377
+ ],
378
+ "description": "Administrative level (0 = country, 1 = province, ..., 5 = smallest)"
379
+ },
380
+ "parent": {
381
+ "type": [
382
+ "string",
383
+ "null"
384
+ ],
385
+ "description": "Parent GADM ID, or null if this is level 0"
386
+ },
387
+ "children": {
388
+ "type": [
389
+ "array",
390
+ "null"
391
+ ],
392
+ "items": {
393
+ "type": "string"
394
+ },
395
+ "description": "List of child GIDs"
396
+ },
397
+ "siblings": {
398
+ "type": [
399
+ "array",
400
+ "null"
401
+ ],
402
+ "items": {
403
+ "type": "string"
404
+ },
405
+ "description": "List of sibling GIDs, including self"
406
+ }
407
+ },
408
+ "required": [
409
+ "status"
410
+ ]
411
+ }
412
+ }
413
+ }
414
+ }
415
+ }
416
+ }
417
+ },
418
+ "/gadm/get_quick_summary": {
419
+ "post": {
420
+ "summary": "Return a human-readable summary of a GADM region",
421
+ "description": "Returns a concise, readable string describing the GADM region: full name, level, latitude, longitude, and GID. Useful for debugging or confirming spatial resolution results before data retrieval.",
422
+ "operationId": "gadm_get_quick_summary",
423
+ "requestBody": {
424
+ "required": true,
425
+ "content": {
426
+ "application/json": {
427
+ "schema": {
428
+ "type": "object",
429
+ "properties": {
430
+ "gid": {
431
+ "type": "string",
432
+ "description": "GADM ID to summarise (e.g., 'ETH.1.3_1')"
433
+ }
434
+ },
435
+ "required": [
436
+ "gid"
437
+ ]
438
+ }
439
+ }
440
+ }
441
+ },
442
+ "responses": {
443
+ "200": {
444
+ "description": "Single-line summary of the region",
445
+ "content": {
446
+ "application/json": {
447
+ "schema": {
448
+ "type": "object",
449
+ "properties": {
450
+ "summary": {
451
+ "type": "string",
452
+ "description": "Human-readable summary or error message"
453
+ },
454
+ "status": {
455
+ "type": "string",
456
+ "description": "Indicates success or failure of the summary request"
457
+ }
458
+ },
459
+ "required": [
460
+ "summary",
461
+ "status"
462
+ ]
463
+ }
464
+ }
465
+ }
466
+ }
467
+ }
468
+ }
469
+ },
470
+ "/soil/get_point": {
471
+ "post": {
472
+ "summary": "Retrieve soil data near a location",
473
+ "description": "Returns soil property values from the best matching sample among the top-k nearest points. The full list of valid property names is available in `column_names.json`. Any unknown property causes immediate failure.",
474
+ "operationId": "soil_get_point",
475
+ "requestBody": {
476
+ "required": true,
477
+ "content": {
478
+ "application/json": {
479
+ "schema": {
480
+ "type": "object",
481
+ "properties": {
482
+ "place": {
483
+ "description": "GADM ID string, place name string, or [lat, lon] coordinate pair.",
484
+ "oneOf": [
485
+ {
486
+ "type": "string"
487
+ },
488
+ {
489
+ "type": "array",
490
+ "items": {
491
+ "type": "number"
492
+ },
493
+ "minItems": 2,
494
+ "maxItems": 2
495
+ }
496
+ ]
497
+ },
498
+ "properties": {
499
+ "type": "array",
500
+ "description": "List of requested soil properties. Valid names must match entries in `column_names.json`.",
501
+ "items": {
502
+ "type": "string"
503
+ }
504
+ },
505
+ "distance_top_k": {
506
+ "type": "integer",
507
+ "description": "Number of nearest samples to consider.",
508
+ "minimum": 1,
509
+ "default": 20
510
+ },
511
+ "distance_limit": {
512
+ "type": "number",
513
+ "description": "Maximum allowed distance in meters.",
514
+ "minimum": 0,
515
+ "default": 200000
516
+ },
517
+ "session_name": {
518
+ "type": "string",
519
+ "nullable": true,
520
+ "description": "Optional session identifier for logging or traceability."
521
+ }
522
+ },
523
+ "required": [
524
+ "place",
525
+ "properties"
526
+ ]
527
+ }
528
+ }
529
+ }
530
+ },
531
+ "responses": {
532
+ "200": {
533
+ "description": "Structured soil data response",
534
+ "content": {
535
+ "application/json": {
536
+ "schema": {
537
+ "type": "object",
538
+ "properties": {
539
+ "query_input": {
540
+ "type": "object",
541
+ "description": "Echo of user input"
542
+ },
543
+ "query_status": {
544
+ "type": "string",
545
+ "description": "Human-readable status message"
546
+ },
547
+ "query_output": {
548
+ "type": "object",
549
+ "nullable": true,
550
+ "description": "Present only on success or partial success",
551
+ "example": {
552
+ "LAT_LONG": [
553
+ 52.13,
554
+ 5.37
555
+ ],
556
+ "GADM_IDS": [
557
+ "NLD.5.2_1"
558
+ ],
559
+ "carbon": {
560
+ "soil_organic_carbon": 12.4
561
+ },
562
+ "entry_key": "NL123456"
563
+ }
564
+ }
565
+ },
566
+ "required": [
567
+ "query_input",
568
+ "query_status",
569
+ "query_output"
570
+ ]
571
+ }
572
+ }
573
+ }
574
+ }
575
+ }
576
+ }
577
+ },
578
+ "/soil/get_map": {
579
+ "post": {
580
+ "summary": "Generate scatter-plot maps for soil properties across a region",
581
+ "description": "Extracts all samples within the target region and generates one PNG map per property. The response contains `query_input`, `query_status`, and a flat `query_output` mapping property names to either a plot URL or a warning message. For valid property names see `column_names.json`.",
582
+ "operationId": "soil_get_map",
583
+ "requestBody": {
584
+ "required": true,
585
+ "content": {
586
+ "application/json": {
587
+ "schema": {
588
+ "type": "object",
589
+ "properties": {
590
+ "place": {
591
+ "description": "GADM ID, place name string, or [lat, lon, bbox_area] triple",
592
+ "oneOf": [
593
+ {
594
+ "type": "string"
595
+ },
596
+ {
597
+ "type": "array",
598
+ "items": {
599
+ "type": "number"
600
+ },
601
+ "minItems": 3,
602
+ "maxItems": 3
603
+ }
604
+ ]
605
+ },
606
+ "properties": {
607
+ "type": "array",
608
+ "description": "List of requested soil properties. Each entry must match a full_name in `column_names.json` (e.g., \"carbon:total (g/kg)\"). Maximum 5 properties per request.",
609
+ "items": {
610
+ "type": "string"
611
+ },
612
+ "maxItems": 5
613
+ },
614
+ "session_name": {
615
+ "type": "string",
616
+ "description": "Required session identifier. Used to namespace generated plot files (ASCII only)."
617
+ },
618
+ "kwargs": {
619
+ "type": "object",
620
+ "description": "Optional additional keyword arguments forwarded to the plotting function.",
621
+ "additionalProperties": true
622
+ }
623
+ },
624
+ "required": [
625
+ "place",
626
+ "properties",
627
+ "session_name"
628
+ ]
629
+ }
630
+ }
631
+ }
632
+ },
633
+ "responses": {
634
+ "200": {
635
+ "description": "Map generation result containing URLs or warning strings per property",
636
+ "content": {
637
+ "application/json": {
638
+ "schema": {
639
+ "type": "object",
640
+ "properties": {
641
+ "query_input": {
642
+ "type": "object",
643
+ "description": "Echo of the input parameters"
644
+ },
645
+ "query_status": {
646
+ "type": "string",
647
+ "description": "Success, failure, or partial success message"
648
+ },
649
+ "query_output": {
650
+ "type": "object",
651
+ "description": "Flat mapping: full property name → URL (.png) or warning string",
652
+ "additionalProperties": {
653
+ "type": "string"
654
+ }
655
+ }
656
+ },
657
+ "required": [
658
+ "query_input",
659
+ "query_status",
660
+ "query_output"
661
+ ]
662
+ }
663
+ }
664
+ }
665
+ }
666
+ }
667
+ }
668
+ },
669
+ "/health": {
670
+ "get": {
671
+ "summary": "Health check",
672
+ "description": "Returns status OK if the ERP-GPT-Europe backend is running.",
673
+ "operationId": "health_check",
674
+ "responses": {
675
+ "200": {
676
+ "description": "Health check successful",
677
+ "content": {
678
+ "application/json": {
679
+ "schema": {
680
+ "type": "object",
681
+ "properties": {
682
+ "status": {
683
+ "type": "string",
684
+ "example": "OK"
685
+ }
686
+ },
687
+ "required": [
688
+ "status"
689
+ ]
690
+ }
691
+ }
692
+ }
693
+ }
694
+ }
695
+ }
696
+ }
697
+ }
698
+ }
gpt_resources/starts.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ What soil data can you access, and where does it come from?
2
+
3
+ What is soil texture? Explain with an example in the UK.
4
+
5
+ Show SOC distribution in France.
6
+
7
+ Which European regions produce good wine, and how do soil and climate explain it?
8
+
9
+ Show me photos from a LUCAS sample. Anywhere.
plot_utils.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ from typing import List, Tuple, Literal
4
+
5
+ import cartopy.crs as ccrs
6
+ import cartopy.feature as cfeature
7
+ import geopandas as gpd
8
+ import matplotlib
9
+
10
+ matplotlib.use("Agg") # Use non-GUI backend for image generation
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ from matplotlib.colors import ListedColormap
14
+
15
+ from gadm_utils import GADMHandler
16
+
17
+
18
+ def get_boundingbox(lats: np.ndarray, lons: np.ndarray) -> tuple[float, float, float, float]:
19
+ """
20
+ Compute the bounding box of a set of latitudes and longitudes,
21
+ returning in Nominatim convention: (lat_min, lat_max, lon_min, lon_max).
22
+ Handles wraparound at the 0/360 meridian for longitudes.
23
+ """
24
+ lat_min, lat_max = lats.min(), lats.max()
25
+
26
+ lons_360 = np.mod(lons, 360)
27
+ span_regular = lons.max() - lons.min()
28
+ span_wrapped = lons_360.max() - lons_360.min()
29
+ lons_used = lons_360 if span_wrapped < span_regular else lons
30
+ lon_min, lon_max = lons_used.min(), lons_used.max()
31
+
32
+ return lat_min, lat_max, lon_min, lon_max
33
+
34
+
35
+ def scatter_plot(gadm_handler: GADMHandler,
36
+ data: np.ndarray = None, is_categorical: bool = None,
37
+ short_name: str = "plot", long_name: str = "", save_dir: str = "plots",
38
+ session_name: str = None, cmap_float: str = "turbo", cmap_str: str = "tab20",
39
+ scatter_size: float | Literal["auto"] = "auto",
40
+ map_boundary_gadm_gids: List[str] = None,
41
+ map_limits: Tuple[float, float, float, float] | Literal["data", "gadm_all", "gadm_first"] = "data",
42
+ map_margin_ratio: float = 0.2,
43
+ map_borders: bool = False, map_coastline: bool = False) -> str:
44
+ """
45
+ Generate a scatter plot with optional GADM boundaries and save to file.
46
+ """
47
+ # Validate and prepare data
48
+ if data is not None:
49
+ if data.ndim != 2 or data.shape[1] != 3:
50
+ raise ValueError("`data` must be an Nx3 array: [lat, lon, value].")
51
+ lats, lons, values = data[:, 0], data[:, 1], data[:, 2]
52
+ else:
53
+ lats = lons = values = np.array([])
54
+
55
+ has_data = data is not None and len(data) > 0
56
+
57
+ # Fail early if nothing to plot
58
+ if not has_data and not map_boundary_gadm_gids:
59
+ raise ValueError("Nothing to plot: both `data` and `map_boundary_gadm_gids` are empty.")
60
+
61
+ # Determine map limits
62
+ if map_limits == "data":
63
+ if not has_data:
64
+ raise ValueError("`map_limits='data'` requires `data` to be provided.")
65
+ lat0, lat1, lon0, lon1 = get_boundingbox(lats, lons)
66
+
67
+ elif "gadm" in map_limits:
68
+ if not map_boundary_gadm_gids:
69
+ raise ValueError("`map_boundary_gadm_gids` is required for GADM-based limits.")
70
+ all_lats, all_lons = [], []
71
+ index_for_limits = 1 if map_limits == "gadm_first" else len(map_boundary_gadm_gids)
72
+ for gid in map_boundary_gadm_gids[:index_for_limits]:
73
+ polygon = gadm_handler.get_polygon(gid)
74
+ if polygon is not None:
75
+ min_x, min_y, max_x, max_y = polygon.bounds
76
+ all_lons.extend([min_x, max_x])
77
+ all_lats.extend([min_y, max_y])
78
+ lat0, lat1, lon0, lon1 = get_boundingbox(np.array(all_lats), np.array(all_lons))
79
+
80
+ else:
81
+ lat0, lat1, lon0, lon1 = map_limits
82
+
83
+ # If data exists, expand map extent so scatter points are always visible
84
+ if has_data:
85
+ data_lat0 = float(np.min(lats))
86
+ data_lat1 = float(np.max(lats))
87
+ data_lon0 = float(np.min(lons))
88
+ data_lon1 = float(np.max(lons))
89
+
90
+ lat0 = min(lat0, data_lat0)
91
+ lat1 = max(lat1, data_lat1)
92
+ lon0 = min(lon0, data_lon0)
93
+ lon1 = max(lon1, data_lon1)
94
+
95
+ # Add margins
96
+ if isinstance(map_limits, str):
97
+ dlat = (lat1 - lat0) * map_margin_ratio or 1.0
98
+ dlon = (lon1 - lon0) * map_margin_ratio or 1.0
99
+ lat0, lat1 = lat0 - dlat, lat1 + dlat
100
+ lon0, lon1 = lon0 - dlon, lon1 + dlon
101
+
102
+ # Setup figure
103
+ base = 6
104
+ width = lon1 - lon0
105
+ height = lat1 - lat0
106
+ plt.figure(figsize=(base * (width / height), base), dpi=200)
107
+ ax = plt.axes(projection=ccrs.PlateCarree())
108
+ ax.set_extent([lon0, lon1, lat0, lat1], crs=ccrs.PlateCarree())
109
+ ax.set_aspect("equal", adjustable="box")
110
+
111
+ tick_font = 8 if has_data else 10
112
+ title_font = 10 if has_data else 12
113
+
114
+ # Gridlines
115
+ gl = ax.gridlines(draw_labels=True, linewidth=0.3, color='gray', alpha=0.7, linestyle='--')
116
+ gl.top_labels = False
117
+ gl.right_labels = False
118
+ gl.xlabel_style = {'size': tick_font}
119
+ gl.ylabel_style = {'size': tick_font}
120
+
121
+ # Base map
122
+ if map_coastline:
123
+ ax.add_feature(cfeature.COASTLINE, linewidth=1.0, color="k")
124
+ if map_borders:
125
+ ax.add_feature(cfeature.BORDERS, linewidth=0.8, color="k")
126
+ ax.add_feature(cfeature.LAND, facecolor="ivory")
127
+ ax.add_feature(cfeature.OCEAN, facecolor="lightblue")
128
+
129
+ # GADM boundaries
130
+ if map_boundary_gadm_gids:
131
+ for gid in map_boundary_gadm_gids:
132
+ polygon = gadm_handler.get_polygon(gid)
133
+ if polygon is not None:
134
+ gpd.GeoSeries([polygon]).plot(ax=ax, facecolor='none', edgecolor='gray', linewidth=0.3)
135
+ if map_limits == "gadm_first":
136
+ gid = map_boundary_gadm_gids[0]
137
+ polygon = gadm_handler.get_polygon(gid)
138
+ if polygon is not None:
139
+ gpd.GeoSeries([polygon]).plot(ax=ax, facecolor='none', edgecolor='black', linewidth=0.6)
140
+ info = gadm_handler.get_full_info(gid)
141
+ if info:
142
+ lat_c = info["geometry"]["latitude"]
143
+ lon_c = info["geometry"]["longitude"]
144
+ name = info["full_name"].split(";")[0]
145
+ plt.text(lon_c, lat_c, name, fontsize=tick_font, ha="center", va="center")
146
+
147
+ # Scatter plot
148
+ if has_data:
149
+ if scatter_size == "auto":
150
+ count = len(lats)
151
+ base_size = 40
152
+ scatter_size = base_size / (np.log10(count + 1) + 1)
153
+ scatter_size = np.clip(scatter_size, 5, 30)
154
+
155
+ if is_categorical is None:
156
+ is_categorical = np.issubdtype(values.dtype, np.str_)
157
+
158
+ rasterize = len(lats) > 10000
159
+ if is_categorical:
160
+ categories, values_encoded = np.unique(values.astype(str), return_inverse=True)
161
+ num_categories = len(categories)
162
+ cmap_base = plt.get_cmap(cmap_str)
163
+ if hasattr(cmap_base, 'colors'):
164
+ cmap_colors = cmap_base.colors[:num_categories]
165
+ cmap_used = ListedColormap(cmap_colors)
166
+ else:
167
+ cmap_used = cmap_base
168
+
169
+ sc = ax.scatter(lons, lats, c=values_encoded, cmap=cmap_used, s=scatter_size,
170
+ linewidth=0.0, transform=ccrs.PlateCarree(), zorder=2,
171
+ rasterized=rasterize, edgecolors='none')
172
+ single_color_width = (num_categories - 1) / num_categories
173
+ cbar = plt.colorbar(sc, ax=ax, orientation='vertical', shrink=0.6,
174
+ ticks=np.linspace(single_color_width / 2,
175
+ num_categories - 1 - single_color_width / 2,
176
+ num_categories))
177
+ cbar.ax.set_yticklabels(categories)
178
+ cbar.set_label(long_name, fontsize=tick_font)
179
+ cbar.ax.tick_params(labelsize=tick_font)
180
+ else:
181
+ try:
182
+ vmin = float(np.percentile(values, 1))
183
+ vmax = float(np.percentile(values, 99))
184
+ except Exception: # noqa
185
+ vmin = vmax = None
186
+
187
+ norm = plt.Normalize(vmin=vmin, vmax=vmax) if vmin is not None and vmax is not None else None
188
+
189
+ sc = ax.scatter(lons, lats, c=values, cmap=cmap_float, s=scatter_size,
190
+ linewidth=0.0, transform=ccrs.PlateCarree(), zorder=2, norm=norm,
191
+ rasterized=rasterize, edgecolors='none')
192
+
193
+ cbar = plt.colorbar(sc, ax=ax, orientation='vertical', shrink=0.6)
194
+ cbar.set_label(long_name, fontsize=tick_font)
195
+ cbar.ax.tick_params(labelsize=tick_font)
196
+
197
+ ax.set_title(long_name, fontsize=title_font)
198
+
199
+ # Save figure with safe filename
200
+ if session_name is None or session_name == "":
201
+ session_name = "default_session"
202
+ safe_session = re.sub(r'[^a-zA-Z0-9_-]', '_', session_name)
203
+ save_dir = os.path.join(save_dir, safe_session)
204
+ os.makedirs(save_dir, exist_ok=True)
205
+
206
+ # build base filename
207
+ base_name = re.sub(r'[^a-zA-Z0-9_-]', '_', short_name)
208
+ ext = ".png"
209
+ filepath = os.path.join(save_dir, f"{base_name}{ext}")
210
+
211
+ # if exists, append -1, -2, ...
212
+ if os.path.exists(filepath):
213
+ i = 1
214
+ while True:
215
+ filepath = os.path.join(save_dir, f"{base_name}-{i}{ext}")
216
+ if not os.path.exists(filepath):
217
+ break
218
+ i += 1
219
+
220
+ plt.savefig(filepath, bbox_inches="tight")
221
+ plt.close()
222
+
223
+ return filepath
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Cartopy
2
+ geopandas
3
+ geopy
4
+ matplotlib
5
+ shapely
6
+
7
+ flask
8
+ numpy
9
+ pandas
10
+
11
+ pycountry