otl-map 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.
Files changed (72) hide show
  1. otl_map-0.1.0/LICENSE +78 -0
  2. otl_map-0.1.0/MANIFEST.in +8 -0
  3. otl_map-0.1.0/PKG-INFO +88 -0
  4. otl_map-0.1.0/README.md +60 -0
  5. otl_map-0.1.0/pyproject.toml +44 -0
  6. otl_map-0.1.0/setup.cfg +4 -0
  7. otl_map-0.1.0/setup.py +11 -0
  8. otl_map-0.1.0/src/otl_map/__init__.py +5 -0
  9. otl_map-0.1.0/src/otl_map/_quadtree.pyx +173 -0
  10. otl_map-0.1.0/src/otl_map/_runlog.py +26 -0
  11. otl_map-0.1.0/src/otl_map/bundle.py +168 -0
  12. otl_map-0.1.0/src/otl_map/cell_integration.pxd +44 -0
  13. otl_map-0.1.0/src/otl_map/cell_integration.pyx +288 -0
  14. otl_map-0.1.0/src/otl_map/cli.py +150 -0
  15. otl_map-0.1.0/src/otl_map/coarse_kernel.py +117 -0
  16. otl_map-0.1.0/src/otl_map/coastline.py +132 -0
  17. otl_map-0.1.0/src/otl_map/compute.py +67 -0
  18. otl_map-0.1.0/src/otl_map/compute_otl_fft.pyx +578 -0
  19. otl_map-0.1.0/src/otl_map/compute_otl_slow.pyx +351 -0
  20. otl_map-0.1.0/src/otl_map/data/greenfnc/PREM.dat +502 -0
  21. otl_map-0.1.0/src/otl_map/data/greenfnc/PREM_CM.dat +502 -0
  22. otl_map-0.1.0/src/otl_map/data/greenfnc/PREM_disp.dat +502 -0
  23. otl_map-0.1.0/src/otl_map/data/greenfnc/PREM_disp_CM.dat +502 -0
  24. otl_map-0.1.0/src/otl_map/data/greenfnc/STW105.dat +502 -0
  25. otl_map-0.1.0/src/otl_map/data/greenfnc/STW105_CM.dat +502 -0
  26. otl_map-0.1.0/src/otl_map/data/greenfnc/STW105_disp.dat +502 -0
  27. otl_map-0.1.0/src/otl_map/data/greenfnc/STW105_disp_CM.dat +502 -0
  28. otl_map-0.1.0/src/otl_map/data/greenfnc/greensfunction_approx.json +162 -0
  29. otl_map-0.1.0/src/otl_map/data/tidemodels/SCHW/amp.m2 +0 -0
  30. otl_map-0.1.0/src/otl_map/data/tidemodels/SCHW/pha.m2 +0 -0
  31. otl_map-0.1.0/src/otl_map/docs/otl-map_manual_v0.1.pdf +0 -0
  32. otl_map-0.1.0/src/otl_map/examples/README.txt +16 -0
  33. otl_map-0.1.0/src/otl_map/examples/ex1/brest.txt +1 -0
  34. otl_map-0.1.0/src/otl_map/examples/ex1/example1.py +24 -0
  35. otl_map-0.1.0/src/otl_map/examples/ex2/brest.txt +1 -0
  36. otl_map-0.1.0/src/otl_map/examples/ex2/example2.py +29 -0
  37. otl_map-0.1.0/src/otl_map/examples/ex3/example3.py +20 -0
  38. otl_map-0.1.0/src/otl_map/examples_cmd.py +33 -0
  39. otl_map-0.1.0/src/otl_map/fetch.py +78 -0
  40. otl_map-0.1.0/src/otl_map/fit_pointload.py +154 -0
  41. otl_map-0.1.0/src/otl_map/geometry.pxd +21 -0
  42. otl_map-0.1.0/src/otl_map/geometry.pyx +72 -0
  43. otl_map-0.1.0/src/otl_map/gf_spline.py +72 -0
  44. otl_map-0.1.0/src/otl_map/greensfunction.pxd +42 -0
  45. otl_map-0.1.0/src/otl_map/greensfunction.pyx +301 -0
  46. otl_map-0.1.0/src/otl_map/modify_tidemodel.pyx +224 -0
  47. otl_map-0.1.0/src/otl_map/nearfield.py +270 -0
  48. otl_map-0.1.0/src/otl_map/paths.py +88 -0
  49. otl_map-0.1.0/src/otl_map/prepare.py +86 -0
  50. otl_map-0.1.0/src/otl_map/refine_grid.py +101 -0
  51. otl_map-0.1.0/src/otl_map/resample.py +162 -0
  52. otl_map-0.1.0/src/otl_map/stations.py +194 -0
  53. otl_map-0.1.0/src/otl_map/subcells_io.py +15 -0
  54. otl_map-0.1.0/src/otl_map/tidemodel.pxd +24 -0
  55. otl_map-0.1.0/src/otl_map/tidemodel.pyx +277 -0
  56. otl_map-0.1.0/src/otl_map.egg-info/PKG-INFO +88 -0
  57. otl_map-0.1.0/src/otl_map.egg-info/SOURCES.txt +70 -0
  58. otl_map-0.1.0/src/otl_map.egg-info/dependency_links.txt +1 -0
  59. otl_map-0.1.0/src/otl_map.egg-info/entry_points.txt +3 -0
  60. otl_map-0.1.0/src/otl_map.egg-info/requires.txt +10 -0
  61. otl_map-0.1.0/src/otl_map.egg-info/top_level.txt +1 -0
  62. otl_map-0.1.0/tests/conftest.py +19 -0
  63. otl_map-0.1.0/tests/test_cell_integrals.py +57 -0
  64. otl_map-0.1.0/tests/test_coastline.py +76 -0
  65. otl_map-0.1.0/tests/test_examples.py +57 -0
  66. otl_map-0.1.0/tests/test_fetch.py +38 -0
  67. otl_map-0.1.0/tests/test_fft.py +66 -0
  68. otl_map-0.1.0/tests/test_manual.py +35 -0
  69. otl_map-0.1.0/tests/test_nearfield_wet_sub.py +49 -0
  70. otl_map-0.1.0/tests/test_package.py +28 -0
  71. otl_map-0.1.0/tests/test_prepare.py +43 -0
  72. otl_map-0.1.0/tests/test_resample.py +47 -0
