safraeli commited on
Commit
90ef7a6
Β·
verified Β·
1 Parent(s): 13fc29d

README: refresh Space metadata

Browse files
Files changed (1) hide show
  1. README.md +82 -117
README.md CHANGED
@@ -1,117 +1,82 @@
1
- # SolarWine β€” Photosynthesis Prediction for Agrivoltaic Vineyards
2
-
3
- A two-stage pipeline that models grapevine photosynthesis under agrivoltaic panels (solar panels above vineyard rows) and predicts it from publicly available weather data. Built for the Sde Boker research site (Negev, Israel).
4
-
5
- ## Status β€” May 2026
6
-
7
- - **2026 sensor migration complete.** `DEVICE_REGISTRY` clean-replaced (19 Crop_2Soil with spectrometer + dual soil profile, 12 panel thermocouples, 4 trackers). `VineSnapshot` rewritten with NDVI / PRI / PSRI / SIPI / GCI / LCI / DUVI + dual-soil + position-keyed dicts. Treatment = rows 501/502/503/504/509; Reference = row 202.
8
- - **Energy predictor refreshed.** New `scripts/refresh_energy_data.py` + `scripts/train_energy_predictor.py`. Hourly MAE 4.5 kWh on the May hold-out; **daily bias +50%** is intervention-regime drift (training tracker-angle avg βˆ’15Β°, hold-out avg βˆ’51Β° due to active shading), not a code bug β€” fix lands once β‰₯3 months of 2026 growing-season data accumulate (~Aug 2026).
9
- - **2026 ML pipeline scaffolded.** `scripts/collect_2026_training_data.py` pulls treatment + reference Crop_2Soil + IMS, applies a tracker-angle + ShadowModel PAR-shading correction (PAR factor 0.10–1.00, median 0.82), then computes Farquhar A as labels. First 10 days: 1,896 rows, daytime mean A β‰ˆ 11.7 Β΅mol COβ‚‚/mΒ²/s β€” squarely in the Greer–Weedon Semillon range.
10
- - **Frontend redesigned.** React app at `frontend/` rebuilt to the SolarWine editorial design system (Negev sand surfaces, vine green + sun gold, Source Serif 4 + IBM Plex Sans + IBM Plex Mono). All 11 pages β€” Home, Agronomy, Photosynthesis, Shading, Power, Trackers, Control loop, Advisor, Monitoring, Documentation, **Research** (new) β€” use the new chrome and Recharts wrappers.
11
- - **Streamlit dashboard cleaned of stale data.** Control Replay defaults to a fresh 2026 sim log; `scripts/run_control_simulation.py` defaults to `today βˆ’ 7 d / today`; Shading tab clarifies the legacy `sensors_wide.csv` is frozen at Feb 2026; freshness warnings flag stale logs.
12
-
13
- See `context/3_todo.md` Β§ 12 for the rolling work log. `frontend/` is the production UI; `app.py` remains as the legacy Streamlit dashboard.
14
-
15
- ## What it does
16
-
17
- **Stage 1 β€” Mechanistic model (sensors β†’ photosynthesis rate A)**
18
- Uses on-site sensor data (PAR, leaf temperature, CO2, VPD, air temperature) collected at 15-minute intervals to compute net carbon assimilation *A* via the Farquhar et al. (1980) biochemical model, with Greer & Weedon (2012) temperature response curves calibrated for *Vitis vinifera*. Includes Crop Water Stress Index (CWSI) and stomatal conductance adjustments. Only the growing season (May–September) is used; vines are dormant October–April.
19
-
20
- **Stage 2 β€” ML prediction (IMS weather β†’ A)**
21
- Trains regression models to predict *A* using only Israel Meteorological Service (IMS) station 43 data (air temperature, GHI solar radiation, relative humidity, rainfall, wind speed). This enables photosynthesis forecasting without on-site sensors. Models evaluated: Linear Regression, Decision Tree, Random Forest, Gradient Boosting, and XGBoost.
22
-
23
- **Time-series forecasting**
24
- Direct multi-horizon forecasting (15 min, 1 hour, 1 day, 1 week, 1 month ahead) using lag features and daytime-session indexing to handle overnight gaps. Per-horizon XGBoost/GradientBoosting models.
25
-
26
- **Tracker optimizer**
27
- Simulates agrivoltaic panel tilt angles to find the optimal tradeoff between solar energy capture and crop photosynthesis. Computes a stress-aware daily schedule that recommends shading during heat stress periods, with season-level summaries of energy yield, photosynthesis impact, and estimated water savings.
28
-
29
- **Solar geometry & canopy photosynthesis**
30
- Calculates sun position, panel shadow geometry, and diffuse/direct PAR reaching the vine canopy at configurable panel dimensions and row spacings.
31
-
32
- ## Interactive Streamlit app
33
-
34
- A branded dashboard (`app.py`, ~1900 lines) with:
35
-
36
- - **Sidebar** β€” Run Stage 1 / Stage 2, download IMS data (chunked 7-day fetches for 2024–2025), data status indicators
37
- - **Stage 1 tab** β€” Labels distribution, validation plots, Farquhar model outputs
38
- - **Stage 2 tab** β€” Model comparison metrics (RMSE, MAE, RΒ²), prediction vs actual plots, feature importance
39
- - **EDA tab** β€” Sensor distributions, A over time, IMS weather statistics, merged dataset exploration
40
- - **Time-Series tab** β€” Multi-horizon forecast results with per-tab explanations
41
- - **Tracker Optimizer tab** β€” Tilt-angle simulations, stress heatmaps, daily shading schedule, season summary
42
- - **About tab** β€” Two-stage rationale, methodology, and project roadmap
43
-
44
- ## Project structure
45
-
46
- ```
47
- config/settings.py Site/panel geometry, IMS channel map, paths, train ratio
48
- src/
49
- farquhar_model.py Farquhar–Greer–Weedon mechanistic photosynthesis model
50
- sensor_data_loader.py Load and filter on-site sensor CSVs
51
- ims_client.py IMS REST API client with caching
52
- preprocessor.py Merge IMS + labels, add time features, temporal split
53
- predictor.py Train/evaluate ML regressors (LR, DT, RF, GBR, XGB)
54
- ts_predictor.py Lag-based multi-horizon time-series forecasting
55
- tracker_optimizer.py Tilt-angle simulation and stress-aware scheduling
56
- solar_geometry.py Sun position, shadow projection, canopy PAR
57
- canopy_photosynthesis.py Canopy-level photosynthesis integration
58
- scripts/
59
- download_ims_data.py CLI: fetch IMS station data (--list-channels, date range)
60
- run_pipeline.py CLI: execute full Stage 1 β†’ Stage 2 pipeline
61
- create_sample_data.py Generate trimmed sample CSV for cloud deployment
62
- eda.py Standalone exploratory data analysis
63
- app.py Streamlit dashboard
64
- Data/Seymour/ On-site sensor data (15-min intervals)
65
- Data/ims/ Cached IMS API responses
66
- Data/processed/ Intermediate files (labels, merged data)
67
- outputs/ Metrics CSVs and plots (gitignored)
68
- assets/ Logo and vineyard imagery
69
- ```
70
-
71
- ## Setup
72
-
73
- ```bash
74
- python -m venv .venv
75
- source .venv/bin/activate # Windows: .venv\Scripts\activate
76
- pip install -r requirements.txt
77
- ```
78
-
79
- Create a `.env` file with your IMS API token:
80
-
81
- ```
82
- IMS_API_TOKEN=<your-token>
83
- ```
84
-
85
- See [ims_api_documentation.md](ims_api_documentation.md) for token registration.
86
-
87
- ## Usage
88
-
89
- ### Download IMS weather data
90
-
91
- ```bash
92
- python -m scripts.download_ims_data --list-channels # show available channels
93
- python -m scripts.download_ims_data --from 2024-01-01 --to 2024-12-31
94
- ```
95
-
96
- ### Run the pipeline
97
-
98
- ```bash
99
- python -m scripts.run_pipeline
100
- ```
101
-
102
- Stage 1: load sensors β†’ filter daytime β†’ keep growing season (May–Sep) β†’ compute Farquhar *A* β†’ save labels.
103
- Stage 2: load IMS + labels β†’ merge on timestamp β†’ add time features β†’ temporal train/test split β†’ train & evaluate models β†’ save metrics and plots to `outputs/`.
104
-
105
- ### Launch the app
106
-
107
- ```bash
108
- streamlit run app.py
109
- ```
110
-
111
- ## Key dependencies
112
-
113
- pandas, numpy, scikit-learn, xgboost, pvlib, matplotlib, seaborn, plotly, streamlit, requests, python-dotenv
114
-
115
- ## Deployment
116
-
117
- See [DEPLOY.md](DEPLOY.md) for Streamlit Community Cloud deployment instructions. A trimmed sensor sample (`sensors_wide_sample.csv`) is included for cloud use where the full 982 MB dataset is not available.
 
