Spaces:
Sleeping
Sleeping
File size: 6,502 Bytes
9d5d2ab fb49915 4a4dc2f fb49915 9d5d2ab fb49915 9d5d2ab fb49915 4a4dc2f fb49915 4a4dc2f fb49915 4a4dc2f fb49915 4a4dc2f fb49915 4a4dc2f fb49915 4a4dc2f fb49915 4a4dc2f fb49915 4a4dc2f fb49915 4a4dc2f fb49915 acbbeb5 fb49915 acbbeb5 fb49915 acbbeb5 fb49915 acbbeb5 fb49915 4a4dc2f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
#This source code is licensed under the BSD-style license found in the
#LICENSE file in the root directory of this source tree.
"""
Smart Farm Irrigation Environment Implementation.
A real-world environment where an AI agent manages crop irrigation
by deciding how much water to give crops each day based on:
- Weather conditions (temperature, rainfall) from real Weather API
- Soil moisture (from sensor or auto-calculated)
- Crop health (user input)
- Crop stage (auto-managed by code)
"""
from uuid import uuid4
from openenv.core.env_server.interfaces import Environment
from openenv.core.env_server.types import State
try:
from my_env.models import FarmAction, FarmObservation, CropStage, CropHealthStatus
from my_env.weather import WeatherService
except ImportError:
from my_env.models import FarmAction, FarmObservation, CropStage, CropHealthStatus
from my_env.weather import WeatherService
class FarmEnvironment(Environment):
"""Smart Farm Irrigation Environment."""
SUPPORTS_CONCURRENT_SESSIONS: bool = True
def __init__(self):
self._state = State(episode_id=str(uuid4()), step_count=0)
self._weather_service = WeatherService()
self._city = "Indore"
self._day = 1
self._soil_moisture = 30.0
self._crop_health = CropHealthStatus.FAIR
self._temperature = 30.0
self._rainfall = 0.0
self._crop_stage = CropStage.SEEDLING
self._sensor_moisture = None
def reset(
self,
city: str = "Indore",
sensor_moisture: float = None,
crop_health: str = "fair"
) -> FarmObservation:
self._state = State(episode_id=str(uuid4()), step_count=0)
self._city = city
weather = self._weather_service.get_weather(city)
self._temperature = weather["temperature"]
self._rainfall = weather["rainfall"]
print(f"Weather for {city}: {self._temperature}C, {self._rainfall}mm rain")
if sensor_moisture is not None:
self._soil_moisture = sensor_moisture
print(f"Soil moisture from sensor: {self._soil_moisture}%")
else:
self._soil_moisture = self._weather_service.calculate_soil_moisture(
current_moisture=50.0,
temperature=self._temperature,
rainfall=self._rainfall
)
print(f"Soil moisture calculated: {self._soil_moisture}%")
try:
self._crop_health = CropHealthStatus(crop_health)
except ValueError:
self._crop_health = CropHealthStatus.FAIR
self._day = 1
self._crop_stage = CropStage.SEEDLING
return FarmObservation(
temperature=self._temperature,
rainfall=self._rainfall,
soil_moisture=self._soil_moisture,
crop_health=self._crop_health,
day_number=self._day,
crop_stage=self._crop_stage,
done=False,
reward=0.0,
)
def step(self, action: FarmAction) -> FarmObservation:
"""Execute one day of farming."""
self._state.step_count += 1
# Water Amount Mapping
water_map = {
"none": 0,
"low": 10,
"medium": 25,
"high": 50,
}
water_added = water_map.get(action.water_amount.value, 0)
# Use real historical weather for each day
weather = self._weather_service.get_historical_weather(
self._city, self._day
)
self._temperature = weather["temperature"]
self._rainfall = weather["rainfall"]
# Update Soil Moisture
if self._sensor_moisture is not None:
evaporation = (self._temperature / 100) * 10
self._soil_moisture = self._soil_moisture + water_added - evaporation
else:
self._soil_moisture = self._weather_service.calculate_soil_moisture(
current_moisture=self._soil_moisture + water_added,
temperature=self._temperature,
rainfall=self._rainfall
)
# Keep moisture in valid range 0-100
self._soil_moisture = max(0.0, min(100.0, self._soil_moisture))
# Update Crop Health based on moisture
health_order = ["poor", "fair", "good", "excellent"]
current_idx = health_order.index(self._crop_health.value)
if self._soil_moisture < 20 or self._soil_moisture > 90:
new_idx = max(0, current_idx - 1)
self._crop_health = CropHealthStatus(health_order[new_idx])
elif 40 <= self._soil_moisture <= 75:
new_idx = min(3, current_idx + 1)
self._crop_health = CropHealthStatus(health_order[new_idx])
# Advance Day
self._day += 1
# Auto Update Crop Stage based on day
if self._day <= 10:
self._crop_stage = CropStage.SEEDLING
elif self._day <= 20:
self._crop_stage = CropStage.GROWING
else:
self._crop_stage = CropStage.MATURE
# Calculate Reward
reward = self._calculate_reward(water_added)
# Is episode done?
done = self._day > 30
return FarmObservation(
temperature=self._temperature,
rainfall=self._rainfall,
soil_moisture=self._soil_moisture,
crop_health=self._crop_health,
day_number=min(self._day, 30),
crop_stage=self._crop_stage,
done=done,
reward=reward,
)
def _calculate_reward(self, water_added: float) -> float:
"""Calculate reward. Returns value between -1.0 and 1.0"""
ideal_ranges = {
CropStage.SEEDLING: (40, 70),
CropStage.GROWING: (45, 70),
CropStage.MATURE: (35, 60),
}
low, high = ideal_ranges[self._crop_stage]
if low <= self._soil_moisture <= high:
reward = 0.98
elif (low - 10) <= self._soil_moisture <= (high + 10):
reward = 0.5
elif self._soil_moisture < 20:
reward = -0.98
elif self._soil_moisture > 90:
reward = -0.5
else:
reward = 0.02
if self._rainfall > 15 and water_added > 0:
reward -= 0.3
return round(max(-0.99, min(0.99, reward)), 4)
@property
def state(self) -> State:
return self._state |