zemin 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
zemin-0.1.0/LICENSE ADDED
@@ -0,0 +1,110 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner.
53
+
54
+ "Contributor" shall mean Licensor and any individual or Legal Entity
55
+ on behalf of whom a Contribution has been received by Licensor and
56
+ subsequently incorporated within the Work.
57
+
58
+ 2. Grant of Copyright License. Subject to the terms and conditions of
59
+ this License, each Contributor hereby grants to You a perpetual,
60
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
61
+ copyright license to reproduce, prepare Derivative Works of,
62
+ publicly display, publicly perform, sublicense, and distribute the
63
+ Work and such Derivative Works in Source or Object form.
64
+
65
+ 3. Grant of Patent License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ (except as stated in this section) patent license to make, have made,
69
+ use, offer to sell, sell, import, and otherwise transfer the Work,
70
+ where such license applies only to those patent claims licensable
71
+ by such Contributor that are necessarily infringed by their
72
+ Contribution(s) alone or by combination of their Contribution(s)
73
+ with the Work to which such Contribution(s) was submitted.
74
+
75
+ 4. Redistribution. You may reproduce and distribute copies of the
76
+ Work or Derivative Works thereof in any medium, with or without
77
+ modifications, and in Source or Object form, provided that You
78
+ meet the following conditions:
79
+ (a) You must give any other recipients of the Work or Derivative
80
+ Works a copy of this License; and
81
+ (b) You must cause any modified files to carry prominent notices
82
+ stating that You changed the files; and
83
+ (c) You must retain all copyright, patent, trademark, and
84
+ attribution notices from the Source form of the Work.
85
+
86
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
87
+ any Contribution intentionally submitted for inclusion in the Work
88
+ by You to the Licensor shall be under the terms and conditions of
89
+ this License, without any additional terms or conditions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
97
+ implied.
98
+
99
+ 8. Limitation of Liability. In no event and under no legal theory
100
+ shall any Contributor be liable to You for damages arising as a
101
+ result of this License or out of the use or inability to use the Work.
102
+
103
+ 9. Accepting Warranty or Additional Liability. While redistributing
104
+ the Work or Derivative Works thereof, You may choose to offer
105
+ acceptance of support, warranty, indemnity, or other liability
106
+ obligations consistent with this License on Your own behalf only.
107
+
108
+ END OF TERMS AND CONDITIONS
109
+
110
+ Copyright 2026 Aslan Satary Dizaji
zemin-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: zemin
3
+ Version: 0.1.0
4
+ Summary: Offline-first urban land subsidence, aquifer resilience, and infrastructure risk auditor for Sentinel-1 InSAR, piezometer, and GIS data.
5
+ Author-email: Aslan Satary Dizaji <aslansatary@gmail.com>
6
+ License: Apache-2.0
7
+ Keywords: insar,subsidence,geotechnics,aquifer,critical-slowing-down,urban-risk,sentinel-1,tehran
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: web
12
+ Requires-Dist: fastapi>=0.115; extra == "web"
13
+ Requires-Dist: uvicorn>=0.30; extra == "web"
14
+ Requires-Dist: python-multipart>=0.0.9; extra == "web"
15
+ Provides-Extra: streamlit
16
+ Requires-Dist: streamlit>=1.38; extra == "streamlit"
17
+ Provides-Extra: all
18
+ Requires-Dist: fastapi>=0.115; extra == "all"
19
+ Requires-Dist: uvicorn>=0.30; extra == "all"
20
+ Requires-Dist: python-multipart>=0.0.9; extra == "all"
21
+ Requires-Dist: streamlit>=1.38; extra == "all"
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=8.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.6; extra == "dev"
25
+ Requires-Dist: httpx>=0.27; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # zemin
29
+
30
+ **زمین** — *earth, ground, geotechnical subsoil.* The same word in Persian
31
+ (*zamīn*), Azerbaijani (*zəmin*), and Turkish (*zemin*, as in *zemin etüdü* —
32
+ geotechnical ground survey).
33
+
34
+ Audit urban land subsidence, seasonal aquifer rebound failure, dynamical
35
+ resilience (Ornstein-Uhlenbeck critical slowing down), and structural
36
+ differential settlement from open Sentinel-1 InSAR, piezometer, and GeoJSON
37
+ corridor data—entirely offline.
38
+
39
+ Southwest Tehran (Districts 17–19, Shahriar, Varamin) and Karaj experience
40
+ severe groundwater-driven subsidence that silently stresses water mains, gas
41
+ trunks, metro tunnel linings, and building foundations. Engineering consultancies
42
+ and utilities often rely on static, years-old borehole reports while InSAR
43
+ pipelines fail silently on phase-unwrapping jumps or low coherence. `zemin`
44
+ turns raw InSAR and groundwater exports into versioned, reproducible
45
+ geotechnical risk dossiers.
46
+
47
+ **Zero runtime dependencies for the core engine (no GDAL, no Shapely, no cloud APIs). Runs 100% offline.**
48
+
49
+ ```bash
50
+ pip install zemin
51
+ ```
52
+
53
+ Python 3.10+. Apache 2.0.
54
+
55
+ [INSTALL](INSTALL.md) · [TESTING](TESTING.md) · [TROUBLESHOOTING](TROUBLESHOOTING.md) ·
56
+ [PUBLISHING](PUBLISHING.md) · [ROADMAP](ROADMAP.md) · [CHANGELOG](CHANGELOG.md)
57
+
58
+ ---
59
+
60
+ ## The thirty-second version
61
+
62
+ ```bash
63
+ # 1. Generate a 3-year synthetic SW Tehran District 18 corridor + GeoJSON and audit it
64
+ zemin demo --out-csv tehran_d18_insar.csv --out-geojson tehran_d18_corridor.geojson
65
+
66
+ # 2. Audit any MintPy, LiCSAR, or TAMAB piezometer CSV inside a project polygon + Persian dossier via Ollama
67
+ zemin audit examples/tehran_d18_insar.csv \
68
+ --polygon examples/tehran_d18_corridor.geojson \
69
+ --json-out d18_audit.json \
70
+ --dossier fa --model gemma3:12b
71
+
72
+ # 3. Compare two survey periods longitudinally
73
+ zemin diff examples/tehran_d18_insar.csv examples/tehran_control_stable.csv \
74
+ --polygon examples/tehran_d18_corridor.geojson
75
+ ```
76
+
77
+ ---
78
+
79
+ ## Seven dynamical & geotechnical hazards detected
80
+
81
+ | Code | What it measures |
82
+ |---|---|
83
+ | `SUBSIDENCE_VELOCITY_HAZARD` | Vertical subsidence velocity (mm/yr), auto-projecting Sentinel-1 LOS via `d_v = d_LOS / cos(theta)` |
84
+ | `SUBSIDENCE_ACCELERATION` | Seasonally adjusted quadratic downward curvature (mm/yr^2) with t-statistic significance gating |
85
+ | `AQUIFER_REBOUND_FAILURE` | Collapse of wet-season elastic uplift & seasonal harmonic decay (irreversible clay compaction) |
86
+ | `CRITICAL_SLOWING_DOWN` | Rolling Ornstein-Uhlenbeck AR(1) recovery-rate decline (Marriott-Pope bias corrected) + rising variance |
87
+ | `DIFFERENTIAL_SETTLEMENT_TILT` | Pairwise Haversine angular distortion `|dS| / L` against Eurocode-7 limits (`1/500` cracking, `1/250` distress) |
88
+ | `GROUNDWATER_COMPACTION_COUPLING` | Piezometer head drop (m/yr) and GRACE TWS loss (cm/yr) coupled to skeletal compaction ratio (mm/m) |
89
+ | `INSAR_DATA_INTEGRITY` | Pre-sign-off quality audit for low temporal coherence and Sentinel-1 C-band phase-unwrapping jumps (~28 mm) |
90
+
91
+ ---
92
+
93
+ ## Built-in zero-dependency adapters
94
+
95
+ | Adapter | Data Source | Handles |
96
+ |---|---|---|
97
+ | `mintpy` | MintPy / ASF HyP3 / ARIA PS-InSAR | Both wide (`D20240101...`) and long formats, meters-to-mm scaling, LOS-to-vertical projection |
98
+ | `licsar` | COMET-LiCSAR / LiCSBAS | Frame cumulative displacement exports and average coherence |
99
+ | `piezometer` | Iran TAMAB / ABFA wells & GRACE/ERA5 | Depth-to-water, extensometer settlement, Persian/Arabic digits (`۰۱۲۳۴۵۶۷۸۹`) |
100
+ | `generic` | Standard `.csv` and `.jsonl` | Clean multi-site geospatial time series |
101
+
102
+ GeoJSON `Polygon` and `MultiPolygon` spatial filtering is built into
103
+ `zemin.geo` using pure-Python ray-casting and Haversine geometry—zero native
104
+ GDAL/GEOS compilation issues.
105
+
106
+ ---
107
+
108
+ ## Offline RTL Persian dashboards
109
+
110
+ ```bash
111
+ # FastAPI + built-in RTL Persian dashboard (http://127.0.0.1:8000)
112
+ pip install "zemin[web]"
113
+ zemin serve --port 8000
114
+
115
+ # Or RTL Persian Streamlit dashboard
116
+ pip install "zemin[streamlit]"
117
+ streamlit run src/zemin/streamlit_app.py
118
+ ```
119
+
120
+ ## Licence
121
+
122
+ Apache 2.0.
zemin-0.1.0/README.md ADDED
@@ -0,0 +1,95 @@
1
+ # zemin
2
+
3
+ **زمین** — *earth, ground, geotechnical subsoil.* The same word in Persian
4
+ (*zamīn*), Azerbaijani (*zəmin*), and Turkish (*zemin*, as in *zemin etüdü* —
5
+ geotechnical ground survey).
6
+
7
+ Audit urban land subsidence, seasonal aquifer rebound failure, dynamical
8
+ resilience (Ornstein-Uhlenbeck critical slowing down), and structural
9
+ differential settlement from open Sentinel-1 InSAR, piezometer, and GeoJSON
10
+ corridor data—entirely offline.
11
+
12
+ Southwest Tehran (Districts 17–19, Shahriar, Varamin) and Karaj experience
13
+ severe groundwater-driven subsidence that silently stresses water mains, gas
14
+ trunks, metro tunnel linings, and building foundations. Engineering consultancies
15
+ and utilities often rely on static, years-old borehole reports while InSAR
16
+ pipelines fail silently on phase-unwrapping jumps or low coherence. `zemin`
17
+ turns raw InSAR and groundwater exports into versioned, reproducible
18
+ geotechnical risk dossiers.
19
+
20
+ **Zero runtime dependencies for the core engine (no GDAL, no Shapely, no cloud APIs). Runs 100% offline.**
21
+
22
+ ```bash
23
+ pip install zemin
24
+ ```
25
+
26
+ Python 3.10+. Apache 2.0.
27
+
28
+ [INSTALL](INSTALL.md) · [TESTING](TESTING.md) · [TROUBLESHOOTING](TROUBLESHOOTING.md) ·
29
+ [PUBLISHING](PUBLISHING.md) · [ROADMAP](ROADMAP.md) · [CHANGELOG](CHANGELOG.md)
30
+
31
+ ---
32
+
33
+ ## The thirty-second version
34
+
35
+ ```bash
36
+ # 1. Generate a 3-year synthetic SW Tehran District 18 corridor + GeoJSON and audit it
37
+ zemin demo --out-csv tehran_d18_insar.csv --out-geojson tehran_d18_corridor.geojson
38
+
39
+ # 2. Audit any MintPy, LiCSAR, or TAMAB piezometer CSV inside a project polygon + Persian dossier via Ollama
40
+ zemin audit examples/tehran_d18_insar.csv \
41
+ --polygon examples/tehran_d18_corridor.geojson \
42
+ --json-out d18_audit.json \
43
+ --dossier fa --model gemma3:12b
44
+
45
+ # 3. Compare two survey periods longitudinally
46
+ zemin diff examples/tehran_d18_insar.csv examples/tehran_control_stable.csv \
47
+ --polygon examples/tehran_d18_corridor.geojson
48
+ ```
49
+
50
+ ---
51
+
52
+ ## Seven dynamical & geotechnical hazards detected
53
+
54
+ | Code | What it measures |
55
+ |---|---|
56
+ | `SUBSIDENCE_VELOCITY_HAZARD` | Vertical subsidence velocity (mm/yr), auto-projecting Sentinel-1 LOS via `d_v = d_LOS / cos(theta)` |
57
+ | `SUBSIDENCE_ACCELERATION` | Seasonally adjusted quadratic downward curvature (mm/yr^2) with t-statistic significance gating |
58
+ | `AQUIFER_REBOUND_FAILURE` | Collapse of wet-season elastic uplift & seasonal harmonic decay (irreversible clay compaction) |
59
+ | `CRITICAL_SLOWING_DOWN` | Rolling Ornstein-Uhlenbeck AR(1) recovery-rate decline (Marriott-Pope bias corrected) + rising variance |
60
+ | `DIFFERENTIAL_SETTLEMENT_TILT` | Pairwise Haversine angular distortion `|dS| / L` against Eurocode-7 limits (`1/500` cracking, `1/250` distress) |
61
+ | `GROUNDWATER_COMPACTION_COUPLING` | Piezometer head drop (m/yr) and GRACE TWS loss (cm/yr) coupled to skeletal compaction ratio (mm/m) |
62
+ | `INSAR_DATA_INTEGRITY` | Pre-sign-off quality audit for low temporal coherence and Sentinel-1 C-band phase-unwrapping jumps (~28 mm) |
63
+
64
+ ---
65
+
66
+ ## Built-in zero-dependency adapters
67
+
68
+ | Adapter | Data Source | Handles |
69
+ |---|---|---|
70
+ | `mintpy` | MintPy / ASF HyP3 / ARIA PS-InSAR | Both wide (`D20240101...`) and long formats, meters-to-mm scaling, LOS-to-vertical projection |
71
+ | `licsar` | COMET-LiCSAR / LiCSBAS | Frame cumulative displacement exports and average coherence |
72
+ | `piezometer` | Iran TAMAB / ABFA wells & GRACE/ERA5 | Depth-to-water, extensometer settlement, Persian/Arabic digits (`۰۱۲۳۴۵۶۷۸۹`) |
73
+ | `generic` | Standard `.csv` and `.jsonl` | Clean multi-site geospatial time series |
74
+
75
+ GeoJSON `Polygon` and `MultiPolygon` spatial filtering is built into
76
+ `zemin.geo` using pure-Python ray-casting and Haversine geometry—zero native
77
+ GDAL/GEOS compilation issues.
78
+
79
+ ---
80
+
81
+ ## Offline RTL Persian dashboards
82
+
83
+ ```bash
84
+ # FastAPI + built-in RTL Persian dashboard (http://127.0.0.1:8000)
85
+ pip install "zemin[web]"
86
+ zemin serve --port 8000
87
+
88
+ # Or RTL Persian Streamlit dashboard
89
+ pip install "zemin[streamlit]"
90
+ streamlit run src/zemin/streamlit_app.py
91
+ ```
92
+
93
+ ## Licence
94
+
95
+ Apache 2.0.
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "zemin"
7
+ version = "0.1.0"
8
+ description = "Offline-first urban land subsidence, aquifer resilience, and infrastructure risk auditor for Sentinel-1 InSAR, piezometer, and GIS data."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "Aslan Satary Dizaji", email = "aslansatary@gmail.com" }]
13
+ keywords = ["insar", "subsidence", "geotechnics", "aquifer", "critical-slowing-down", "urban-risk", "sentinel-1", "tehran"]
14
+ dependencies = []
15
+
16
+ [project.optional-dependencies]
17
+ web = ["fastapi>=0.115", "uvicorn>=0.30", "python-multipart>=0.0.9"]
18
+ streamlit = ["streamlit>=1.38"]
19
+ all = ["fastapi>=0.115", "uvicorn>=0.30", "python-multipart>=0.0.9", "streamlit>=1.38"]
20
+ dev = ["pytest>=8.0", "ruff>=0.6", "httpx>=0.27"]
21
+
22
+ [project.scripts]
23
+ zemin = "zemin.cli:main"
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src"]
zemin-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,39 @@
1
+ from .__version__ import __version__
2
+ from .adapters import ADAPTER_REGISTRY, detect_adapter, load_with_adapter
3
+ from .diff import diff_files, diff_json_reports
4
+ from .engine import audit_file, audit_observations
5
+ from .geo import filter_observations_by_polygon, haversine_m, load_geojson_polygons
6
+ from .llm_dossier import generate_engineering_dossier
7
+ from .schema import (
8
+ AdapterInfo,
9
+ AuditConfig,
10
+ AuditReport,
11
+ EpochDiffResult,
12
+ Finding,
13
+ GeoObservation,
14
+ Severity,
15
+ SiteSummary,
16
+ )
17
+
18
+ __all__ = [
19
+ "__version__",
20
+ "ADAPTER_REGISTRY",
21
+ "AdapterInfo",
22
+ "AuditConfig",
23
+ "AuditReport",
24
+ "EpochDiffResult",
25
+ "Finding",
26
+ "GeoObservation",
27
+ "Severity",
28
+ "SiteSummary",
29
+ "audit_file",
30
+ "audit_observations",
31
+ "detect_adapter",
32
+ "diff_files",
33
+ "diff_json_reports",
34
+ "filter_observations_by_polygon",
35
+ "generate_engineering_dossier",
36
+ "haversine_m",
37
+ "load_geojson_polygons",
38
+ "load_with_adapter",
39
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Callable
5
+
6
+ from ..schema import AdapterInfo, GeoObservation
7
+ from .generic import load_generic_geo
8
+ from .licsar import can_parse as is_licsar
9
+ from .licsar import load_licsar_csv
10
+ from .mintpy import can_parse as is_mintpy
11
+ from .mintpy import load_mintpy_csv
12
+ from .piezometer import can_parse as is_piezometer
13
+ from .piezometer import load_piezometer_csv
14
+
15
+ ADAPTER_REGISTRY: dict[str, Callable[[Path], tuple[list[GeoObservation], AdapterInfo]]] = {
16
+ "mintpy": load_mintpy_csv,
17
+ "licsar": load_licsar_csv,
18
+ "piezometer": load_piezometer_csv,
19
+ "generic": load_generic_geo,
20
+ }
21
+
22
+
23
+ def detect_adapter(path: Path) -> str:
24
+ if path.suffix.lower() in {".jsonl", ".ndjson"}:
25
+ return "generic"
26
+ sample = path.read_text(encoding="utf-8-sig", errors="replace")[:4096]
27
+ if is_mintpy(sample):
28
+ return "mintpy"
29
+ if is_licsar(sample):
30
+ return "licsar"
31
+ if is_piezometer(sample):
32
+ return "piezometer"
33
+ return "generic"
34
+
35
+
36
+ def load_with_adapter(
37
+ path: str | Path,
38
+ adapter: str = "auto",
39
+ ) -> tuple[list[GeoObservation], AdapterInfo]:
40
+ p = Path(path)
41
+ chosen = detect_adapter(p) if adapter == "auto" else adapter.lower()
42
+ if chosen not in ADAPTER_REGISTRY:
43
+ raise ValueError(f"Unknown adapter '{adapter}'. Choose from: auto, {', '.join(ADAPTER_REGISTRY)}")
44
+ return ADAPTER_REGISTRY[chosen](p)
45
+
46
+
47
+ __all__ = ["ADAPTER_REGISTRY", "detect_adapter", "load_with_adapter"]
@@ -0,0 +1,205 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import math
5
+ import re
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from ..schema import AdapterInfo, GeoObservation
11
+
12
+ _PERSIAN_ARABIC_DIGITS = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩٫٬", "01234567890123456789.,")
13
+
14
+ _TIMESTAMP_FORMATS = (
15
+ "%Y-%m-%d",
16
+ "%Y-%m-%d %H:%M:%S",
17
+ "%Y/%m/%d",
18
+ "%Y/%m/%d %H:%M:%S",
19
+ "%Y%m%d",
20
+ "%d.%m.%Y",
21
+ "%d/%m/%Y",
22
+ )
23
+
24
+
25
+ def normalize_digits(text: str) -> str:
26
+ return text.translate(_PERSIAN_ARABIC_DIGITS).strip()
27
+
28
+
29
+ def parse_float(raw: Any, decimal_comma: bool = False) -> float | None:
30
+ if raw is None:
31
+ return None
32
+ text = normalize_digits(str(raw))
33
+ if not text or text.lower() in {"na", "n/a", "nan", "null", "none", "-", "--", "nodata"}:
34
+ return None
35
+ text = re.sub(r"\s*(mm|cm|m|deg|°)$", "", text, flags=re.IGNORECASE).strip()
36
+ if decimal_comma and "," in text and "." not in text:
37
+ text = text.replace(",", ".")
38
+ elif "," in text and "." in text:
39
+ text = text.replace(",", "")
40
+ elif "," in text and re.match(r"^-?\d+,\d{1,3}$", text):
41
+ text = text.replace(",", ".")
42
+ try:
43
+ return float(text)
44
+ except ValueError:
45
+ return None
46
+
47
+
48
+ def parse_timestamp(raw: Any) -> datetime:
49
+ text = normalize_digits(str(raw))
50
+ if not text:
51
+ raise ValueError("Empty timestamp")
52
+ if text.startswith(("D", "d")) and re.fullmatch(r"[Dd]\d{8}", text):
53
+ text = text[1:]
54
+ if re.fullmatch(r"\d{10}(\.\d+)?", text):
55
+ return datetime.fromtimestamp(float(text), tz=timezone.utc).replace(tzinfo=None)
56
+ iso = text[:-1] + "+00:00" if text.endswith("Z") else text
57
+ try:
58
+ dt = datetime.fromisoformat(iso)
59
+ return dt.replace(tzinfo=None) if dt.tzinfo is not None else dt
60
+ except ValueError:
61
+ pass
62
+ for fmt in _TIMESTAMP_FORMATS:
63
+ try:
64
+ return datetime.strptime(text, fmt)
65
+ except ValueError:
66
+ continue
67
+ raise ValueError(f"Unrecognized date/timestamp format: {raw!r}")
68
+
69
+
70
+ def detect_delimiter(header_line: str) -> str:
71
+ for delim in (";", ",", "\t"):
72
+ if delim in header_line and len(header_line.split(delim)) >= 2:
73
+ return delim
74
+ return ","
75
+
76
+
77
+ def infer_displacement_scale_to_mm(col_name: str) -> float:
78
+ low = col_name.lower()
79
+ if any(tok in low for tok in ("_m", "(m)", "[m]", "meters", "metre")) and "mm" not in low and "cm" not in low:
80
+ return 1000.0
81
+ if any(tok in low for tok in ("_cm", "(cm)", "[cm]")) and "mm" not in low:
82
+ return 10.0
83
+ return 1.0
84
+
85
+
86
+ def match_columns(fieldnames: list[str], patterns: dict[str, tuple[str, ...]]) -> dict[str, str]:
87
+ mapping: dict[str, str] = {}
88
+ cleaned = [(c, re.sub(r"\s+", " ", c.strip().lower())) for c in fieldnames if c]
89
+ for canonical, regexes in patterns.items():
90
+ for rx in regexes:
91
+ compiled = re.compile(rx, flags=re.IGNORECASE)
92
+ for orig, low in cleaned:
93
+ if compiled.search(low):
94
+ mapping[canonical] = orig
95
+ break
96
+ if canonical in mapping:
97
+ break
98
+ return mapping
99
+
100
+
101
+ def project_los_to_vertical(los_mm: float, incidence_deg: float) -> float:
102
+ cos_theta = math.cos(math.radians(incidence_deg))
103
+ if abs(cos_theta) < 0.2:
104
+ return los_mm
105
+ return los_mm / cos_theta
106
+
107
+
108
+ def parse_long_csv(
109
+ path: Path,
110
+ adapter_name: str,
111
+ column_patterns: dict[str, tuple[str, ...]],
112
+ header_markers: tuple[str, ...],
113
+ project_los: bool = False,
114
+ default_incidence_deg: float = 38.0,
115
+ max_preamble_lines: int = 25,
116
+ ) -> tuple[list[GeoObservation], AdapterInfo]:
117
+ lines = path.read_text(encoding="utf-8-sig", errors="replace").splitlines()
118
+ header_idx = 0
119
+ delimiter = ","
120
+
121
+ for idx, line in enumerate(lines[:max_preamble_lines]):
122
+ stripped = line.strip()
123
+ if not stripped or stripped.startswith("#"):
124
+ continue
125
+ cand_delim = detect_delimiter(stripped)
126
+ cols = [c.strip().strip('"').lower() for c in stripped.split(cand_delim)]
127
+ if len(cols) >= 2 and any(any(m in c for m in header_markers) for c in cols):
128
+ header_idx = idx
129
+ delimiter = cand_delim
130
+ break
131
+
132
+ data_lines = lines[header_idx:]
133
+ if not data_lines:
134
+ raise ValueError(f"No tabular data found in {path}")
135
+
136
+ reader = csv.DictReader(data_lines, delimiter=delimiter)
137
+ if not reader.fieldnames:
138
+ raise ValueError(f"Empty CSV header in {path}")
139
+
140
+ col_map = match_columns(list(reader.fieldnames), column_patterns)
141
+ if "timestamp" not in col_map or "displacement_mm" not in col_map:
142
+ raise ValueError(
143
+ f"Adapter '{adapter_name}' could not resolve required date/timestamp and displacement columns "
144
+ f"from headers {reader.fieldnames!r} (resolved={col_map})."
145
+ )
146
+
147
+ disp_scale = infer_displacement_scale_to_mm(col_map["displacement_mm"])
148
+ dec_comma = delimiter == ";"
149
+ used_los = project_los or ("los" in col_map["displacement_mm"].lower())
150
+ inc_used: float | None = None
151
+ observations: list[GeoObservation] = []
152
+
153
+ for row in reader:
154
+ if not row:
155
+ continue
156
+ raw_ts = row.get(col_map["timestamp"])
157
+ raw_disp = parse_float(row.get(col_map["displacement_mm"]), decimal_comma=dec_comma)
158
+ if not raw_ts or raw_disp is None:
159
+ continue
160
+ try:
161
+ ts = parse_timestamp(raw_ts)
162
+ except ValueError:
163
+ continue
164
+
165
+ def opt(name: str) -> float | None:
166
+ src = col_map.get(name)
167
+ return parse_float(row.get(src), decimal_comma=dec_comma) if src else None
168
+
169
+ disp_mm = raw_disp * disp_scale
170
+ if used_los:
171
+ inc_val = opt("incidence_deg")
172
+ angle = inc_val if inc_val is not None else default_incidence_deg
173
+ inc_used = angle
174
+ disp_mm = project_los_to_vertical(disp_mm, angle)
175
+
176
+ site_col = col_map.get("site_id")
177
+ site_id = normalize_digits(str(row.get(site_col) or "SITE_01")) if site_col else "SITE_01"
178
+ lat = opt("lat")
179
+ lon = opt("lon")
180
+
181
+ observations.append(
182
+ GeoObservation(
183
+ timestamp=ts,
184
+ site_id=site_id or "SITE_01",
185
+ lat=lat if lat is not None else 35.6500,
186
+ lon=lon if lon is not None else 51.3100,
187
+ displacement_mm=round(disp_mm, 4),
188
+ coherence=opt("coherence"),
189
+ groundwater_depth_m=opt("groundwater_depth_m"),
190
+ tws_cm=opt("tws_cm"),
191
+ soil_moisture=opt("soil_moisture"),
192
+ los_projected=used_los,
193
+ )
194
+ )
195
+
196
+ observations.sort(key=lambda o: (o.site_id, o.timestamp))
197
+ info = AdapterInfo(
198
+ adapter=adapter_name,
199
+ delimiter=delimiter,
200
+ skipped_preamble_lines=header_idx,
201
+ displacement_unit_scale=disp_scale,
202
+ los_incidence_deg=inc_used,
203
+ resolved_columns=col_map,
204
+ )
205
+ return observations, info