OccuPYcy 0.0.1.dev45429274732__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.

Potentially problematic release.


This version of OccuPYcy might be problematic. Click here for more details.

Files changed (38) hide show
  1. occupycy-0.0.1.dev45429274732/LICENSE +21 -0
  2. occupycy-0.0.1.dev45429274732/PKG-INFO +294 -0
  3. occupycy-0.0.1.dev45429274732/README.md +252 -0
  4. occupycy-0.0.1.dev45429274732/pyproject.toml +34 -0
  5. occupycy-0.0.1.dev45429274732/setup.cfg +4 -0
  6. occupycy-0.0.1.dev45429274732/src/OccuPYcy.egg-info/PKG-INFO +294 -0
  7. occupycy-0.0.1.dev45429274732/src/OccuPYcy.egg-info/SOURCES.txt +36 -0
  8. occupycy-0.0.1.dev45429274732/src/OccuPYcy.egg-info/dependency_links.txt +1 -0
  9. occupycy-0.0.1.dev45429274732/src/OccuPYcy.egg-info/requires.txt +10 -0
  10. occupycy-0.0.1.dev45429274732/src/OccuPYcy.egg-info/top_level.txt +1 -0
  11. occupycy-0.0.1.dev45429274732/src/occupycy/__init__.py +7 -0
  12. occupycy-0.0.1.dev45429274732/src/occupycy/data/__init__.py +12 -0
  13. occupycy-0.0.1.dev45429274732/src/occupycy/data/core.py +730 -0
  14. occupycy-0.0.1.dev45429274732/src/occupycy/data/from_dataframe.py +132 -0
  15. occupycy-0.0.1.dev45429274732/src/occupycy/data/simulate_data.py +495 -0
  16. occupycy-0.0.1.dev45429274732/src/occupycy/fit/__init__.py +12 -0
  17. occupycy-0.0.1.dev45429274732/src/occupycy/fit/checkpoints.py +96 -0
  18. occupycy-0.0.1.dev45429274732/src/occupycy/fit/cross_validation.py +571 -0
  19. occupycy-0.0.1.dev45429274732/src/occupycy/fit/early_stopper.py +47 -0
  20. occupycy-0.0.1.dev45429274732/src/occupycy/fit/formula.py +103 -0
  21. occupycy-0.0.1.dev45429274732/src/occupycy/fit/lbfgs.py +294 -0
  22. occupycy-0.0.1.dev45429274732/src/occupycy/fit/naive_estimator.py +74 -0
  23. occupycy-0.0.1.dev45429274732/src/occupycy/fit/result.py +46 -0
  24. occupycy-0.0.1.dev45429274732/src/occupycy/fit/sgd_like.py +553 -0
  25. occupycy-0.0.1.dev45429274732/src/occupycy/likelihood/__init__.py +4 -0
  26. occupycy-0.0.1.dev45429274732/src/occupycy/likelihood/penalty.py +104 -0
  27. occupycy-0.0.1.dev45429274732/src/occupycy/likelihood/single_season_multi_species.py +403 -0
  28. occupycy-0.0.1.dev45429274732/src/occupycy/models/__init__.py +15 -0
  29. occupycy-0.0.1.dev45429274732/src/occupycy/models/base.py +159 -0
  30. occupycy-0.0.1.dev45429274732/src/occupycy/models/constant.py +102 -0
  31. occupycy-0.0.1.dev45429274732/src/occupycy/models/linear.py +49 -0
  32. occupycy-0.0.1.dev45429274732/src/occupycy/models/linear_mlp.py +140 -0
  33. occupycy-0.0.1.dev45429274732/src/occupycy/models/mlp.py +144 -0
  34. occupycy-0.0.1.dev45429274732/src/occupycy/models/qualitative_linear_mlp.py +187 -0
  35. occupycy-0.0.1.dev45429274732/tests/test_fit_lbfgs_full_batch.py +36 -0
  36. occupycy-0.0.1.dev45429274732/tests/test_import.py +9 -0
  37. occupycy-0.0.1.dev45429274732/tests/test_likelihoods.py +119 -0
  38. occupycy-0.0.1.dev45429274732/tests/test_occudata.py +208 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Raphaël Benerradi
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.
@@ -0,0 +1,294 @@
1
+ Metadata-Version: 2.4
2
+ Name: OccuPYcy
3
+ Version: 0.0.1.dev45429274732
4
+ Summary: Occupancy modeling with maximum likelihood estimation in Python
5
+ Author: Raphaël Benerradi
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Raphaël Benerradi
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: Documentation, https://raphbnrd.github.io/OccuPYcy/
28
+ Classifier: License :: OSI Approved :: MIT License
29
+ Requires-Python: >=3.10
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Requires-Dist: ipykernel>=7.0
33
+ Requires-Dist: matplotlib>=3.0
34
+ Requires-Dist: pandas>=2.0
35
+ Requires-Dist: polars>=1.0
36
+ Requires-Dist: numpy>=2.0
37
+ Requires-Dist: torch>=2.0
38
+ Requires-Dist: tqdm>=4.0
39
+ Provides-Extra: dev
40
+ Requires-Dist: pytest>=7; extra == "dev"
41
+ Dynamic: license-file
42
+
43
+ <p align="center">
44
+ <img src="assets/logo_cropped.png" width="70%" alt="OccuPYcy logo">
45
+ </p>
46
+ <!-- Colors:
47
+ dark green = #2B432A ; biege = #FEF8F5 ; orange = #EF702D ;
48
+ yellow = #FBB742 ; light green = #7AA92F
49
+ -->
50
+
51
+ <!-- [![PyPI](https://img.shields.io/pypi/v/OccuPYcy.svg)](https://pypi.org/project/OccuPYcy/) -->
52
+ <!-- ![Python](https://img.shields.io/pypi/pyversions/OccuPYcy) -->
53
+ [![docs](https://img.shields.io/badge/docs-latest-blue)](https://raphbnrd.github.io/OccuPYcy/)
54
+ ![License](https://img.shields.io/github/license/RaphBnrd/OccuPYcy)
55
+ ![GitHub last commit](https://img.shields.io/github/last-commit/RaphBnrd/OccuPYcy)
56
+ <!-- [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.XXXXXXX.svg)](https://doi.org/10.5281/zenodo.XXXXXXX) -->
57
+
58
+
59
+ **OccuPYcy** is an open-source <strong><ins>PY</ins></strong>thon package for site-<strong><ins>occu</ins></strong>pan<strong><ins>cy</ins></strong> modeling at scale. OccuPYcy provides tools for flexible, high-performance fitting of single or multi-species occupancy models using maximum likelihood with (stochastic) gradient-based optimization in [PyTorch](https://pytorch.org/). It is designed for scalability, deep model expressivity, and robust application to massive, uneven datasets—such as those from citizen science.
60
+
61
+ ## Table of Contents
62
+ - [Features](#-features)
63
+ - [Installation](#-installation)
64
+ - [Quick Start Example](#%EF%B8%8F-quick-start-example)
65
+ - [Site-Occupancy Framework](#-site-occupancy-framework)
66
+ - [How to Cite](#-how-to-cite)
67
+ - [Contributing & Collaboration](#-contributing--collaboration)
68
+ - [License](#-license)
69
+ - [Project Links](#-project-links)
70
+
71
+ # ✨ Features
72
+
73
+ - **Flexible Model Definitions:** Use linear, non-linear, or neural networks for occupancy and detection probabilities via PyTorch modules.
74
+ - **Extensible:** Define custom architectures and features for modern site-occupancy modeling.
75
+ - **Supports Large, Heterogeneous Datasets:** Memory mapping and efficient batching for millions of observations with highly uneven visits per site. Suited for citizen science data with variable sampling and detection effort.
76
+ - **Multiple Optimizers:** LBFGS, SGD, Adam, and other first- and second-order optimizers.
77
+ - **Penalized Estimation:** Easily apply L1/L2 regularization and other penalties.
78
+ - **Open Source:** code available on GitHub under the MIT License, soon on PyPI. *A scientific publication describing and applying the method is in preparation.*
79
+
80
+ # 📦 Installation
81
+
82
+ We recommend using [uv](https://docs.astral.sh/uv/) for reproducible local development.
83
+ *Python ≥3.10 and PyTorch ≥2.0 recommended.*
84
+
85
+
86
+ ## Using OccuPYcy in another project
87
+
88
+ You can install OccuPYcy as a dependency in your project either from GitHub or from a local clone of the repository.
89
+
90
+ **From PyPI:** *(coming soon🤞)*
91
+
92
+ **From GitHub:**
93
+ Navigate to the repository on GitHub, create and activate your environment, and run:
94
+
95
+ ```bash
96
+ uv pip install git+https://github.com/RaphBnrd/OccuPYcy.git
97
+ ```
98
+ or if not using `uv`:
99
+ ```bash
100
+ pip install git+https://github.com/RaphBnrd/OccuPYcy.git
101
+ ```
102
+
103
+ **From the repository cloned on your machine:**
104
+ After cloning OccuPYcy (see below), navigate to the repository root of your project, and install it in editable mode with:
105
+ ```bash
106
+ pip install -e /local/path/to/the/repository/OccuPYcy
107
+ ```
108
+
109
+ ## Source code download
110
+
111
+ To download the source code and install the dependencies, you should first clone the repository, using `git clone https://github.com/RaphBnrd/OccuPYcy.git` at the location of your choice. You can also download the code as a zip or clone using SSH.
112
+
113
+ Then, if you want to setup a local development environment in the repository, move to the repository root (`cd occupycy`) and you can use `uv` or `venv` to create a virtual environment and install the dependencies.
114
+
115
+ ```bash
116
+ uv venv
117
+ uv pip install -e ".[dev]"
118
+ uv run pytest -q
119
+ ```
120
+
121
+ If not using `uv`:
122
+ ```bash
123
+ python3 -m venv .venv
124
+ source .venv/bin/activate
125
+ pip install -U pip
126
+ pip install -e ".[dev]"
127
+ pytest -q
128
+ ```
129
+
130
+ # ⚡️ Quick Start Example
131
+
132
+ Below is an example fitting a Multi-Layer Perceptron (MLP) occupancy model on simulated data.
133
+ Other examples are available in the [examples/](examples/) folder. More details on the code below are available in the notebook [01-fitting_on_simulated_data.ipynb](examples/01-fitting_on_simulated_data.ipynb).
134
+
135
+
136
+ ```python
137
+ import torch
138
+ import occupycy
139
+
140
+ seed = 1
141
+ torch.manual_seed(seed)
142
+ device = torch.device("cpu")
143
+
144
+ # 1. Simulate data (arbitrary non-linear functions)
145
+ def true_f_psi(X_psi): # here X_psi of shape (n_sites, n_cov_psi=2)
146
+ return torch.sigmoid(
147
+ - 0.5 * torch.cos(X_psi[:,0]) - 0.5 * (X_psi[:,1] ** 2)
148
+ ).unsqueeze(1)
149
+ def true_f_d(X_d): # here X_d of shape (n_total_visits, n_cov_d=1)
150
+ return torch.sigmoid(
151
+ torch.tanh(5 * X_d[:,0]) - torch.cos(X_d[:,0])
152
+ ).unsqueeze(1)
153
+
154
+ y, visit_site_ids, site_ids_in_X_psi, X_psi, X_d, true_z = \
155
+ occupycy.data.simulate_non_linear(
156
+ n_sites=5000,
157
+ n_total_visits_max=int(1e4),
158
+ n_cov_psi=2,
159
+ n_cov_d=1,
160
+ f_effort = lambda x: torch.distributions.LogNormal(0, 3).sample((x.shape[0],)),
161
+ f_psi=true_f_psi,
162
+ f_d=true_f_d,
163
+ seed=seed,
164
+ plot_summary=True,
165
+ verbose=True
166
+ )
167
+
168
+ # 2. Build OccuData (YOU CAN REPLACE THIS WITH YOUR OWN DATA)
169
+ # y: tensor of shape (n_total_visits, n_species) with the detection/non-detection data
170
+ # visit_site_ids: list of length (n_total_visits,) with the site id of each visit
171
+ # site_ids_in_X_psi: list of length (n_sites,) with the site ids of the rows in X_psi
172
+ # X_psi: tensor of shape (n_sites, n_cov_psi) with the covariates for occupancy
173
+ # X_d: tensor of shape (n_total_visits, n_cov_d) with the covariates for detection
174
+ data = occupycy.data.OccuData(
175
+ y=y,
176
+ visit_site_ids=visit_site_ids,
177
+ X_psi=X_psi,
178
+ X_d=X_d,
179
+ site_ids_in_X_psi=site_ids_in_X_psi
180
+ )
181
+
182
+ # 3. Define an MLP-MLP model
183
+ # (other architectures are possible, including custom ones)
184
+ model = occupycy.models.MLPOccuModel(
185
+ n_species=1,
186
+ n_cov_psi=data.X_psi.shape[1],
187
+ n_cov_d=data.X_d.shape[1],
188
+ hidden_dims_psi=[256, 256], hidden_dims_d=[256, 256],
189
+ activation_fn_psi=torch.nn.ReLU, activation_fn_d=torch.nn.ReLU
190
+ )
191
+
192
+ # 4. Fit the model with Adam (LBFGS is also available)
193
+ res = occupycy.fit.fit_sgd_like(
194
+ data, # OccuData object
195
+ model, # OccuModel object
196
+ n_epochs=1000, # maximum number of epochs
197
+ val_fraction=0.15, # fraction of sites to use for validation
198
+ batch_size=512, # number of sites per batch
199
+ optimizer_psi_cls=torch.optim.Adam, # optimizer class for the occupancy part
200
+ optimizer_d_cls=torch.optim.Adam, # optimizer class for the detection part
201
+ lr_psi=1e-3, # learning rate for the occupancy part
202
+ lr_d=1e-3, # learning rate for the detection part
203
+ patience_early_stopping=100,
204
+ patience_reduceLROnPlateau=20,
205
+ device=device
206
+ )
207
+
208
+ # 5. Get the predictions
209
+ with torch.no_grad():
210
+ pred_logit_psi, pred_logit_d = model.forward_logits(X_psi=X_psi.to(device), X_d=X_d.to(device))
211
+
212
+ ```
213
+
214
+ NB: The [examples](/examples) are numbered in the order of increasing complexity (and readability...).
215
+
216
+ # 🌱 Site-Occupancy Framework
217
+
218
+ **Site-occupancy models** estimate the probability that a species is present at a given site while accounting for imperfect detection during surveys ([MacKenzie et al. (2002)](https://doi.org/10.1890/0012-9658(2002)083[2248:ESORWD]2.0.CO;2)). This hierarchical approach is especially powerful for citizen science data, where both **detection bias** and **sampling bias** are common due to uneven survey effort and heterogeneous detection conditions.
219
+
220
+
221
+ <p align="center">
222
+ <img src="assets/opportunistic_PO_data-diagram.png" width="80%" alt="Illustration of citizen science data bias">
223
+ </p>
224
+
225
+ <p align="center">
226
+ <img src="assets/occupancy-diagram.png" width="60%" alt="Illustration of occupancy modeling framework">
227
+ </p>
228
+
229
+ <p align="center">
230
+ <sub>
231
+ <i>
232
+ Icon credits: icons from the figure sourced from Flaticon, created by Nikita Golubev, Freepik, Pixel Perfect, and surang.
233
+ </i>
234
+ </sub>
235
+ </p>
236
+
237
+ Mathematically:
238
+
239
+ - $Z_s \sim \mathrm{Bernoulli}(\psi_s)$
240
+ The latent occupancy state ($Z_s$) for site $s$.
241
+ - $Y_v \mid Z_{s(v)} \sim \mathrm{Bernoulli}(d_v \cdot Z_{s(v)})$
242
+ The detection ($Y_v$) during visit $v$, conditional on the site's true state $Z_{s(v)}$.
243
+
244
+ The probabilities $\psi_s$ (occupancy) and $d_v$ (detection) are flexible, parametric functions of covariates (e.g., spatial, temporal, observer info):
245
+
246
+ - **Classically**, $\psi_s$ and $d_v$ are modeled as sigmoid-linear functions (logistic regression).
247
+ - **With OccuPYcy**, these can be *any* differentiable model; in particular, a sigmoid transformation of an arbitrary PyTorch module, such as a neural network.
248
+
249
+ Then, for $K$ independent species, the likelihood of the observed data is:
250
+
251
+ <p align="center">
252
+ <img src="assets/NLL_equation.png" width="90%" alt="Negative log-likelihood equation">
253
+ </p>
254
+
255
+ where:
256
+
257
+ - $\mathcal{S}_{1,k}$ is the set of sites with at least one detection for species $k$
258
+ - $\mathcal{S}_{0,k}$ is the set of sites with no detection for species $k$
259
+ - $\mathcal{V}_s$ is the set of visits to site $s$
260
+
261
+ This likelihood is optimized with respect to the parameters $\theta_\psi$ and $\theta_d$ — the parameters of the occupancy and detection models — using (stochastic) gradient-based methods.
262
+
263
+ > **Example:**
264
+ > &nbsp;&nbsp; $\psi_s = \mathrm{sigmoid}\left(f_{\theta_\psi}(X_s)\right)$
265
+ > &nbsp;&nbsp; $d_v = \mathrm{sigmoid}\left(g_{\theta_d}(U_v)\right)$
266
+ > where $f_{\theta_\psi}$ and $g_{\theta_d}$ can be linear, MLP, or any neural network.
267
+
268
+ **Applications:**
269
+
270
+ - Well-suited for massive, opportunistic presence-only datasets, such as citizen science records (sites = spatial grid, visits = observations).
271
+ - Corrects for both **detection** and **sampling** bias, enabling robust estimation of species distributions and trends.
272
+ - Models uneven non-linear sampling and detection: complex and heterogeneous survey effort, or detection/reporting ability or willingness across space, time, and observers.
273
+ - Handles multi-species data with shared covariates and common embedding.
274
+
275
+ # 📖 How to Cite
276
+
277
+ *Manuscript in preparation*
278
+
279
+ # 🤝 Contributing & Collaboration
280
+
281
+ We welcome not only code contributions and bug reports, but also scientific collaborations — especially in ecology, citizen science, machine learning, and statistics! If you'd like to collaborate or have scientific ideas to discuss, feel free to [email me](mailto:raphael.benerradi@inria.fr) or open an [issue](https://github.com/RaphBnrd/OccuPYcy/issues).
282
+
283
+ Standard code contributions (pull requests, feature requests, etc.) are also welcome.
284
+
285
+ # 📜 License
286
+
287
+ OccuPYcy is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
288
+
289
+ # 🔗 Project Links
290
+
291
+ - [Source code on GitHub](https://github.com/RaphBnrd/OccuPYcy)
292
+ - [Example usage](examples/) in the repository
293
+ - [PhD project](https://raphbnrd.github.io/projects/mapping_plant_species/) section on my website
294
+ - For questions, contact [raphael.benerradi@inria.fr](mailto:raphael.benerradi@inria.fr)
@@ -0,0 +1,252 @@
1
+ <p align="center">
2
+ <img src="assets/logo_cropped.png" width="70%" alt="OccuPYcy logo">
3
+ </p>
4
+ <!-- Colors:
5
+ dark green = #2B432A ; biege = #FEF8F5 ; orange = #EF702D ;
6
+ yellow = #FBB742 ; light green = #7AA92F
7
+ -->
8
+
9
+ <!-- [![PyPI](https://img.shields.io/pypi/v/OccuPYcy.svg)](https://pypi.org/project/OccuPYcy/) -->
10
+ <!-- ![Python](https://img.shields.io/pypi/pyversions/OccuPYcy) -->
11
+ [![docs](https://img.shields.io/badge/docs-latest-blue)](https://raphbnrd.github.io/OccuPYcy/)
12
+ ![License](https://img.shields.io/github/license/RaphBnrd/OccuPYcy)
13
+ ![GitHub last commit](https://img.shields.io/github/last-commit/RaphBnrd/OccuPYcy)
14
+ <!-- [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.XXXXXXX.svg)](https://doi.org/10.5281/zenodo.XXXXXXX) -->
15
+
16
+
17
+ **OccuPYcy** is an open-source <strong><ins>PY</ins></strong>thon package for site-<strong><ins>occu</ins></strong>pan<strong><ins>cy</ins></strong> modeling at scale. OccuPYcy provides tools for flexible, high-performance fitting of single or multi-species occupancy models using maximum likelihood with (stochastic) gradient-based optimization in [PyTorch](https://pytorch.org/). It is designed for scalability, deep model expressivity, and robust application to massive, uneven datasets—such as those from citizen science.
18
+
19
+ ## Table of Contents
20
+ - [Features](#-features)
21
+ - [Installation](#-installation)
22
+ - [Quick Start Example](#%EF%B8%8F-quick-start-example)
23
+ - [Site-Occupancy Framework](#-site-occupancy-framework)
24
+ - [How to Cite](#-how-to-cite)
25
+ - [Contributing & Collaboration](#-contributing--collaboration)
26
+ - [License](#-license)
27
+ - [Project Links](#-project-links)
28
+
29
+ # ✨ Features
30
+
31
+ - **Flexible Model Definitions:** Use linear, non-linear, or neural networks for occupancy and detection probabilities via PyTorch modules.
32
+ - **Extensible:** Define custom architectures and features for modern site-occupancy modeling.
33
+ - **Supports Large, Heterogeneous Datasets:** Memory mapping and efficient batching for millions of observations with highly uneven visits per site. Suited for citizen science data with variable sampling and detection effort.
34
+ - **Multiple Optimizers:** LBFGS, SGD, Adam, and other first- and second-order optimizers.
35
+ - **Penalized Estimation:** Easily apply L1/L2 regularization and other penalties.
36
+ - **Open Source:** code available on GitHub under the MIT License, soon on PyPI. *A scientific publication describing and applying the method is in preparation.*
37
+
38
+ # 📦 Installation
39
+
40
+ We recommend using [uv](https://docs.astral.sh/uv/) for reproducible local development.
41
+ *Python ≥3.10 and PyTorch ≥2.0 recommended.*
42
+
43
+
44
+ ## Using OccuPYcy in another project
45
+
46
+ You can install OccuPYcy as a dependency in your project either from GitHub or from a local clone of the repository.
47
+
48
+ **From PyPI:** *(coming soon🤞)*
49
+
50
+ **From GitHub:**
51
+ Navigate to the repository on GitHub, create and activate your environment, and run:
52
+
53
+ ```bash
54
+ uv pip install git+https://github.com/RaphBnrd/OccuPYcy.git
55
+ ```
56
+ or if not using `uv`:
57
+ ```bash
58
+ pip install git+https://github.com/RaphBnrd/OccuPYcy.git
59
+ ```
60
+
61
+ **From the repository cloned on your machine:**
62
+ After cloning OccuPYcy (see below), navigate to the repository root of your project, and install it in editable mode with:
63
+ ```bash
64
+ pip install -e /local/path/to/the/repository/OccuPYcy
65
+ ```
66
+
67
+ ## Source code download
68
+
69
+ To download the source code and install the dependencies, you should first clone the repository, using `git clone https://github.com/RaphBnrd/OccuPYcy.git` at the location of your choice. You can also download the code as a zip or clone using SSH.
70
+
71
+ Then, if you want to setup a local development environment in the repository, move to the repository root (`cd occupycy`) and you can use `uv` or `venv` to create a virtual environment and install the dependencies.
72
+
73
+ ```bash
74
+ uv venv
75
+ uv pip install -e ".[dev]"
76
+ uv run pytest -q
77
+ ```
78
+
79
+ If not using `uv`:
80
+ ```bash
81
+ python3 -m venv .venv
82
+ source .venv/bin/activate
83
+ pip install -U pip
84
+ pip install -e ".[dev]"
85
+ pytest -q
86
+ ```
87
+
88
+ # ⚡️ Quick Start Example
89
+
90
+ Below is an example fitting a Multi-Layer Perceptron (MLP) occupancy model on simulated data.
91
+ Other examples are available in the [examples/](examples/) folder. More details on the code below are available in the notebook [01-fitting_on_simulated_data.ipynb](examples/01-fitting_on_simulated_data.ipynb).
92
+
93
+
94
+ ```python
95
+ import torch
96
+ import occupycy
97
+
98
+ seed = 1
99
+ torch.manual_seed(seed)
100
+ device = torch.device("cpu")
101
+
102
+ # 1. Simulate data (arbitrary non-linear functions)
103
+ def true_f_psi(X_psi): # here X_psi of shape (n_sites, n_cov_psi=2)
104
+ return torch.sigmoid(
105
+ - 0.5 * torch.cos(X_psi[:,0]) - 0.5 * (X_psi[:,1] ** 2)
106
+ ).unsqueeze(1)
107
+ def true_f_d(X_d): # here X_d of shape (n_total_visits, n_cov_d=1)
108
+ return torch.sigmoid(
109
+ torch.tanh(5 * X_d[:,0]) - torch.cos(X_d[:,0])
110
+ ).unsqueeze(1)
111
+
112
+ y, visit_site_ids, site_ids_in_X_psi, X_psi, X_d, true_z = \
113
+ occupycy.data.simulate_non_linear(
114
+ n_sites=5000,
115
+ n_total_visits_max=int(1e4),
116
+ n_cov_psi=2,
117
+ n_cov_d=1,
118
+ f_effort = lambda x: torch.distributions.LogNormal(0, 3).sample((x.shape[0],)),
119
+ f_psi=true_f_psi,
120
+ f_d=true_f_d,
121
+ seed=seed,
122
+ plot_summary=True,
123
+ verbose=True
124
+ )
125
+
126
+ # 2. Build OccuData (YOU CAN REPLACE THIS WITH YOUR OWN DATA)
127
+ # y: tensor of shape (n_total_visits, n_species) with the detection/non-detection data
128
+ # visit_site_ids: list of length (n_total_visits,) with the site id of each visit
129
+ # site_ids_in_X_psi: list of length (n_sites,) with the site ids of the rows in X_psi
130
+ # X_psi: tensor of shape (n_sites, n_cov_psi) with the covariates for occupancy
131
+ # X_d: tensor of shape (n_total_visits, n_cov_d) with the covariates for detection
132
+ data = occupycy.data.OccuData(
133
+ y=y,
134
+ visit_site_ids=visit_site_ids,
135
+ X_psi=X_psi,
136
+ X_d=X_d,
137
+ site_ids_in_X_psi=site_ids_in_X_psi
138
+ )
139
+
140
+ # 3. Define an MLP-MLP model
141
+ # (other architectures are possible, including custom ones)
142
+ model = occupycy.models.MLPOccuModel(
143
+ n_species=1,
144
+ n_cov_psi=data.X_psi.shape[1],
145
+ n_cov_d=data.X_d.shape[1],
146
+ hidden_dims_psi=[256, 256], hidden_dims_d=[256, 256],
147
+ activation_fn_psi=torch.nn.ReLU, activation_fn_d=torch.nn.ReLU
148
+ )
149
+
150
+ # 4. Fit the model with Adam (LBFGS is also available)
151
+ res = occupycy.fit.fit_sgd_like(
152
+ data, # OccuData object
153
+ model, # OccuModel object
154
+ n_epochs=1000, # maximum number of epochs
155
+ val_fraction=0.15, # fraction of sites to use for validation
156
+ batch_size=512, # number of sites per batch
157
+ optimizer_psi_cls=torch.optim.Adam, # optimizer class for the occupancy part
158
+ optimizer_d_cls=torch.optim.Adam, # optimizer class for the detection part
159
+ lr_psi=1e-3, # learning rate for the occupancy part
160
+ lr_d=1e-3, # learning rate for the detection part
161
+ patience_early_stopping=100,
162
+ patience_reduceLROnPlateau=20,
163
+ device=device
164
+ )
165
+
166
+ # 5. Get the predictions
167
+ with torch.no_grad():
168
+ pred_logit_psi, pred_logit_d = model.forward_logits(X_psi=X_psi.to(device), X_d=X_d.to(device))
169
+
170
+ ```
171
+
172
+ NB: The [examples](/examples) are numbered in the order of increasing complexity (and readability...).
173
+
174
+ # 🌱 Site-Occupancy Framework
175
+
176
+ **Site-occupancy models** estimate the probability that a species is present at a given site while accounting for imperfect detection during surveys ([MacKenzie et al. (2002)](https://doi.org/10.1890/0012-9658(2002)083[2248:ESORWD]2.0.CO;2)). This hierarchical approach is especially powerful for citizen science data, where both **detection bias** and **sampling bias** are common due to uneven survey effort and heterogeneous detection conditions.
177
+
178
+
179
+ <p align="center">
180
+ <img src="assets/opportunistic_PO_data-diagram.png" width="80%" alt="Illustration of citizen science data bias">
181
+ </p>
182
+
183
+ <p align="center">
184
+ <img src="assets/occupancy-diagram.png" width="60%" alt="Illustration of occupancy modeling framework">
185
+ </p>
186
+
187
+ <p align="center">
188
+ <sub>
189
+ <i>
190
+ Icon credits: icons from the figure sourced from Flaticon, created by Nikita Golubev, Freepik, Pixel Perfect, and surang.
191
+ </i>
192
+ </sub>
193
+ </p>
194
+
195
+ Mathematically:
196
+
197
+ - $Z_s \sim \mathrm{Bernoulli}(\psi_s)$
198
+ The latent occupancy state ($Z_s$) for site $s$.
199
+ - $Y_v \mid Z_{s(v)} \sim \mathrm{Bernoulli}(d_v \cdot Z_{s(v)})$
200
+ The detection ($Y_v$) during visit $v$, conditional on the site's true state $Z_{s(v)}$.
201
+
202
+ The probabilities $\psi_s$ (occupancy) and $d_v$ (detection) are flexible, parametric functions of covariates (e.g., spatial, temporal, observer info):
203
+
204
+ - **Classically**, $\psi_s$ and $d_v$ are modeled as sigmoid-linear functions (logistic regression).
205
+ - **With OccuPYcy**, these can be *any* differentiable model; in particular, a sigmoid transformation of an arbitrary PyTorch module, such as a neural network.
206
+
207
+ Then, for $K$ independent species, the likelihood of the observed data is:
208
+
209
+ <p align="center">
210
+ <img src="assets/NLL_equation.png" width="90%" alt="Negative log-likelihood equation">
211
+ </p>
212
+
213
+ where:
214
+
215
+ - $\mathcal{S}_{1,k}$ is the set of sites with at least one detection for species $k$
216
+ - $\mathcal{S}_{0,k}$ is the set of sites with no detection for species $k$
217
+ - $\mathcal{V}_s$ is the set of visits to site $s$
218
+
219
+ This likelihood is optimized with respect to the parameters $\theta_\psi$ and $\theta_d$ — the parameters of the occupancy and detection models — using (stochastic) gradient-based methods.
220
+
221
+ > **Example:**
222
+ > &nbsp;&nbsp; $\psi_s = \mathrm{sigmoid}\left(f_{\theta_\psi}(X_s)\right)$
223
+ > &nbsp;&nbsp; $d_v = \mathrm{sigmoid}\left(g_{\theta_d}(U_v)\right)$
224
+ > where $f_{\theta_\psi}$ and $g_{\theta_d}$ can be linear, MLP, or any neural network.
225
+
226
+ **Applications:**
227
+
228
+ - Well-suited for massive, opportunistic presence-only datasets, such as citizen science records (sites = spatial grid, visits = observations).
229
+ - Corrects for both **detection** and **sampling** bias, enabling robust estimation of species distributions and trends.
230
+ - Models uneven non-linear sampling and detection: complex and heterogeneous survey effort, or detection/reporting ability or willingness across space, time, and observers.
231
+ - Handles multi-species data with shared covariates and common embedding.
232
+
233
+ # 📖 How to Cite
234
+
235
+ *Manuscript in preparation*
236
+
237
+ # 🤝 Contributing & Collaboration
238
+
239
+ We welcome not only code contributions and bug reports, but also scientific collaborations — especially in ecology, citizen science, machine learning, and statistics! If you'd like to collaborate or have scientific ideas to discuss, feel free to [email me](mailto:raphael.benerradi@inria.fr) or open an [issue](https://github.com/RaphBnrd/OccuPYcy/issues).
240
+
241
+ Standard code contributions (pull requests, feature requests, etc.) are also welcome.
242
+
243
+ # 📜 License
244
+
245
+ OccuPYcy is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
246
+
247
+ # 🔗 Project Links
248
+
249
+ - [Source code on GitHub](https://github.com/RaphBnrd/OccuPYcy)
250
+ - [Example usage](examples/) in the repository
251
+ - [PhD project](https://raphbnrd.github.io/projects/mapping_plant_species/) section on my website
252
+ - For questions, contact [raphael.benerradi@inria.fr](mailto:raphael.benerradi@inria.fr)
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "OccuPYcy"
7
+ version = "0.0.1.dev45429274732"
8
+ description = "Occupancy modeling with maximum likelihood estimation in Python"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { file = "LICENSE" }
12
+ classifiers = ["License :: OSI Approved :: MIT License"]
13
+ authors = [{ name = "Raphaël Benerradi" }]
14
+ dependencies = [
15
+ "ipykernel>=7.0",
16
+ "matplotlib>=3.0",
17
+ "pandas>=2.0",
18
+ "polars>=1.0",
19
+ "numpy>=2.0",
20
+ "torch>=2.0",
21
+ "tqdm>=4.0",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ dev = ["pytest>=7"]
26
+
27
+ [project.urls]
28
+ Documentation = "https://raphbnrd.github.io/OccuPYcy/"
29
+
30
+ [tool.setuptools]
31
+ package-dir = { "" = "src" }
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+