otl_map-0.1.0/LICENSE ADDED
@@ -0,0 +1,78 @@
1
+ OTL-MAP SOFTWARE LICENSE AGREEMENT
2
+ ----------------------------------
3
+
4
+ Version 1.0
5
+
6
+ Copyright (c) 2026
7
+ TeroMovigo – Earth Innovation Lda ("Licensor")
8
+
9
+ 1. DEFINITIONS
10
+
11
+ "Software" means the otl-map software package, including source code,
12
+ documentation, and any associated materials provided by the Licensor.
13
+
14
+ "Non-Commercial Use" means use solely for research, academic, educational,
15
+ or other purposes that are not primarily intended for or directed toward
16
+ commercial advantage or monetary compensation.
17
+
18
+ "Commercial Use" means any use that does not qualify as Non-Commercial Use,
19
+ including use by for-profit entities, use in connection with revenue-generating
20
+ activities, or use in proprietary products or services.
21
+
22
+ 2. GRANT OF LICENSE
23
+
24
+ Subject to the terms of this Agreement, the Licensor hereby grants a
25
+ non-exclusive, non-transferable, royalty-free license to use, reproduce,
26
+ modify, and distribute the Software for Non-Commercial Use.
27
+
28
+ 3. COMMERCIAL USE
29
+
30
+ Commercial Use of the Software is not permitted under this license.
31
+ Any Commercial Use requires a separate written agreement with the Licensor.
32
+
33
+ Commercial entities or individuals intending to use the Software for
34
+ Commercial Use must contact:
35
+
36
+ TeroMovigo – Earth Innovation Lda
37
+ info@teromovigo.com / https://teromovigo.com
38
+
39
+ 4. RESTRICTIONS
40
+
41
+ Except as expressly permitted under this Agreement, you may not:
42
+
43
+ (a) use the Software for Commercial Use;
44
+ (b) sublicense, sell, lease, or otherwise distribute the Software
45
+ for Commercial Use;
46
+ (c) remove or alter any copyright or attribution notices.
47
+
48
+ 5. ATTRIBUTION
49
+
50
+ Any redistribution of the Software, in whole or in part, must retain
51
+ this license text and provide appropriate attribution to the Licensor.
52
+
53
+ 6. OWNERSHIP
54
+
55
+ The Software is licensed, not sold. All intellectual property rights,
56
+ including copyright, remain with the Licensor.
57
+
58
+ 7. NO WARRANTY
59
+
60
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
61
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
62
+ FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
63
+
64
+ 8. LIMITATION OF LIABILITY
65
+
66
+ IN NO EVENT SHALL THE LICENSOR BE LIABLE FOR ANY CLAIM, DAMAGES, OR
67
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,
68
+ ARISING FROM OR IN CONNECTION WITH THE SOFTWARE OR ITS USE.
69
+
70
+ 9. TERMINATION
71
+
72
+ This license terminates automatically if you breach any of its terms.
73
+ Upon termination, you must cease all use of the Software.
74
+
75
+ 10. GOVERNING LAW
76
+
77
+ This Agreement shall be governed by and construed in accordance with
78
+ the laws of Portugal, without regard to conflict-of-law principles.
@@ -0,0 +1,8 @@
1
+ # Source distribution: the Cython sources (the wheels are built from them), the manual, the tests.
2
+ recursive-include src/otl_map *.pyx *.pxd
3
+ recursive-include src/otl_map/data *
4
+ recursive-include src/otl_map/docs *.pdf
5
+ recursive-include src/otl_map/examples *.txt *.py
6
+ recursive-exclude src/otl_map *.c *.so *.pyd
7
+ graft tests
8
+ global-exclude __pycache__ *.py[cod] .DS_Store
otl_map-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: otl-map
3
+ Version: 0.1.0
4
+ Summary: Global ocean tide loading maps with an FFT along latitude rows and a coastal near-field correction
5
+ Author-email: "Machiel S. Bos" <machiel.bos@teromovigo.com>
6
+ License-Expression: LicenseRef-otl-map
7
+ Project-URL: Repository, https://github.com/machielbos8/otl-map
8
+ Project-URL: Manual, https://github.com/machielbos8/otl-map/blob/main/src/otl_map/docs/otl-map_manual_v0.1.pdf
9
+ Project-URL: OTL API, https://otl.teromovigo.com
10
+ Project-URL: Onsala OTL service, https://elder.oso.chalmers.se/loading/l.php
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Cython
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Scientific/Engineering :: Physics
15
+ Classifier: Intended Audience :: Science/Research
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: numpy>=1.24
20
+ Requires-Dist: scipy
21
+ Requires-Dist: netCDF4
22
+ Requires-Dist: tqdm
23
+ Provides-Extra: plot
24
+ Requires-Dist: matplotlib; extra == "plot"
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # otl-map
30
+
31
+ Global ocean tide loading (OTL) maps computed with an FFT along latitude rows, with a coastal near-field
32
+ correction that also gives the OTL at any station.
33
+
34
+ **Version 0.1.0** (November 2026): `pip install otl-map`. The user manual comes with the package (`otl-map-examples`).
35
+
36
+ The method is described in Scherneck and Bos (in preparation), *Fast Computation of Ocean Tide Loading
37
+ Maps* (Journal of Geodesy). otl-map is for off-line computation (maps, many stations, other tide or Earth
38
+ models). For the OTL corrections of some stations, use the Onsala service at
39
+ <https://elder.oso.chalmers.se/loading/l.php>; for automatic computations from your own software, the OTL
40
+ API at <https://otl.teromovigo.com> (FES2014b, FES2022b, GOT5.5, TPXO10-atlas).
41
+
42
+ ## What it does
43
+
44
+ - prepares a tide model: water fraction of every cell from a full-resolution coastline, scaling of the tide by
45
+ this fraction, extension by one cell over the coast;
46
+ - computes global or regional OTL maps (vertical, north, east) with the row-wise FFT, with the Green's function
47
+ integrated analytically over the nearby cells;
48
+ - applies the near-field correction to refine the map at coastal grid nodes, or to compute the OTL at a station;
49
+ - writes station values in BLQ or JSON format, with or without the centre-of-mass correction.
50
+
51
+ Shipped with the package: load Green's functions for PREM and STW105, elastic and with anelastic dispersion
52
+ (CE and CM frames), and the Schwiderski (1980) M2 tide model as an example. The full-resolution coastline
53
+ (derived from GSHHG, Wessel and Smith 1996) is downloaded once on first use. Other tide models are not
54
+ distributed; see the documentation for the expected format.
55
+
56
+ ## Installation
57
+
58
+ In a virtual environment of its own (Linux and macOS; on Windows `py -m venv` and `Scripts\Activate.ps1`):
59
+
60
+ ```bash
61
+ python3 -m venv ~/venvs/otl-map
62
+ source ~/venvs/otl-map/bin/activate
63
+ pip install otl-map
64
+ otl-map --version
65
+ ```
66
+
67
+ pip also installs the dependencies (NumPy, SciPy, netCDF4, tqdm); no `requirements.txt` is needed. Then
68
+
69
+ ```bash
70
+ otl-map-examples
71
+ ```
72
+
73
+ copies the user manual (PDF) and the tutorial examples into a new folder `otl-map-examples`. Open the manual
74
+ first; `cd otl-map-examples/ex1 && python example1.py` runs the first example.
75
+
76
+ From source, for development:
77
+
78
+ ```bash
79
+ git clone https://github.com/machielbos8/otl-map.git && cd otl-map
80
+ python3 -m venv .venv && source .venv/bin/activate
81
+ pip install -e ".[test]"
82
+ pytest
83
+ ```
84
+
85
+ ## Licence
86
+
87
+ Free for non-commercial use (research, academic, educational). Commercial use requires a separate licence from
88
+ TeroMovigo – Earth Innovation Lda (info@teromovigo.com). See [LICENSE](LICENSE).
@@ -0,0 +1,60 @@
1
+ # otl-map
2
+
3
+ Global ocean tide loading (OTL) maps computed with an FFT along latitude rows, with a coastal near-field
4
+ correction that also gives the OTL at any station.
5
+
6
+ **Version 0.1.0** (November 2026): `pip install otl-map`. The user manual comes with the package (`otl-map-examples`).
7
+
8
+ The method is described in Scherneck and Bos (in preparation), *Fast Computation of Ocean Tide Loading
9
+ Maps* (Journal of Geodesy). otl-map is for off-line computation (maps, many stations, other tide or Earth
10
+ models). For the OTL corrections of some stations, use the Onsala service at
11
+ <https://elder.oso.chalmers.se/loading/l.php>; for automatic computations from your own software, the OTL
12
+ API at <https://otl.teromovigo.com> (FES2014b, FES2022b, GOT5.5, TPXO10-atlas).
13
+
14
+ ## What it does
15
+
16
+ - prepares a tide model: water fraction of every cell from a full-resolution coastline, scaling of the tide by
17
+ this fraction, extension by one cell over the coast;
18
+ - computes global or regional OTL maps (vertical, north, east) with the row-wise FFT, with the Green's function
19
+ integrated analytically over the nearby cells;
20
+ - applies the near-field correction to refine the map at coastal grid nodes, or to compute the OTL at a station;
21
+ - writes station values in BLQ or JSON format, with or without the centre-of-mass correction.
22
+
23
+ Shipped with the package: load Green's functions for PREM and STW105, elastic and with anelastic dispersion
24
+ (CE and CM frames), and the Schwiderski (1980) M2 tide model as an example. The full-resolution coastline
25
+ (derived from GSHHG, Wessel and Smith 1996) is downloaded once on first use. Other tide models are not
26
+ distributed; see the documentation for the expected format.
27
+
28
+ ## Installation
29
+
30
+ In a virtual environment of its own (Linux and macOS; on Windows `py -m venv` and `Scripts\Activate.ps1`):
31
+
32
+ ```bash
33
+ python3 -m venv ~/venvs/otl-map
34
+ source ~/venvs/otl-map/bin/activate
35
+ pip install otl-map
36
+ otl-map --version
37
+ ```
38
+
39
+ pip also installs the dependencies (NumPy, SciPy, netCDF4, tqdm); no `requirements.txt` is needed. Then
40
+
41
+ ```bash
42
+ otl-map-examples
43
+ ```
44
+
45
+ copies the user manual (PDF) and the tutorial examples into a new folder `otl-map-examples`. Open the manual
46
+ first; `cd otl-map-examples/ex1 && python example1.py` runs the first example.
47
+
48
+ From source, for development:
49
+
50
+ ```bash
51
+ git clone https://github.com/machielbos8/otl-map.git && cd otl-map
52
+ python3 -m venv .venv && source .venv/bin/activate
53
+ pip install -e ".[test]"
54
+ pytest
55
+ ```
56
+
57
+ ## Licence
58
+
59
+ Free for non-commercial use (research, academic, educational). Commercial use requires a separate licence from
60
+ TeroMovigo – Earth Innovation Lda (info@teromovigo.com). See [LICENSE](LICENSE).
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel", "Cython>=3.0", "numpy>=2.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "otl-map"
7
+ dynamic = ["version"]
8
+ description = "Global ocean tide loading maps with an FFT along latitude rows and a coastal near-field correction"
9
+ readme = "README.md"
10
+ license = "LicenseRef-otl-map"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Machiel S. Bos", email = "machiel.bos@teromovigo.com" }]
13
+ requires-python = ">=3.10"
14
+ dependencies = ["numpy>=1.24", "scipy", "netCDF4", "tqdm"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Cython",
18
+ "Operating System :: OS Independent",
19
+ "Topic :: Scientific/Engineering :: Physics",
20
+ "Intended Audience :: Science/Research",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ plot = ["matplotlib"]
25
+ test = ["pytest"]
26
+
27
+ [project.urls]
28
+ Repository = "https://github.com/machielbos8/otl-map"
29
+ Manual = "https://github.com/machielbos8/otl-map/blob/main/src/otl_map/docs/otl-map_manual_v0.1.pdf"
30
+ "OTL API" = "https://otl.teromovigo.com"
31
+ "Onsala OTL service" = "https://elder.oso.chalmers.se/loading/l.php"
32
+
33
+ [project.scripts]
34
+ otl-map = "otl_map.cli:main"
35
+ otl-map-examples = "otl_map.examples_cmd:main"
36
+
37
+ [tool.setuptools.dynamic]
38
+ version = { attr = "otl_map.__version__" }
39
+
40
+ [tool.setuptools.packages.find]
41
+ where = ["src"]
42
+
43
+ [tool.setuptools.package-data]
44
+ otl_map = ["*.pxd", "data/greenfnc/*", "data/tidemodels/*/*", "docs/*.pdf", "examples/*", "examples/*/*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
otl_map-0.1.0/setup.py ADDED
@@ -0,0 +1,11 @@
1
+ """Cython extensions of otl-map (metadata is in pyproject.toml)."""
2
+ import numpy
3
+ from Cython.Build import cythonize
4
+ from setuptools import Extension, setup
5
+
6
+ NP = [numpy.get_include()]
7
+ MODULES = {"geometry": [], "tidemodel": [], "greensfunction": NP, "cell_integration": NP,
8
+ "compute_otl_slow": NP, "_quadtree": NP, "compute_otl_fft": NP, "modify_tidemodel": NP}
9
+ extensions = [Extension(f"otl_map.{m}", [f"src/otl_map/{m}.pyx"], include_dirs=inc) for m, inc in MODULES.items()]
10
+
11
+ setup(ext_modules=cythonize(extensions, compiler_directives={"language_level": "3"}))
@@ -0,0 +1,5 @@
1
+ """otl-map: global ocean tide loading maps (row-wise FFT + coastal near-field correction).
2
+
3
+ Free for non-commercial use; commercial use requires a licence from TeroMovigo (see LICENSE).
4
+ """
5
+ __version__ = "0.1.0"
@@ -0,0 +1,173 @@
1
+ # cython: boundscheck=False, wraparound=False, cdivision=True, language_level=3
2
+ """Quadtree coastline (GSHHG-derived, Frisken & Perry layout) and land areas on a regular grid.
3
+
4
+ File layout (little endian): int32 n_levels, then float32 values in depth-first order: for every subdivided
5
+ cell its four children (x, y) = (0,0), (1,0), (0,1), (1,1); FLT_MAX = subdivided (its children follow),
6
+ otherwise a leaf with value >= 999 for land. The root covers longitude [0, 2 pi] and latitude [-pi/2, 3 pi/2]
7
+ (the upper half is unused); a leaf with location codes (xc, yc) at level L spans
8
+ lon [xc s, (xc + 2^L) s], lat [3 pi/2 - (yc + 2^L) s, 3 pi/2 - yc s], s = 2 pi / 2^(n_levels - 1).
9
+ Land areas are computed in plain longitude-latitude radians^2 and clipped to |lat| <= pi/2, exactly as
10
+ QuadtreeMask::exact of the C++ tools (cpp/create_mask, cpp/create_subcells of the development repository).
11
+ """
12
+ import numpy as np
13
+ cimport numpy as cnp
14
+ from libc.math cimport floor, fmin, fmax, M_PI
15
+
16
+ cdef float FLTMAX = np.finfo(np.float32).max
17
+
18
+
19
+ def read_land_leaves(path):
20
+ """Return (n_levels, xc, yc, level) of all land leaves (uint32, uint32, uint8 arrays)."""
21
+ raw = np.fromfile(path, dtype="<i4", count=1)
22
+ cdef int n_levels = int(raw[0])
23
+ cdef cnp.float32_t[:] v = np.fromfile(path, dtype="<f4", offset=4)
24
+ cdef Py_ssize_t nv = v.shape[0], p = 0, n = 0
25
+ cdef int root = n_levels - 1
26
+ # explicit stack: per level the parent codes and the index of the next child to read
27
+ cdef cnp.uint32_t[:] sx = np.zeros(n_levels + 1, np.uint32)
28
+ cdef cnp.uint32_t[:] sy = np.zeros(n_levels + 1, np.uint32)
29
+ cdef cnp.int32_t[:] si = np.zeros(n_levels + 1, np.int32)
30
+ xs = np.empty(nv, np.uint32)
31
+ ys = np.empty(nv, np.uint32)
32
+ ls = np.empty(nv, np.uint8)
33
+ cdef cnp.uint32_t[:] ox = xs
34
+ cdef cnp.uint32_t[:] oy = ys
35
+ cdef cnp.uint8_t[:] ol = ls
36
+ cdef int lev = root # level of the cell whose children are being read
37
+ cdef unsigned int half, cx, cy
38
+ cdef int i
39
+ cdef float val
40
+ sx[lev] = 0; sy[lev] = 0; si[lev] = 0
41
+ while lev <= root:
42
+ i = si[lev]
43
+ if i == 4: # all children done: back to the parent
44
+ lev += 1
45
+ if lev <= root:
46
+ si[lev] += 1
47
+ continue
48
+ if p >= nv:
49
+ raise ValueError("quadtree file ends early")
50
+ val = v[p]
51
+ p += 1
52
+ half = 1u << (lev - 1)
53
+ cx = sx[lev] + (half if (i == 1 or i == 3) else 0)
54
+ cy = sy[lev] + (half if (i == 2 or i == 3) else 0)
55
+ if val == FLTMAX: # subdivided: descend
56
+ lev -= 1
57
+ sx[lev] = cx; sy[lev] = cy; si[lev] = 0
58
+ else:
59
+ if val > 999.0:
60
+ ox[n] = cx; oy[n] = cy; ol[n] = lev - 1
61
+ n += 1
62
+ si[lev] += 1
63
+ return n_levels, xs[:n].copy(), ys[:n].copy(), ls[:n].copy()
64
+
65
+
66
+ def land_area(int n_levels, cnp.uint32_t[:] xc, cnp.uint32_t[:] yc, cnp.uint8_t[:] lv,
67
+ double xedge, double dx, int nx, double ytop, double dy, int ny, int row0=0, int row1=-1):
68
+ """Land area (rad^2) of the cells of a global regular grid, rows row0 <= j < row1 (north to south).
69
+
70
+ xedge: western edge of column 0 (rad), dx: spacing (rad), nx columns covering 2 pi (wrap);
71
+ ytop: northern edge of row 0 (rad), dy: spacing (rad)."""
72
+ if row1 < 0:
73
+ row1 = ny
74
+ out_np = np.zeros((row1 - row0, nx))
75
+ cdef double[:, :] out = out_np
76
+ cdef double s = 2.0 * M_PI / (1u << (n_levels - 1))
77
+ cdef double y3 = 1.5 * M_PI, hp = 0.5 * M_PI
78
+ cdef Py_ssize_t k, n = xc.shape[0]
79
+ cdef double x0, x1, y0, y1, ax, ay, cx0, cy1
80
+ cdef long i, i0, i1, j, j0, j1, ii
81
+ for k in range(n):
82
+ x0 = xc[k] * s
83
+ x1 = x0 + (1u << lv[k]) * s
84
+ y1 = y3 - yc[k] * s
85
+ y0 = y1 - (1u << lv[k]) * s
86
+ if y1 > hp:
87
+ y1 = hp
88
+ if y0 < -hp:
89
+ y0 = -hp
90
+ if y1 <= y0:
91
+ continue
92
+ j0 = <long>floor((ytop - y1) / dy)
93
+ j1 = <long>floor((ytop - y0) / dy)
94
+ if j1 < row0 or j0 >= row1:
95
+ continue
96
+ i0 = <long>floor((x0 - xedge) / dx)
97
+ i1 = <long>floor((x1 - xedge) / dx)
98
+ for j in range(max(j0, row0), min(j1, row1 - 1) + 1):
99
+ cy1 = ytop - j * dy
100
+ ay = fmin(y1, cy1) - fmax(y0, cy1 - dy)
101
+ if ay <= 0.0:
102
+ continue
103
+ for i in range(i0, i1 + 1):
104
+ cx0 = xedge + i * dx
105
+ ax = fmin(x1, cx0 + dx) - fmax(x0, cx0)
106
+ if ax <= 0.0:
107
+ continue
108
+ ii = i % nx
109
+ if ii < 0:
110
+ ii += nx
111
+ out[j - row0, ii] += ax * ay
112
+ return out_np
113
+
114
+
115
+ def subcell_land(int n_levels, cnp.uint32_t[:] xc, cnp.uint32_t[:] yc, cnp.uint8_t[:] lv,
116
+ double xedge, double dx, int nx, double ytop, double dy, int ny, int cf,
117
+ cnp.int64_t[:] cells, int row0, int row1):
118
+ """Land area (rad^2) of the cf x cf sub-cells of the given cells (linear index j*nx + i, rows row0..row1-1).
119
+
120
+ Returns float64 (len(cells), cf*cf), sub-cells rows north to south, columns west to east."""
121
+ cdef Py_ssize_t nc = cells.shape[0]
122
+ pos_np = np.full((row1 - row0) * nx, -1, np.int64)
123
+ cdef cnp.int64_t[:] pos = pos_np
124
+ cdef Py_ssize_t q
125
+ for q in range(nc):
126
+ pos[cells[q] - <long>row0 * nx] = q
127
+ out_np = np.zeros((nc, cf * cf))
128
+ cdef double[:, :] out = out_np
129
+ cdef double s = 2.0 * M_PI / (1u << (n_levels - 1))
130
+ cdef double y3 = 1.5 * M_PI, hp = 0.5 * M_PI
131
+ cdef double ddx = dx / cf, ddy = dy / cf
132
+ cdef Py_ssize_t k, n = xc.shape[0]
133
+ cdef double x0, x1, y0, y1, ax, ay, cx0, cy1
134
+ cdef long I, I0, I1, J, J0, J1, i, j, c, ii, jj
135
+ cdef long R0 = <long>row0 * cf, R1 = <long>row1 * cf
136
+ for k in range(n):
137
+ x0 = xc[k] * s
138
+ x1 = x0 + (1u << lv[k]) * s
139
+ y1 = y3 - yc[k] * s
140
+ y0 = y1 - (1u << lv[k]) * s
141
+ if y1 > hp:
142
+ y1 = hp
143
+ if y0 < -hp:
144
+ y0 = -hp
145
+ if y1 <= y0:
146
+ continue
147
+ J0 = <long>floor((ytop - y1) / ddy)
148
+ J1 = <long>floor((ytop - y0) / ddy)
149
+ if J1 < R0 or J0 >= R1:
150
+ continue
151
+ I0 = <long>floor((x0 - xedge) / ddx)
152
+ I1 = <long>floor((x1 - xedge) / ddx)
153
+ for J in range(max(J0, R0), min(J1, R1 - 1) + 1):
154
+ cy1 = ytop - J * ddy
155
+ ay = fmin(y1, cy1) - fmax(y0, cy1 - ddy)
156
+ if ay <= 0.0:
157
+ continue
158
+ j = J // cf
159
+ jj = J - j * cf
160
+ for I in range(I0, I1 + 1):
161
+ cx0 = xedge + I * ddx
162
+ ax = fmin(x1, cx0 + ddx) - fmax(x0, cx0)
163
+ if ax <= 0.0:
164
+ continue
165
+ i = I // cf
166
+ ii = I - i * cf
167
+ i = i % nx
168
+ if i < 0:
169
+ i += nx
170
+ c = pos[(j - row0) * nx + i]
171
+ if c >= 0:
172
+ out[c, jj * cf + ii] += ax * ay
173
+ return out_np
@@ -0,0 +1,26 @@
1
+ """Minimal stand-in for the provenance Run used in the private repository (prints only)."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class Run:
6
+ def __init__(self, purpose, params=None, inputs=None, script=None):
7
+ self.purpose = purpose
8
+
9
+ def __enter__(self):
10
+ print(f":: {self.purpose}")
11
+ return self
12
+
13
+ def __exit__(self, *exc):
14
+ return False
15
+
16
+ def note(self, **kw):
17
+ for k, v in kw.items():
18
+ print(f" {k} = {v}")
19
+
20
+ def output(self, path):
21
+ return path
22
+
23
+ def write_text(self, path, txt):
24
+ with open(path, "w") as f:
25
+ f.write(txt)
26
+ return path
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env python3
2
+ """Bundle v2 for the unified coastal refinement (docs/code/unified_refinement_plan.md).
3
+
4
+ refine_bundle_v2/<model>/
5
+ meta.json grid (nx, ny, x0/y0 = first cell centre, sp), ncell N, cf, M = N + 1, harmonics
6
+ idx.npy int64 sorted linear cell index j*nx + i of every stored cell
7
+ w0.npy float32 cell water fraction (mask_<model>.nc, quadtree)
8
+ tide.npy complex64 (n, nharm) u + i v of the modified tide model, exactly as compute_otl_fft
9
+ reads it (amp*cos(pha), amp*sin(pha); land 999 -> 0)
10
+ sptr.npy int32 row into sub.npy for a coastal cell (1e-6 < w0 < 1-1e-6), else -1
11
+ sub.npy uint8 (n_coastal, cf*cf) quadtree sub-cell water fraction * 255 (cpp/create_subcells),
12
+ rows N->S, columns W->E
13
+ coarse_<GF>.npy float64 (ny, 3, 2M+1, 2M+1) FFT kernel element for a node in tide row j and the
14
+ cell at row offset t, column offset di (coarse_kernel.table_for_row)
15
+
16
+ Stored cells: every cell within 2N columns/rows (Chebyshev, wrapping in longitude) of a coastal cell, so
17
+ the +-N patch of any station whose patch contains a coastal cell is complete.
18
+
19
+ Inputs: the water fractions and sub-cells of `otl-map masks <model>` (cache directory) and the prepared
20
+ tide model <model>_mod_ext (`otl-map prepare <model>`). Output: <cache>/refine_bundle_v2/<model>.
21
+ Command line: otl-map bundle <model> [PREM STW105 ...]
22
+ """
23
+ import json
24
+ import math
25
+ import os
26
+ import sys
27
+ from glob import glob
28
+ from multiprocessing import Pool
29
+
30
+ import netCDF4 as nc
31
+ import numpy as np
32
+
33
+ from otl_map.subcells_io import read_subcells # noqa: E402
34
+ from otl_map.paths import bundle_root, greenfnc_dir, mask_file as mask_path, subcells_dir, tidemodel_dir # noqa: E402
35
+ from otl_map._runlog import Run # noqa: E402
36
+
37
+ HARMS = ["m2", "s2", "n2", "k2", "k1", "o1", "p1", "q1", "mf", "mm", "ssa"]
38
+ GF_FILE = {"PREM": "PREM.dat", "PREM_disp": "PREM_disp.dat", "STW105": "STW105.dat", "STW105_disp": "STW105_disp.dat"}
39
+
40
+
41
+ def read_grd(path):
42
+ d = nc.Dataset(path)
43
+ nx, ny = (int(v) for v in d["dimension"][:])
44
+ z = np.array(d["z"][:], np.float32).reshape(ny, nx)
45
+ xr, yr, sp = (np.array(d[k][:], float) for k in ("x_range", "y_range", "spacing"))
46
+ d.close()
47
+ return z, xr, yr, sp
48
+
49
+
50
+ def dilate(a, r):
51
+ """Box (Chebyshev) dilation by r cells, wrapping in longitude, not across the poles."""
52
+ out = a.copy()
53
+ for _ in range(r):
54
+ h = out | np.roll(out, 1, axis=1) | np.roll(out, -1, axis=1)
55
+ v = h.copy()
56
+ v[1:] |= h[:-1]
57
+ v[:-1] |= h[1:]
58
+ out = v
59
+ return out
60
+
61
+
62
+ _G = {}
63
+
64
+
65
+ def _rows(args):
66
+ gf_file, rows, cy1, csp, M, ny = args
67
+ from otl_map.coarse_kernel import load_gf, table_for_row
68
+ if gf_file not in _G:
69
+ C = json.load(open(os.path.join(greenfnc_dir(), "greensfunction_approx.json")))[gf_file]
70
+ _G[gf_file] = ([load_gf(gf_file, c) for c in range(3)], [C[str(c)] for c in range(3)])
71
+ gfs, ccs = _G[gf_file]
72
+ out = []
73
+ for j in rows:
74
+ lat = math.degrees(cy1 - (j + 0.5) * csp)
75
+ if abs(lat) > 89.5:
76
+ out.append((j, np.zeros((3, 2 * M + 1, 2 * M + 1))))
77
+ else:
78
+ out.append((j, table_for_row(gfs, ccs, j, cy1, csp, csp, M, cny=ny)))
79
+ return out
80
+
81
+
82
+ def wet_sub_for(sp):
83
+ """Point-load sub-cells per side for whole wet cells beyond the 0.15 deg fit range (nearfield._fine).
84
+
85
+ Up to 1/16 deg these cells are >= 9 km from the station and 10 x 10 suffices. On coarser lattices
86
+ (GOT5.5, 1/8 deg) the station's own cell and its neighbours fall in this class, 1-3 km from P; 10 x 10
87
+ (1.4 km) errs by up to 0.03 mm per m of water, 40 x 40 by 0.0014 mm
88
+ (paper_JoG/paper_scripts/nf_coarse_grid_owncell_test.py, 2026-11-22)."""
89
+ return 10 if sp <= 0.0625 + 1e-9 else 40
90
+
91
+
92
+ def build_bundle(model, earths=("PREM",), ncell=None, out=None, workers=None, wet_sub=None):
93
+ """Near-field bundle for <model> and the given Earth models; returns the output directory.
94
+ ncell: patch half-width in cells (default about 0.25 deg, at least 4);
95
+ wet_sub: point-load sub-cells per side for whole wet cells beyond the fit range (default wet_sub_for)."""
96
+ earths = list(earths)
97
+ NCELL = ncell
98
+ root = bundle_root()
99
+ out = out or str(root / model if not NCELL else root.parent / f"refine_bundle_v2_np{NCELL}" / model)
100
+ tide_dir = tidemodel_dir(f"{model}_mod_ext")
101
+ mask_file = mask_path(model)
102
+ parts = sorted(glob(os.path.join(subcells_dir(model), "part_*.bin")))
103
+ if not os.path.isfile(mask_file) or not parts:
104
+ raise FileNotFoundError(f"water fractions/sub-cells of {model} not found: run `otl-map masks {model}`")
105
+ inputs = [mask_file, f"{tide_dir}/amp.m2"] + parts
106
+ with Run(f"unified refinement: bundle v2 for {model} ({', '.join(earths)})",
107
+ params=dict(model=model, earth_models=earths, ncell=NCELL or "default"), inputs=inputs, script=__file__) as run:
108
+ w0, xr, yr, sp = read_grd(mask_file)
109
+ ny, nx = w0.shape
110
+ spx = float(sp[0])
111
+ if abs(nx * spx - 360.0) > 1e-6: # e.g. 10801 columns with centres 0..360: see tools/cut_seam_column.py
112
+ raise SystemExit(f"{model}: {nx} columns x {spx} deg != 360 deg (duplicate seam column?)")
113
+ N = int(NCELL) if NCELL else max(4, int(round(0.25 / spx)))
114
+ M = N + 1
115
+ S = [read_subcells(p) for p in parts]
116
+ cf = S[0]["cf"]
117
+ ks = np.concatenate([s["k"] for s in S])
118
+ fs = np.concatenate([s["f"] for s in S])
119
+ o = np.argsort(ks)
120
+ ks, fs = ks[o], fs[o]
121
+ coastal = np.zeros(ny * nx, bool)
122
+ coastal[ks] = True
123
+ coastal = coastal.reshape(ny, nx)
124
+ keep = dilate(coastal, 2 * N)
125
+ idx = np.flatnonzero(keep.ravel()).astype(np.int64)
126
+ print(f"{model}: {nx}x{ny}, N={N}, cf={cf}, coastal {len(ks):,}, stored {len(idx):,}", flush=True)
127
+ sptr = np.full(len(idx), -1, np.int32)
128
+ pos = np.searchsorted(idx, ks)
129
+ assert np.all(idx[pos] == ks)
130
+ sptr[pos] = np.arange(len(ks), dtype=np.int32)
131
+ harms = [h for h in HARMS if os.path.exists(f"{tide_dir}/amp.{h}")]
132
+ tide = np.zeros((len(idx), len(harms)), np.complex64)
133
+ for hi, h in enumerate(harms):
134
+ a, _, _, _ = read_grd(f"{tide_dir}/amp.{h}")
135
+ p, _, _, _ = read_grd(f"{tide_dir}/pha.{h}")
136
+ a, p = a.ravel()[idx].astype(float), p.ravel()[idx].astype(float)
137
+ land = ~(a < 999.0)
138
+ u = a * np.cos(np.radians(p))
139
+ v = a * np.sin(np.radians(p))
140
+ u[land] = v[land] = 0.0
141
+ tide[:, hi] = u + 1j * v
142
+ os.makedirs(out, exist_ok=True)
143
+ for name, arr in (("idx", idx), ("w0", w0.ravel()[idx].astype(np.float32)), ("tide", tide),
144
+ ("sptr", sptr), ("sub", fs)):
145
+ np.save(f"{out}/{name}.npy", arr)
146
+ run.output(f"{out}/{name}.npy")
147
+ cy1, csp = math.radians(float(yr[1])), math.radians(spx)
148
+ for e in earths:
149
+ T = np.zeros((ny, 3, 2 * M + 1, 2 * M + 1))
150
+ chunks = [list(range(j, min(j + 40, ny))) for j in range(0, ny, 40)]
151
+ with Pool(workers or min(8, os.cpu_count() or 1)) as pool:
152
+ for res in pool.imap_unordered(_rows, [(GF_FILE[e], c, cy1, csp, M, ny) for c in chunks]):
153
+ for j, t in res:
154
+ T[j] = t
155
+ np.save(f"{out}/coarse_{e}.npy", T)
156
+ run.output(f"{out}/coarse_{e}.npy")
157
+ print(f" coarse table {e} done", flush=True)
158
+ meta = dict(model=model, nx=nx, ny=ny, x0=float(xr[0]) + spx / 2, y0=float(yr[1]) - spx / 2, sp=spx,
159
+ ncell=N, M=M, cf=cf, wet_sub=int(wet_sub or wet_sub_for(spx)), harmonics=harms, earth_models=earths, rho=1030.0,
160
+ coastal_cells=int(len(ks)), stored_cells=int(len(idx)), tide_model=f"{model}_mod_ext")
161
+ json.dump(meta, open(f"{out}/meta.json", "w"), indent=2)
162
+ run.output(f"{out}/meta.json")
163
+ run.note(**{k: meta[k] for k in ("ncell", "cf", "wet_sub", "coastal_cells", "stored_cells")})
164
+ return out
165
+
166
+
167
+ if __name__ == "__main__":
168
+ build_bundle(sys.argv[1], sys.argv[2:] or ["PREM"])