meta-hackathon-project / server /my_env_environment.py
Vidhiii1711's picture
updated some files
9d5d2ab
Raw History Blame Contribute Delete
6.5 kB
# 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