neuralftw 0.1.0__py3-none-any.whl
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.
- neuralftw/__init__.py +12 -0
- neuralftw/__init__.pyi +40 -0
- neuralftw/_errors.py +28 -0
- neuralftw/_types.py +12 -0
- neuralftw/_utils.py +103 -0
- neuralftw/analysis/__init__.py +36 -0
- neuralftw/analysis/intrinsic_dim.py +347 -0
- neuralftw/analysis/variogram.py +469 -0
- neuralftw/cli.py +434 -0
- neuralftw/conf/model/aef.yaml +6 -0
- neuralftw/conf/model/climplicit.yaml +5 -0
- neuralftw/conf/model/csp-fmow.yaml +5 -0
- neuralftw/conf/model/csp-inat.yaml +5 -0
- neuralftw/conf/model/gair.yaml +5 -0
- neuralftw/conf/model/geoclip.yaml +5 -0
- neuralftw/conf/model/geoclosp.yaml +5 -0
- neuralftw/conf/model/gtloc.yaml +5 -0
- neuralftw/conf/model/hydroloc.yaml +5 -0
- neuralftw/conf/model/le-sinr.yaml +5 -0
- neuralftw/conf/model/mind-3072.yaml +7 -0
- neuralftw/conf/model/mind-head.yaml +6 -0
- neuralftw/conf/model/mind.yaml +7 -0
- neuralftw/conf/model/nerf.yaml +5 -0
- neuralftw/conf/model/osmgraphclip-a-l10.yaml +5 -0
- neuralftw/conf/model/osmgraphclip-a-l40.yaml +5 -0
- neuralftw/conf/model/osmgraphclip-ms-l10.yaml +5 -0
- neuralftw/conf/model/osmgraphclip.yaml +5 -0
- neuralftw/conf/model/rff3072.yaml +8 -0
- neuralftw/conf/model/satclip-resnet18-l10.yaml +5 -0
- neuralftw/conf/model/satclip-resnet18-l40.yaml +5 -0
- neuralftw/conf/model/satclip-resnet50-l10.yaml +5 -0
- neuralftw/conf/model/satclip-resnet50-l40.yaml +5 -0
- neuralftw/conf/model/satclip-vit16-l10.yaml +5 -0
- neuralftw/conf/model/satclip.yaml +5 -0
- neuralftw/conf/model/sh40.yaml +5 -0
- neuralftw/conf/model/sincos.yaml +4 -0
- neuralftw/conf/model/sinr.yaml +5 -0
- neuralftw/conf/model/sled-s2.yaml +5 -0
- neuralftw/conf/model/sled.yaml +5 -0
- neuralftw/conf/model/spherical-harmonics.yaml +5 -0
- neuralftw/conf/model/taxabind.yaml +5 -0
- neuralftw/conf/model/terranova-st.yaml +6 -0
- neuralftw/conf/model/terranova.yaml +6 -0
- neuralftw/conf/model/tessera.yaml +6 -0
- neuralftw/conf/model/tte.yaml +5 -0
- neuralftw/conf/model/xyz.yaml +4 -0
- neuralftw/coordbench/__init__.py +10 -0
- neuralftw/coordbench/__init__.pyi +93 -0
- neuralftw/coordbench/catalog.py +161 -0
- neuralftw/coordbench/config.py +575 -0
- neuralftw/coordbench/datasets.py +850 -0
- neuralftw/coordbench/leaderboard.py +132 -0
- neuralftw/coordbench/run.py +1181 -0
- neuralftw/coordbench/taxonomy.py +119 -0
- neuralftw/data/cities15000.parquet +0 -0
- neuralftw/models/__init__.py +10 -0
- neuralftw/models/__init__.pyi +244 -0
- neuralftw/models/_base.py +275 -0
- neuralftw/models/_utils.py +177 -0
- neuralftw/models/climplicit.py +503 -0
- neuralftw/models/csp.py +466 -0
- neuralftw/models/encoders.py +358 -0
- neuralftw/models/geoclosp.py +220 -0
- neuralftw/models/gtloc.py +181 -0
- neuralftw/models/hydroloc.py +221 -0
- neuralftw/models/lesinr.py +176 -0
- neuralftw/models/mind.py +429 -0
- neuralftw/models/onnx.py +472 -0
- neuralftw/models/osmgraphclip.py +218 -0
- neuralftw/models/products.py +673 -0
- neuralftw/models/registry.py +417 -0
- neuralftw/models/rff_capsule.py +543 -0
- neuralftw/models/satclip.py +598 -0
- neuralftw/models/sinr.py +223 -0
- neuralftw/models/terranova.py +1016 -0
- neuralftw/models/tte.py +432 -0
- neuralftw/probes/__init__.py +71 -0
- neuralftw/probes/classifiers.py +505 -0
- neuralftw/probes/linear.py +888 -0
- neuralftw/probes/metrics.py +173 -0
- neuralftw/probes/spatial.py +457 -0
- neuralftw/probes/splits.py +261 -0
- neuralftw/py.typed +0 -0
- neuralftw/viz.py +312 -0
- neuralftw-0.1.0.dist-info/METADATA +324 -0
- neuralftw-0.1.0.dist-info/RECORD +89 -0
- neuralftw-0.1.0.dist-info/WHEEL +4 -0
- neuralftw-0.1.0.dist-info/entry_points.txt +3 -0
- neuralftw-0.1.0.dist-info/licenses/LICENSE +21 -0
neuralftw/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Copyright (c) Taylor Geospatial. All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""NeuralFTW: Implicit Neural Representations for Earth Observation."""
|
|
5
|
+
|
|
6
|
+
import lazy_loader as lazy
|
|
7
|
+
|
|
8
|
+
__version__ = '0.1.0'
|
|
9
|
+
|
|
10
|
+
__getattr__, __dir__, _lazy_all = lazy.attach_stub(__name__, __file__)
|
|
11
|
+
|
|
12
|
+
__all__ = tuple(sorted({'__version__', *_lazy_all}))
|
neuralftw/__init__.pyi
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Copyright (c) Taylor Geospatial. All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""Type stubs for top-level NeuralFTW lazy exports."""
|
|
5
|
+
|
|
6
|
+
from . import analysis, cli, coordbench, models, probes, viz
|
|
7
|
+
from ._errors import (
|
|
8
|
+
ConfigError,
|
|
9
|
+
DatasetNotFoundError,
|
|
10
|
+
DependencyNotFoundError,
|
|
11
|
+
NeuralFTWError,
|
|
12
|
+
)
|
|
13
|
+
from .models._base import LocationEncoder
|
|
14
|
+
from .models.registry import get_model, list_models, register_model, unregister_model
|
|
15
|
+
from .viz import embeddings_to_rgb, encode_grid, make_coord_grid, plot_embedding_map
|
|
16
|
+
|
|
17
|
+
__version__: str
|
|
18
|
+
|
|
19
|
+
__all__: tuple[str, ...] = (
|
|
20
|
+
'ConfigError',
|
|
21
|
+
'DatasetNotFoundError',
|
|
22
|
+
'DependencyNotFoundError',
|
|
23
|
+
'LocationEncoder',
|
|
24
|
+
'NeuralFTWError',
|
|
25
|
+
'__version__',
|
|
26
|
+
'analysis',
|
|
27
|
+
'cli',
|
|
28
|
+
'coordbench',
|
|
29
|
+
'embeddings_to_rgb',
|
|
30
|
+
'encode_grid',
|
|
31
|
+
'get_model',
|
|
32
|
+
'list_models',
|
|
33
|
+
'make_coord_grid',
|
|
34
|
+
'models',
|
|
35
|
+
'plot_embedding_map',
|
|
36
|
+
'probes',
|
|
37
|
+
'register_model',
|
|
38
|
+
'unregister_model',
|
|
39
|
+
'viz',
|
|
40
|
+
)
|
neuralftw/_errors.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Copyright (c) Taylor Geospatial. All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""Custom exception hierarchy for NeuralFTW."""
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class NeuralFTWError(Exception):
|
|
8
|
+
"""Base exception for all NeuralFTW errors."""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DependencyNotFoundError(NeuralFTWError):
|
|
12
|
+
"""Raised when an optional dependency is not installed."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class DatasetNotFoundError(NeuralFTWError, FileNotFoundError):
|
|
16
|
+
"""Raised when a required dataset or file cannot be found."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ConfigError(NeuralFTWError, ValueError):
|
|
20
|
+
"""Raised when a configuration file or parameter is invalid."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
__all__ = (
|
|
24
|
+
'ConfigError',
|
|
25
|
+
'DatasetNotFoundError',
|
|
26
|
+
'DependencyNotFoundError',
|
|
27
|
+
'NeuralFTWError',
|
|
28
|
+
)
|
neuralftw/_types.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Copyright (c) Taylor Geospatial. All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""Shared type aliases for NeuralFTW."""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
type Path = str | os.PathLike[str]
|
|
10
|
+
type CoordOrder = Literal['lonlat', 'latlon']
|
|
11
|
+
|
|
12
|
+
__all__ = ('CoordOrder', 'Path')
|
neuralftw/_utils.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# Copyright (c) Taylor Geospatial. All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""Shared runtime utilities for NeuralFTW."""
|
|
5
|
+
|
|
6
|
+
import importlib
|
|
7
|
+
from types import ModuleType
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
from ._errors import DependencyNotFoundError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def lazy_import(name: str, extra: str | None = None) -> ModuleType:
|
|
15
|
+
"""Import an optional dependency lazily, raising a helpful error if missing.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
name: Fully qualified module name to import.
|
|
19
|
+
extra: Optional ``neuralftw`` extra name providing the dependency.
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
The imported module object.
|
|
23
|
+
|
|
24
|
+
Raises:
|
|
25
|
+
DependencyNotFoundError: If *name* cannot be imported.
|
|
26
|
+
"""
|
|
27
|
+
try:
|
|
28
|
+
return importlib.import_module(name)
|
|
29
|
+
except ModuleNotFoundError:
|
|
30
|
+
install_hint = f'neuralftw[{extra}]' if extra is not None else name
|
|
31
|
+
raise DependencyNotFoundError(
|
|
32
|
+
f'{name} is not installed and is required for this feature. '
|
|
33
|
+
f"Install it with 'pip install {install_hint}'."
|
|
34
|
+
) from None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def resolve_device(device: str | torch.device = 'cpu') -> torch.device:
|
|
38
|
+
"""Resolve and validate a PyTorch device specification.
|
|
39
|
+
|
|
40
|
+
Explicit ``'cpu'`` requests never query CUDA availability. ``'auto'`` selects the
|
|
41
|
+
current CUDA device when available and otherwise falls back to CPU. Unavailable
|
|
42
|
+
or out-of-range CUDA/MPS requests fail eagerly.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
device: Target device string (e.g. ``'cpu'``, ``'auto'``, ``'cuda'``,
|
|
46
|
+
``'cuda:0'``, ``'mps'``) or :class:`torch.device` instance.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
Validated :class:`torch.device` instance.
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
ValueError: If *device* is empty, malformed, unavailable, or out of range.
|
|
53
|
+
"""
|
|
54
|
+
if isinstance(device, str):
|
|
55
|
+
raw = device.strip()
|
|
56
|
+
if not raw:
|
|
57
|
+
raise ValueError('Device string must not be empty.')
|
|
58
|
+
if raw == 'cpu':
|
|
59
|
+
return torch.device('cpu')
|
|
60
|
+
if raw == 'auto':
|
|
61
|
+
if torch.cuda.is_available():
|
|
62
|
+
return torch.device('cuda', torch.cuda.current_device())
|
|
63
|
+
return torch.device('cpu')
|
|
64
|
+
try:
|
|
65
|
+
resolved = torch.device(raw)
|
|
66
|
+
except (RuntimeError, ValueError) as err:
|
|
67
|
+
raise ValueError(f'Invalid device: {device!r}.') from err
|
|
68
|
+
else:
|
|
69
|
+
resolved = device
|
|
70
|
+
|
|
71
|
+
if resolved.type == 'cpu':
|
|
72
|
+
return resolved
|
|
73
|
+
if resolved.type == 'cuda':
|
|
74
|
+
if not torch.cuda.is_available():
|
|
75
|
+
raise ValueError(
|
|
76
|
+
f'CUDA device {resolved!s} requested, but CUDA is not available.'
|
|
77
|
+
)
|
|
78
|
+
if resolved.index is not None:
|
|
79
|
+
count = torch.cuda.device_count()
|
|
80
|
+
if resolved.index >= count:
|
|
81
|
+
raise ValueError(
|
|
82
|
+
f'CUDA device index {resolved.index} is out of range for '
|
|
83
|
+
f'{count} available device(s).'
|
|
84
|
+
)
|
|
85
|
+
return resolved
|
|
86
|
+
if resolved.type == 'mps':
|
|
87
|
+
if not torch.backends.mps.is_available():
|
|
88
|
+
raise ValueError('MPS device requested, but MPS is not available.')
|
|
89
|
+
return resolved
|
|
90
|
+
return resolved
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def float64_dtype(device: torch.device) -> torch.dtype:
|
|
94
|
+
"""Return ``torch.float32`` on MPS (no float64 support) and ``torch.float64`` elsewhere."""
|
|
95
|
+
return torch.float32 if device.type == 'mps' else torch.float64
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def float64_device(device: torch.device) -> torch.device:
|
|
99
|
+
"""Return CPU when *device* is MPS (no float64 support), otherwise *device*."""
|
|
100
|
+
return torch.device('cpu') if device.type == 'mps' else device
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
__all__ = ('float64_device', 'float64_dtype', 'lazy_import', 'resolve_device')
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Copyright (c) Taylor Geospatial. All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""Spatial statistics, implicit resolution, and intrinsic dimension analysis."""
|
|
5
|
+
|
|
6
|
+
from .intrinsic_dim import (
|
|
7
|
+
SUPPORTED_ESTIMATORS,
|
|
8
|
+
analyze_intrinsic_dimension,
|
|
9
|
+
estimate_intrinsic_dimension,
|
|
10
|
+
generate_equal_area_grid,
|
|
11
|
+
participation_ratio,
|
|
12
|
+
)
|
|
13
|
+
from .variogram import (
|
|
14
|
+
EARTH_RADIUS_KM,
|
|
15
|
+
KM_PER_DEGREE,
|
|
16
|
+
analyze_implicit_resolution,
|
|
17
|
+
empirical_semivariogram,
|
|
18
|
+
geodesic_offset,
|
|
19
|
+
half_sill_distance,
|
|
20
|
+
sample_sphere_points,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = (
|
|
24
|
+
'EARTH_RADIUS_KM',
|
|
25
|
+
'KM_PER_DEGREE',
|
|
26
|
+
'SUPPORTED_ESTIMATORS',
|
|
27
|
+
'analyze_implicit_resolution',
|
|
28
|
+
'analyze_intrinsic_dimension',
|
|
29
|
+
'empirical_semivariogram',
|
|
30
|
+
'estimate_intrinsic_dimension',
|
|
31
|
+
'generate_equal_area_grid',
|
|
32
|
+
'geodesic_offset',
|
|
33
|
+
'half_sill_distance',
|
|
34
|
+
'participation_ratio',
|
|
35
|
+
'sample_sphere_points',
|
|
36
|
+
)
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
# Copyright (c) Taylor Geospatial. All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""Intrinsic dimension and participation ratio analysis for location embeddings."""
|
|
5
|
+
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from typing import TYPE_CHECKING, Any
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import torch
|
|
11
|
+
from numpy.typing import NDArray
|
|
12
|
+
from torch import Tensor
|
|
13
|
+
|
|
14
|
+
from .._utils import float64_dtype, lazy_import, resolve_device
|
|
15
|
+
from .variogram import EARTH_RADIUS_KM
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from ..models._base import LocationEncoder
|
|
19
|
+
|
|
20
|
+
#: Estimator names supported via the optional ``torchid`` dependency.
|
|
21
|
+
SUPPORTED_ESTIMATORS: tuple[str, ...] = ('fishers', 'mle', 'mom', 'tle', 'twonn')
|
|
22
|
+
|
|
23
|
+
_ESTIMATOR_SET: frozenset[str] = frozenset(SUPPORTED_ESTIMATORS)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _to_float64_2d(
|
|
27
|
+
embeddings: NDArray[np.floating[Any]] | Tensor,
|
|
28
|
+
) -> NDArray[np.float64]:
|
|
29
|
+
"""Validate and convert a 2D embedding array or tensor to float64."""
|
|
30
|
+
if isinstance(embeddings, Tensor):
|
|
31
|
+
arr = embeddings.detach().cpu().to(dtype=torch.float64).numpy()
|
|
32
|
+
else:
|
|
33
|
+
arr = np.asarray(embeddings, dtype=np.float64)
|
|
34
|
+
if arr.ndim != 2 or arr.shape[0] < 2 or arr.shape[1] < 1:
|
|
35
|
+
raise ValueError(
|
|
36
|
+
'embeddings must be a 2D array with at least 2 samples and 1 feature.'
|
|
37
|
+
)
|
|
38
|
+
return arr
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def generate_equal_area_grid(
|
|
42
|
+
spacing_km: float = 100.0,
|
|
43
|
+
*,
|
|
44
|
+
lat_min: float = -90.0,
|
|
45
|
+
lat_max: float = 90.0,
|
|
46
|
+
jitter_km: float = 0.0,
|
|
47
|
+
seed: int = 0,
|
|
48
|
+
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
|
|
49
|
+
"""Generate a deterministic equal-area Fibonacci sphere grid at *spacing_km*.
|
|
50
|
+
|
|
51
|
+
Places ``N = max(2, round(4 * pi * R^2 / spacing_km^2))`` points globally on a
|
|
52
|
+
sphere of radius ``R = 6371.0 km`` (``N = 51,006`` at ``spacing_km=100.0``) using
|
|
53
|
+
the golden-angle Fibonacci lattice:
|
|
54
|
+
|
|
55
|
+
- ``z_i = 1 - (2 * i + 1) / N`` for ``i = 0, ..., N - 1``
|
|
56
|
+
- ``lat_i = arcsin(z_i)`` in degrees
|
|
57
|
+
- ``lon_i = ((degrees(i * pi * (3 - sqrt(5))) + 180) mod 360) - 180``
|
|
58
|
+
|
|
59
|
+
Points avoid the exact poles, have zero duplicates, and maintain near-isotropic
|
|
60
|
+
neighbor spacing across all latitudes. When ``jitter_km > 0``, each lattice point
|
|
61
|
+
is displaced along a random bearing by an equal-area disk radius
|
|
62
|
+
``jitter_km * sqrt(U)`` via the exact spherical geodesic formula; setting
|
|
63
|
+
``jitter_km=spacing_km`` breaks lattice regularity so Poisson-process k-NN
|
|
64
|
+
estimators such as ``TwoNN`` do not observe degenerate ``r_2 / r_1 ~ 1`` ratios.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
spacing_km: Target characteristic spacing between neighboring grid points in
|
|
68
|
+
kilometres (must be finite and positive).
|
|
69
|
+
lat_min: Minimum latitude in degrees (inclusive).
|
|
70
|
+
lat_max: Maximum latitude in degrees (inclusive).
|
|
71
|
+
jitter_km: Optional maximum geodesic disk perturbation radius in kilometres
|
|
72
|
+
(must be finite and non-negative; default ``0.0`` for deterministic grid).
|
|
73
|
+
seed: Random seed used when ``jitter_km > 0``.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
Tuple ``(lon, lat)`` of 1D float64 coordinate arrays in WGS84 degrees.
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
ValueError: If *spacing_km* or *jitter_km* is invalid, latitude bounds are
|
|
80
|
+
invalid, or no grid points fall inside ``[lat_min, lat_max]``.
|
|
81
|
+
"""
|
|
82
|
+
if not np.isfinite(spacing_km) or spacing_km <= 0.0:
|
|
83
|
+
raise ValueError(f'spacing_km must be finite and positive, got {spacing_km}.')
|
|
84
|
+
if not np.isfinite(jitter_km) or jitter_km < 0.0:
|
|
85
|
+
raise ValueError(f'jitter_km must be finite and non-negative, got {jitter_km}.')
|
|
86
|
+
if not (-90.0 <= lat_min < lat_max <= 90.0):
|
|
87
|
+
raise ValueError(
|
|
88
|
+
f'Expected -90 <= lat_min < lat_max <= 90, got [{lat_min}, {lat_max}].'
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
surface_area_km2 = 4.0 * np.pi * EARTH_RADIUS_KM * EARTH_RADIUS_KM
|
|
92
|
+
n_global = max(2, round(surface_area_km2 / (spacing_km * spacing_km)))
|
|
93
|
+
idx = np.arange(n_global, dtype=np.float64)
|
|
94
|
+
z = 1.0 - (2.0 * idx + 1.0) / float(n_global)
|
|
95
|
+
lat = np.degrees(np.arcsin(np.clip(z, -1.0, 1.0)))
|
|
96
|
+
golden_angle = np.pi * (3.0 - np.sqrt(5.0))
|
|
97
|
+
lon = (np.degrees(idx * golden_angle) + 180.0) % 360.0 - 180.0
|
|
98
|
+
|
|
99
|
+
if jitter_km > 0.0:
|
|
100
|
+
rng = np.random.default_rng(seed)
|
|
101
|
+
ang = (jitter_km * np.sqrt(rng.uniform(0.0, 1.0, size=n_global))) / (
|
|
102
|
+
EARTH_RADIUS_KM
|
|
103
|
+
)
|
|
104
|
+
bearing = rng.uniform(0.0, 2.0 * np.pi, size=n_global)
|
|
105
|
+
p1 = np.radians(lat)
|
|
106
|
+
l1 = np.radians(lon)
|
|
107
|
+
sin_p2 = np.sin(p1) * np.cos(ang) + np.cos(p1) * np.sin(ang) * np.cos(bearing)
|
|
108
|
+
p2 = np.arcsin(np.clip(sin_p2, -1.0, 1.0))
|
|
109
|
+
l2 = l1 + np.arctan2(
|
|
110
|
+
np.sin(bearing) * np.sin(ang) * np.cos(p1),
|
|
111
|
+
np.cos(ang) - np.sin(p1) * np.sin(p2),
|
|
112
|
+
)
|
|
113
|
+
lon = (np.degrees(l2) + 180.0) % 360.0 - 180.0
|
|
114
|
+
lat = np.degrees(p2)
|
|
115
|
+
|
|
116
|
+
mask = (lat >= lat_min) & (lat <= lat_max)
|
|
117
|
+
lon_sel = lon[mask]
|
|
118
|
+
lat_sel = lat[mask]
|
|
119
|
+
if lon_sel.shape[0] == 0:
|
|
120
|
+
raise ValueError(
|
|
121
|
+
f'No Fibonacci grid points fall within [{lat_min}, {lat_max}] '
|
|
122
|
+
f'at spacing_km={spacing_km}.'
|
|
123
|
+
)
|
|
124
|
+
return lon_sel.astype(np.float64), lat_sel.astype(np.float64)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def participation_ratio(
|
|
128
|
+
embeddings: NDArray[np.floating[Any]] | Tensor, *, standardize: bool = False
|
|
129
|
+
) -> float:
|
|
130
|
+
"""Compute the linear covariance participation ratio in float64.
|
|
131
|
+
|
|
132
|
+
Measures the effective number of variance-carrying linear directions from the
|
|
133
|
+
eigenvalues ``lambda_i`` of the centered sample covariance matrix:
|
|
134
|
+
|
|
135
|
+
``PR = (sum_i lambda_i)^2 / sum_i lambda_i^2``
|
|
136
|
+
|
|
137
|
+
This quantity equals ``k`` for ``k`` orthogonal equal-variance directions and is
|
|
138
|
+
invariant to orthogonal rotations and positive scalar rescaling when
|
|
139
|
+
``standardize=False``.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
embeddings: 2D array or PyTorch tensor of shape ``(N, D)`` with ``N >= 2``.
|
|
143
|
+
standardize: If ``True``, divide non-constant columns (``std > 1e-8``) by
|
|
144
|
+
their standard deviation before computing the spectrum (correlation-matrix
|
|
145
|
+
participation ratio).
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
Participation ratio as a Python float, or ``nan`` if all dimensions have zero
|
|
149
|
+
variance.
|
|
150
|
+
|
|
151
|
+
Raises:
|
|
152
|
+
ValueError: If *embeddings* is not a 2D array/tensor with at least 2 samples
|
|
153
|
+
and 1 feature.
|
|
154
|
+
"""
|
|
155
|
+
arr = _to_float64_2d(embeddings)
|
|
156
|
+
centered = arr - arr.mean(axis=0, keepdims=True)
|
|
157
|
+
if standardize:
|
|
158
|
+
sd = centered.std(axis=0)
|
|
159
|
+
active = sd > 1e-8
|
|
160
|
+
if not np.any(active):
|
|
161
|
+
return float('nan')
|
|
162
|
+
centered = centered[:, active] / sd[active]
|
|
163
|
+
|
|
164
|
+
n_samples, n_features = centered.shape
|
|
165
|
+
if n_samples >= n_features:
|
|
166
|
+
gram = (centered.T @ centered) / float(n_samples)
|
|
167
|
+
else:
|
|
168
|
+
gram = (centered @ centered.T) / float(n_samples)
|
|
169
|
+
eigvals = np.maximum(np.linalg.eigvalsh(gram), 0.0)
|
|
170
|
+
denom = float(np.sum(eigvals * eigvals))
|
|
171
|
+
if denom <= 0.0:
|
|
172
|
+
return float('nan')
|
|
173
|
+
total = float(np.sum(eigvals))
|
|
174
|
+
return (total * total) / denom
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def estimate_intrinsic_dimension(
|
|
178
|
+
embeddings: NDArray[np.floating[Any]] | Tensor,
|
|
179
|
+
*,
|
|
180
|
+
estimators: Sequence[str] = ('mle', 'twonn', 'mom', 'tle', 'fishers'),
|
|
181
|
+
k: int = 20,
|
|
182
|
+
conditional_number: float = 10.0,
|
|
183
|
+
standardize_pr: bool = False,
|
|
184
|
+
deduplicate: bool = True,
|
|
185
|
+
device: str | torch.device = 'cpu',
|
|
186
|
+
) -> dict[str, float]:
|
|
187
|
+
"""Estimate linear participation ratio and nonlinear manifold intrinsic dimension.
|
|
188
|
+
|
|
189
|
+
Always computes the pure-NumPy float64 covariance participation ratio (``'pr'``).
|
|
190
|
+
When *estimators* is non-empty, lazily imports ``torchid`` and evaluates each
|
|
191
|
+
requested estimator on float64 centered embeddings.
|
|
192
|
+
|
|
193
|
+
Args:
|
|
194
|
+
embeddings: 2D array or PyTorch tensor of shape ``(N, D)`` with ``N >= 2``.
|
|
195
|
+
estimators: Sequence of ``torchid`` estimator names to run. Supported values
|
|
196
|
+
are ``'mle'``, ``'twonn'``, ``'mom'``, ``'tle'``, and ``'fishers'``
|
|
197
|
+
(case-insensitive). Pass an empty sequence to compute only ``'pr'``
|
|
198
|
+
without importing ``torchid``.
|
|
199
|
+
k: Number of nearest neighbors for neighborhood-based estimators (``'mle'``,
|
|
200
|
+
``'mom'``, ``'tle'``).
|
|
201
|
+
conditional_number: Conditioning threshold passed to ``FisherS``.
|
|
202
|
+
standardize_pr: If ``True``, standardize non-constant features before
|
|
203
|
+
computing ``'pr'``.
|
|
204
|
+
deduplicate: If ``True``, drop exact duplicate rows prior to running
|
|
205
|
+
``torchid`` estimators so zero neighbor distances do not corrupt
|
|
206
|
+
distance-based estimates.
|
|
207
|
+
device: PyTorch device used for ``torchid`` estimation (default ``'cpu'``).
|
|
208
|
+
|
|
209
|
+
Returns:
|
|
210
|
+
Dictionary mapping ``'pr'`` and each requested lowercased estimator name to
|
|
211
|
+
its float dimension estimate.
|
|
212
|
+
|
|
213
|
+
Raises:
|
|
214
|
+
ValueError: If *embeddings*, *k*, *conditional_number*, or any estimator name
|
|
215
|
+
is invalid, or if too few unique rows remain for *k*-NN estimation.
|
|
216
|
+
DependencyNotFoundError: If *estimators* is non-empty and ``torchid`` is not
|
|
217
|
+
installed.
|
|
218
|
+
"""
|
|
219
|
+
arr = _to_float64_2d(embeddings)
|
|
220
|
+
if k < 2:
|
|
221
|
+
raise ValueError(f'k must be at least 2, got {k}.')
|
|
222
|
+
if not np.isfinite(conditional_number) or conditional_number <= 0.0:
|
|
223
|
+
raise ValueError(
|
|
224
|
+
f'conditional_number must be finite and positive, got {conditional_number}.'
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
normalized: list[str] = []
|
|
228
|
+
for name in estimators:
|
|
229
|
+
key = name.lower()
|
|
230
|
+
if key not in _ESTIMATOR_SET:
|
|
231
|
+
raise ValueError(
|
|
232
|
+
f'Unsupported estimator {name!r}. '
|
|
233
|
+
f'Expected one of {SUPPORTED_ESTIMATORS}.'
|
|
234
|
+
)
|
|
235
|
+
if key not in normalized:
|
|
236
|
+
normalized.append(key)
|
|
237
|
+
|
|
238
|
+
results: dict[str, float] = {
|
|
239
|
+
'pr': participation_ratio(arr, standardize=standardize_pr)
|
|
240
|
+
}
|
|
241
|
+
if not normalized:
|
|
242
|
+
return results
|
|
243
|
+
|
|
244
|
+
work = np.unique(arr, axis=0) if deduplicate else arr
|
|
245
|
+
min_rows = k + 1 if any(e in ('mle', 'mom', 'tle') for e in normalized) else 3
|
|
246
|
+
if work.shape[0] < min_rows:
|
|
247
|
+
raise ValueError(
|
|
248
|
+
f'Need at least {min_rows} unique embeddings for {normalized}, '
|
|
249
|
+
f'got {work.shape[0]}.'
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
torchid_mod = lazy_import('torchid')
|
|
253
|
+
resolved = resolve_device(device)
|
|
254
|
+
centered = work - work.mean(axis=0, keepdims=True)
|
|
255
|
+
tensor = torch.from_numpy(centered).to(
|
|
256
|
+
device=resolved, dtype=float64_dtype(resolved)
|
|
257
|
+
)
|
|
258
|
+
est_mod = torchid_mod.estimators
|
|
259
|
+
|
|
260
|
+
for key in normalized:
|
|
261
|
+
if key == 'mle':
|
|
262
|
+
est = est_mod.MLE().fit(tensor, n_neighbors=k)
|
|
263
|
+
elif key == 'twonn':
|
|
264
|
+
est = est_mod.TwoNN().fit(tensor)
|
|
265
|
+
elif key == 'mom':
|
|
266
|
+
est = est_mod.MOM(n_neighbors=k).fit(tensor)
|
|
267
|
+
elif key == 'tle':
|
|
268
|
+
est = est_mod.TLE(n_neighbors=k).fit(tensor)
|
|
269
|
+
else:
|
|
270
|
+
est = est_mod.FisherS(conditional_number=conditional_number).fit(tensor)
|
|
271
|
+
results[key] = float(est.dimension_)
|
|
272
|
+
|
|
273
|
+
return results
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def analyze_intrinsic_dimension(
|
|
277
|
+
encoder: 'LocationEncoder',
|
|
278
|
+
lon: NDArray[np.floating[Any]],
|
|
279
|
+
lat: NDArray[np.floating[Any]],
|
|
280
|
+
*,
|
|
281
|
+
year: NDArray[np.floating[Any]] | None = None,
|
|
282
|
+
month: NDArray[np.floating[Any]] | None = None,
|
|
283
|
+
estimators: Sequence[str] = ('mle', 'twonn', 'mom', 'tle', 'fishers'),
|
|
284
|
+
k: int = 20,
|
|
285
|
+
conditional_number: float = 10.0,
|
|
286
|
+
standardize_pr: bool = False,
|
|
287
|
+
deduplicate: bool = True,
|
|
288
|
+
device: str | torch.device = 'cpu',
|
|
289
|
+
) -> dict[str, float]:
|
|
290
|
+
"""Encode geographic coordinates and estimate intrinsic dimension and PR.
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
encoder: Instantiated :class:`~neuralftw.models.LocationEncoder`.
|
|
294
|
+
lon: 1D array of longitudes in degrees.
|
|
295
|
+
lat: 1D array of latitudes in degrees.
|
|
296
|
+
year: Optional 1D array of observation years matching *lon* and *lat*.
|
|
297
|
+
month: Optional 1D array of observation months matching *lon* and *lat*.
|
|
298
|
+
estimators: Sequence of ``torchid`` estimator names to run alongside ``'pr'``.
|
|
299
|
+
k: Number of nearest neighbors for neighborhood-based estimators.
|
|
300
|
+
conditional_number: Conditioning threshold passed to ``FisherS``.
|
|
301
|
+
standardize_pr: If ``True``, standardize non-constant features before
|
|
302
|
+
computing ``'pr'``.
|
|
303
|
+
deduplicate: If ``True``, remove exact duplicate embedding rows before
|
|
304
|
+
estimation.
|
|
305
|
+
device: PyTorch device used for ``torchid`` estimation (default ``'cpu'``).
|
|
306
|
+
|
|
307
|
+
Returns:
|
|
308
|
+
Dictionary containing ``'pr'``, each requested estimator value,
|
|
309
|
+
``'n_points'``, and ``'embed_dim'``.
|
|
310
|
+
|
|
311
|
+
Raises:
|
|
312
|
+
ValueError: If *lon* and *lat* are invalid or fewer than 2 points are given.
|
|
313
|
+
DependencyNotFoundError: If *estimators* is non-empty and ``torchid`` is not
|
|
314
|
+
installed.
|
|
315
|
+
"""
|
|
316
|
+
lon_arr = np.asarray(lon, dtype=np.float64)
|
|
317
|
+
lat_arr = np.asarray(lat, dtype=np.float64)
|
|
318
|
+
if lon_arr.ndim != 1 or lat_arr.ndim != 1 or lon_arr.shape != lat_arr.shape:
|
|
319
|
+
raise ValueError('lon and lat must be 1D arrays of equal length.')
|
|
320
|
+
n_pts = lon_arr.shape[0]
|
|
321
|
+
if n_pts < 2:
|
|
322
|
+
raise ValueError('lon and lat must contain at least 2 points.')
|
|
323
|
+
|
|
324
|
+
year_arr = None if year is None else np.asarray(year, dtype=np.float64)
|
|
325
|
+
month_arr = None if month is None else np.asarray(month, dtype=np.float64)
|
|
326
|
+
emb = encoder.encode(lon_arr, lat_arr, year=year_arr, month=month_arr)
|
|
327
|
+
scores = estimate_intrinsic_dimension(
|
|
328
|
+
emb,
|
|
329
|
+
estimators=estimators,
|
|
330
|
+
k=k,
|
|
331
|
+
conditional_number=conditional_number,
|
|
332
|
+
standardize_pr=standardize_pr,
|
|
333
|
+
deduplicate=deduplicate,
|
|
334
|
+
device=device,
|
|
335
|
+
)
|
|
336
|
+
scores['n_points'] = float(n_pts)
|
|
337
|
+
scores['embed_dim'] = float(emb.shape[1])
|
|
338
|
+
return scores
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
__all__ = (
|
|
342
|
+
'SUPPORTED_ESTIMATORS',
|
|
343
|
+
'analyze_intrinsic_dimension',
|
|
344
|
+
'estimate_intrinsic_dimension',
|
|
345
|
+
'generate_equal_area_grid',
|
|
346
|
+
'participation_ratio',
|
|
347
|
+
)
|