1
+ ---
2
+ title: SolarWine API
3
+ emoji: 🌿
4
+ colorFrom: green
5
+ colorTo: yellow
6
+ sdk: docker
7
+ app_port: 7860
8
+ private: true
9
+ ---
10
+
11
+ # SolarWine API
12
+
13
+ FastAPI backend for the SolarWine agrivoltaic vineyard control system.
14
+
15
+ ## Endpoints
16
+
17
+ ### Health & Monitoring
18
+ - `GET|HEAD /api/health` β€” system health (uptime, Redis, TB, IMS, Gemini status)
19
+ - `GET /api/health/data` β€” data freshness per source (age, ok/degraded)
20
+ - `GET /api/health/data-sources` β€” per-source green/yellow/red status with thresholds
21
+
22
+ ### Weather (IMS Station 43)
23
+ - `GET /api/weather/current` β€” latest weather readings + data age
24
+ - `GET /api/weather/history?start_date&end_date&format` β€” historical weather (hourly)
25
+ - `GET /api/weather/forecast` β€” weather forecast
26
+
27
+ ### Vine Sensors (ThingsBoard)
28
+ - `GET /api/sensors/snapshot` β€” latest readings (treatment vs reference)
29
+ - `GET /api/sensors/history?type&area&hours` β€” sensor time-series
30
+ - `GET /api/sensors/soil-moisture?hours` β€” soil moisture history
31
+ - `GET /api/sensors/rain?hours` β€” rainfall history
32
+
33
+ ### Energy
34
+ - `GET /api/energy/current` β€” current power output (kW)
35
+ - `GET /api/energy/daily/{date}` β€” daily production + hourly profile
36
+ - `GET /api/energy/history` β€” energy generation time-series
37
+ - `GET /api/energy/predict/{date}` β€” predicted daily generation
38
+
39
+ ### Photosynthesis
40
+ - `GET /api/photosynthesis/current?model` β€” current A rate (FvCB or ML)
41
+ - `GET /api/photosynthesis/forecast` β€” 24h predicted A profile
42
+
43
+ ### Control System
44
+ - `GET /api/control/status` β€” last control loop tick
45
+ - `GET /api/control/plan` β€” current day-ahead plan
46
+ - `GET /api/control/budget` β€” energy budget status
47
+ - `GET /api/control/trackers` β€” tracker angles and modes
48
+
49
+ ### Chatbot (Gemini AI)
50
+ - `POST /api/chatbot/message` β€” send message to vineyard advisor
51
+ - `POST /api/chatbot/feedback` β€” submit feedback on response
52
+ - `GET /api/chatbot/briefing` β€” current system status briefing
53
+
54
+ ### Biology
55
+ - `GET /api/biology/phenology` β€” current growth stage
56
+ - `GET /api/biology/rules` β€” all biology rules
57
+ - `GET /api/biology/rules/{name}` β€” single rule detail
58
+ - `GET /api/biology/chill-units?season_start` β€” accumulated chill units
59
+
60
+ ### Auth
61
+ - `POST /api/auth/login` β€” JWT token (guest mode when JWT_SECRET unset)
62
+
63
+ ### Events
64
+ - `GET /api/events/stream` β€” SSE stream for live frontend updates
65
+
66
+ Interactive docs at `/docs`.
67
+
68
+ ## Environment Variables
69
+
70
+ | Variable | Required | Description |
71
+ |----------|----------|-------------|
72
+ | `IMS_API_TOKEN` | Yes | IMS weather API token |
73
+ | `THINGSBOARD_HOST` | Yes | ThingsBoard server URL |
74
+ | `THINGSBOARD_USERNAME` | Yes | ThingsBoard login |
75
+ | `THINGSBOARD_PASSWORD` | Yes | ThingsBoard password |
76
+ | `GOOGLE_API_KEY` | No | Gemini AI for chatbot/advisor |
77
+ | `JWT_SECRET` | No | JWT signing key (guest mode if unset) |
78
+ | `ADMIN_PASSWORD` | No | Login password |
79
+ | `REDIS_URL` | No | Upstash Redis for shared cache |
80
+ | `SENTRY_DSN` | No | Sentry error tracking |
81
+ | `SMTP_HOST` | No | Email alerts (with ALERT_EMAIL_TO) |
82
+ | `ALERT_EMAIL_TO` | No | Alert recipient email(s) |