nestsar 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.
- nestsar/__init__.py +13 -0
- nestsar/_nest.py +73 -0
- nestsar/_sample.py +114 -0
- nestsar-0.1.0.dist-info/METADATA +52 -0
- nestsar-0.1.0.dist-info/RECORD +7 -0
- nestsar-0.1.0.dist-info/WHEEL +4 -0
- nestsar-0.1.0.dist-info/licenses/LICENSE +21 -0
nestsar/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Nested species-area relationship datasets from point observations."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from nestsar._nest import Nest, random_nest
|
|
6
|
+
from nestsar._sample import Sample, hull_area
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
__version__ = version("nestsar")
|
|
10
|
+
except PackageNotFoundError: # running from a source tree without an install
|
|
11
|
+
__version__ = "0.0.0"
|
|
12
|
+
|
|
13
|
+
__all__ = ["Nest", "Sample", "__version__", "hull_area", "random_nest"]
|
nestsar/_nest.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Nested samples: a sequence of ever-smaller subsets of one sample."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from nestsar._sample import Sample, hull_area
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Nest:
|
|
15
|
+
"""A nested sequence of sub-samples of one :class:`Sample`.
|
|
16
|
+
|
|
17
|
+
``steps[i]`` holds the row indices into ``sample.points`` that remain at
|
|
18
|
+
step ``i``; ``steps[0]`` is every point and each later step is a subset
|
|
19
|
+
of the one before. Strategies differ only in which point they drop next.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
sample: Sample
|
|
23
|
+
steps: tuple[np.ndarray, ...]
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def n_steps(self) -> int:
|
|
27
|
+
return len(self.steps)
|
|
28
|
+
|
|
29
|
+
def sample_at(self, step: int) -> Sample:
|
|
30
|
+
return self.sample.subset(self.steps[step])
|
|
31
|
+
|
|
32
|
+
def to_frame(self) -> pd.DataFrame:
|
|
33
|
+
"""One row per step: ``step``, ``n_points``, ``area``, ``species``."""
|
|
34
|
+
points = self.sample.points
|
|
35
|
+
species = self.sample.data["species"].to_numpy()
|
|
36
|
+
keys = pd.MultiIndex.from_frame(self.sample.data[["lon", "lat"]])
|
|
37
|
+
rows = []
|
|
38
|
+
for i, idx in enumerate(self.steps):
|
|
39
|
+
kept = points[idx]
|
|
40
|
+
mask = keys.isin([tuple(p) for p in kept])
|
|
41
|
+
rows.append(
|
|
42
|
+
{
|
|
43
|
+
"step": i,
|
|
44
|
+
"n_points": len(idx),
|
|
45
|
+
"area": hull_area(kept),
|
|
46
|
+
"species": int(len(np.unique(species[mask]))),
|
|
47
|
+
}
|
|
48
|
+
)
|
|
49
|
+
return pd.DataFrame(rows)
|
|
50
|
+
|
|
51
|
+
def sar_data(self) -> pd.DataFrame:
|
|
52
|
+
"""``area`` and ``species`` columns for ``sars``, dropping zero-area steps."""
|
|
53
|
+
frame = self.to_frame()
|
|
54
|
+
return frame.loc[frame["area"] > 0, ["area", "species"]].reset_index(drop=True)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def random_nest(sample: Sample, min_points: int = 3, seed: int | None = None) -> Nest:
|
|
58
|
+
"""Nest a sample by removing one point at a time, uniformly at random.
|
|
59
|
+
|
|
60
|
+
The baseline every other strategy is compared against. Stops when
|
|
61
|
+
``min_points`` points remain.
|
|
62
|
+
"""
|
|
63
|
+
n = sample.n_points
|
|
64
|
+
if n < min_points:
|
|
65
|
+
raise ValueError(f"Sample has {n} points; need at least {min_points}")
|
|
66
|
+
rng = np.random.default_rng(seed)
|
|
67
|
+
remaining = np.arange(n)
|
|
68
|
+
steps = [remaining.copy()]
|
|
69
|
+
while len(remaining) > min_points:
|
|
70
|
+
drop = rng.integers(len(remaining))
|
|
71
|
+
remaining = np.delete(remaining, drop)
|
|
72
|
+
steps.append(remaining.copy())
|
|
73
|
+
return Nest(sample=sample, steps=tuple(steps))
|
nestsar/_sample.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Point observations of species, the input every nesting strategy starts from."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
from shapely.geometry import MultiPoint
|
|
12
|
+
|
|
13
|
+
COLUMNS = ("species", "lon", "lat")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _validate(df: pd.DataFrame) -> pd.DataFrame:
|
|
17
|
+
missing = [c for c in COLUMNS if c not in df.columns]
|
|
18
|
+
if missing:
|
|
19
|
+
raise KeyError(f"Missing column(s): {missing}. Need {list(COLUMNS)}.")
|
|
20
|
+
out = df.loc[:, list(COLUMNS)].reset_index(drop=True)
|
|
21
|
+
if len(out) == 0:
|
|
22
|
+
raise ValueError("Sample has no observations")
|
|
23
|
+
if out["species"].isna().any():
|
|
24
|
+
raise ValueError("species contains missing values")
|
|
25
|
+
lon = pd.to_numeric(out["lon"], errors="coerce")
|
|
26
|
+
lat = pd.to_numeric(out["lat"], errors="coerce")
|
|
27
|
+
if lon.isna().any() or lat.isna().any():
|
|
28
|
+
raise ValueError("lon and lat must be numeric with no missing values")
|
|
29
|
+
if ((lat < -90) | (lat > 90)).any():
|
|
30
|
+
raise ValueError("lat must be within [-90, 90]")
|
|
31
|
+
if ((lon < -180) | (lon > 180)).any():
|
|
32
|
+
raise ValueError("lon must be within [-180, 180]")
|
|
33
|
+
out["lon"] = lon.astype(float)
|
|
34
|
+
out["lat"] = lat.astype(float)
|
|
35
|
+
out["species"] = out["species"].astype(str)
|
|
36
|
+
return out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Sample:
|
|
41
|
+
"""A set of georeferenced species observations.
|
|
42
|
+
|
|
43
|
+
Each row of ``data`` is one observation with columns ``species``, ``lon``,
|
|
44
|
+
and ``lat`` (decimal degrees). Several observations may share a point.
|
|
45
|
+
|
|
46
|
+
Build one with :meth:`from_df` or :meth:`from_csv`.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
data: pd.DataFrame
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def from_df(
|
|
53
|
+
cls,
|
|
54
|
+
df: pd.DataFrame,
|
|
55
|
+
species_col: str = "species",
|
|
56
|
+
lon_col: str = "lon",
|
|
57
|
+
lat_col: str = "lat",
|
|
58
|
+
) -> Sample:
|
|
59
|
+
"""Build a sample from a DataFrame, renaming columns as needed."""
|
|
60
|
+
renamed = df.rename(columns={species_col: "species", lon_col: "lon", lat_col: "lat"})
|
|
61
|
+
return cls(_validate(renamed))
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def from_csv(cls, path: str | Path, **kwargs: str) -> Sample:
|
|
65
|
+
"""Build a sample from a CSV file; ``kwargs`` are the column names for :meth:`from_df`."""
|
|
66
|
+
return cls.from_df(pd.read_csv(path), **kwargs)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def n_observations(self) -> int:
|
|
70
|
+
return len(self.data)
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def n_species(self) -> int:
|
|
74
|
+
return int(self.data["species"].nunique())
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def points(self) -> np.ndarray:
|
|
78
|
+
"""Distinct (lon, lat) points, shape (n_points, 2), in first-seen order."""
|
|
79
|
+
return self.data[["lon", "lat"]].drop_duplicates().to_numpy(dtype=float)
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def n_points(self) -> int:
|
|
83
|
+
return len(self.points)
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def area(self) -> float:
|
|
87
|
+
"""Area of the convex hull of the points, in square degrees.
|
|
88
|
+
|
|
89
|
+
Zero when fewer than three distinct, non-collinear points remain.
|
|
90
|
+
Square degrees are not a physical area; they are fine for ordering
|
|
91
|
+
nested samples and for fitting within one sample, which is what the
|
|
92
|
+
nesting strategies need. A projected area is planned.
|
|
93
|
+
"""
|
|
94
|
+
return hull_area(self.points)
|
|
95
|
+
|
|
96
|
+
def subset(self, point_indices: Sequence[int]) -> Sample:
|
|
97
|
+
"""The observations at the given rows of :attr:`points`."""
|
|
98
|
+
keep = self.points[list(point_indices)]
|
|
99
|
+
mask = pd.MultiIndex.from_frame(self.data[["lon", "lat"]]).isin([tuple(p) for p in keep])
|
|
100
|
+
return Sample(self.data.loc[mask].reset_index(drop=True))
|
|
101
|
+
|
|
102
|
+
def __repr__(self) -> str:
|
|
103
|
+
return (
|
|
104
|
+
f"Sample(n_observations={self.n_observations}, n_points={self.n_points}, "
|
|
105
|
+
f"n_species={self.n_species}, area={self.area:.6g})"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def hull_area(points: np.ndarray) -> float:
|
|
110
|
+
"""Convex hull area of an (n, 2) array of (lon, lat) points, in square degrees."""
|
|
111
|
+
pts = np.asarray(points, dtype=float)
|
|
112
|
+
if len(pts) < 3:
|
|
113
|
+
return 0.0
|
|
114
|
+
return float(MultiPoint([tuple(p) for p in pts]).convex_hull.area)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: nestsar
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Nested species-area relationship datasets from point observations
|
|
5
|
+
Project-URL: Homepage, https://github.com/jmcmeen/nestsar
|
|
6
|
+
Project-URL: Source, https://github.com/jmcmeen/nestsar
|
|
7
|
+
Project-URL: Changelog, https://github.com/jmcmeen/nestsar/blob/main/CHANGELOG.md
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/jmcmeen/nestsar/issues
|
|
9
|
+
Author-email: John McMeen <johnmcmeen@gmail.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Requires-Dist: numpy>=1.22
|
|
23
|
+
Requires-Dist: pandas>=1.4
|
|
24
|
+
Requires-Dist: sars>=0.7.10
|
|
25
|
+
Requires-Dist: shapely>=2.0
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest-cov; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
29
|
+
Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# nestsar
|
|
33
|
+
|
|
34
|
+
Nested species-area relationship datasets from point observations. Build a
|
|
35
|
+
sequence of nested sub-samples from georeferenced species records and hand
|
|
36
|
+
the resulting area and richness table to [sars](https://pypi.org/project/sars/)
|
|
37
|
+
for curve fitting.
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import nestsar, sars
|
|
41
|
+
|
|
42
|
+
sample = nestsar.Sample.from_csv("observations.csv") # species, lon, lat
|
|
43
|
+
nest = nestsar.random_nest(sample, seed=0)
|
|
44
|
+
fit = sars.sar_power(nest.sar_data())
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Development
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
make install # create .venv with dev tooling
|
|
51
|
+
make check # lint, format check, tests
|
|
52
|
+
```
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
nestsar/__init__.py,sha256=YpLZl-RjXYa4cTtPEqZX-LyKhcj_sKhhhta_hp-U6Zo,446
|
|
2
|
+
nestsar/_nest.py,sha256=WJSCrkA5IBhWyCCt_gybdgZipOwonsubFzdCNqUDVH8,2499
|
|
3
|
+
nestsar/_sample.py,sha256=1Twwsy0UyY2CKxxrz3ENkp8C1JfkaPeFifkx1gyqewE,4068
|
|
4
|
+
nestsar-0.1.0.dist-info/METADATA,sha256=6NAA5QD9JwJTLc9zjqBm_5QRKY_sWbl8KxRmqRl_inM,1820
|
|
5
|
+
nestsar-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
6
|
+
nestsar-0.1.0.dist-info/licenses/LICENSE,sha256=qzmCAeakObqZTPFNxWt_xwcfdG7J_3DWvuq_M9UnjFI,1068
|
|
7
|
+
nestsar-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 John McMeen
|
|
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.
|