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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Baseline Inference Script for Smart Farm Irrigation Environment.
|
| 9 |
+
|
| 10 |
+
This script runs a simple rule-based agent through all 3 tasks
|
| 11 |
+
and produces reproducible baseline scores.
|
| 12 |
+
|
| 13 |
+
The agent uses simple rules:
|
| 14 |
+
- If soil moisture < 40% β water high
|
| 15 |
+
- If soil moisture < 55% β water medium
|
| 16 |
+
- If soil moisture < 65% β water low
|
| 17 |
+
- Otherwise β no water
|
| 18 |
+
|
| 19 |
+
Usage:
|
| 20 |
+
python baseline.py
|
| 21 |
+
python baseline.py --city Mumbai
|
| 22 |
+
python baseline.py --city Delhi --task 1
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import sys
|
| 27 |
+
import os
|
| 28 |
+
|
| 29 |
+
# Add parent directory to path so we can import our modules
|
| 30 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 31 |
+
|
| 32 |
+
from server.my_env_environment import FarmEnvironment
|
| 33 |
+
from graders import grade_task1, grade_task2, grade_task3
|
| 34 |
+
from tasks import get_all_tasks
|
| 35 |
+
|
| 36 |
+
def simple_agent(observation: dict) -> str:
|
| 37 |
+
"""
|
| 38 |
+
A simple rule-based agent that decides how much to water
|
| 39 |
+
based on current soil moisture level.
|
| 40 |
+
|
| 41 |
+
Rules:
|
| 42 |
+
- Very dry (< 40%) β water high
|
| 43 |
+
- Dry (< 55%) β water medium
|
| 44 |
+
- Slightly (< 65%) β water low
|
| 45 |
+
- Good (>= 65%) β no water
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
observation: Current farm state dictionary
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
water_amount string: "none"/"low"/"medium"/"high"
|
| 52 |
+
"""
|
| 53 |
+
moisture = observation.get("soil_moisture", 50)
|
| 54 |
+
rainfall = observation.get("rainfall", 0)
|
| 55 |
+
|
| 56 |
+
# Don't water if it's already raining heavily
|
| 57 |
+
if rainfall > 15:
|
| 58 |
+
return "none"
|
| 59 |
+
|
| 60 |
+
# Decide based on moisture level
|
| 61 |
+
if moisture < 40:
|
| 62 |
+
return "high"
|
| 63 |
+
elif moisture < 55:
|
| 64 |
+
return "medium"
|
| 65 |
+
elif moisture < 65:
|
| 66 |
+
return "low"
|
| 67 |
+
else:
|
| 68 |
+
return "none"
|
| 69 |
+
|
| 70 |
+
def run_task(env, task_id: int, city: str = "Indore") -> dict:
|
| 71 |
+
"""
|
| 72 |
+
Runs the agent through a single task and returns results.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
env: FarmEnvironment instance
|
| 76 |
+
task_id: 1, 2, or 3
|
| 77 |
+
city: City name for weather data
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
Dictionary with score and episode history
|
| 81 |
+
"""
|
| 82 |
+
# Task configurations
|
| 83 |
+
task_config = {
|
| 84 |
+
1: {"max_steps": 7, "name": "Basic Moisture Control"},
|
| 85 |
+
2: {"max_steps": 14, "name": "Weather Adaptive Irrigation"},
|
| 86 |
+
3: {"max_steps": 30, "name": "Full Season Management"},
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
config = task_config[task_id]
|
| 90 |
+
max_steps = config["max_steps"]
|
| 91 |
+
task_name = config["name"]
|
| 92 |
+
|
| 93 |
+
print(f"\n{'='*50}")
|
| 94 |
+
print(f"Running Task {task_id}: {task_name}")
|
| 95 |
+
print(f"City: {city} | Max Steps: {max_steps}")
|
| 96 |
+
print(f"{'='*50}")
|
| 97 |
+
|
| 98 |
+
# Reset environment
|
| 99 |
+
obs = env.reset(city=city)
|
| 100 |
+
|
| 101 |
+
# Convert observation to dict
|
| 102 |
+
obs_dict = {
|
| 103 |
+
"temperature": obs.temperature,
|
| 104 |
+
"rainfall": obs.rainfall,
|
| 105 |
+
"soil_moisture": obs.soil_moisture,
|
| 106 |
+
"crop_health": obs.crop_health.value,
|
| 107 |
+
"day_number": obs.day_number,
|
| 108 |
+
"crop_stage": obs.crop_stage.value,
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
episode_history = []
|
| 112 |
+
|
| 113 |
+
# Run for max_steps
|
| 114 |
+
for step in range(max_steps):
|
| 115 |
+
|
| 116 |
+
# Agent decides action
|
| 117 |
+
water_amount = simple_agent(obs_dict)
|
| 118 |
+
|
| 119 |
+
# Map action to number for graders
|
| 120 |
+
action_map = {
|
| 121 |
+
"none": 0,
|
| 122 |
+
"low": 1,
|
| 123 |
+
"medium": 2,
|
| 124 |
+
"high": 3
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
# Record this step
|
| 128 |
+
episode_history.append({
|
| 129 |
+
"day": obs_dict["day_number"],
|
| 130 |
+
"soil_moisture": obs_dict["soil_moisture"],
|
| 131 |
+
"crop_health": obs_dict["crop_health"],
|
| 132 |
+
"water_action": action_map[water_amount],
|
| 133 |
+
"rainfall": obs_dict["rainfall"],
|
| 134 |
+
"temperature": obs_dict["temperature"],
|
| 135 |
+
"crop_stage": obs_dict["crop_stage"],
|
| 136 |
+
})
|
| 137 |
+
|
| 138 |
+
print(f"Day {obs_dict['day_number']:2d} | "
|
| 139 |
+
f"Moisture: {obs_dict['soil_moisture']:5.1f}% | "
|
| 140 |
+
f"Temp: {obs_dict['temperature']:4.1f}C | "
|
| 141 |
+
f"Rain: {obs_dict['rainfall']:4.1f}mm | "
|
| 142 |
+
f"Action: {water_amount}")
|
| 143 |
+
|
| 144 |
+
# Take action in environment
|
| 145 |
+
from models import FarmAction, WaterAmount
|
| 146 |
+
action = FarmAction(water_amount=WaterAmount(water_amount))
|
| 147 |
+
result = env.step(action)
|
| 148 |
+
|
| 149 |
+
# Check if done
|
| 150 |
+
if result.done:
|
| 151 |
+
break
|
| 152 |
+
|
| 153 |
+
# Update observation
|
| 154 |
+
obs_dict = {
|
| 155 |
+
"temperature": result.temperature,
|
| 156 |
+
"rainfall": result.rainfall,
|
| 157 |
+
"soil_moisture": result.soil_moisture,
|
| 158 |
+
"crop_health": result.crop_health.value,
|
| 159 |
+
"day_number": result.day_number,
|
| 160 |
+
"crop_stage": result.crop_stage.value,
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
# Grade the episode
|
| 164 |
+
graders = {
|
| 165 |
+
1: grade_task1,
|
| 166 |
+
2: grade_task2,
|
| 167 |
+
3: grade_task3,
|
| 168 |
+
}
|
| 169 |
+
score = graders[task_id](episode_history)
|
| 170 |
+
|
| 171 |
+
print(f"\nTask {task_id} Final Score: {score}")
|
| 172 |
+
return {
|
| 173 |
+
"task_id": task_id,
|
| 174 |
+
"task_name": task_name,
|
| 175 |
+
"score": score,
|
| 176 |
+
"steps_completed": len(episode_history),
|
| 177 |
+
"episode_history": episode_history,
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
def main(city: str = "Indore", task_id: int = None):
|
| 181 |
+
"""
|
| 182 |
+
Main function β runs agent through all 3 tasks
|
| 183 |
+
and prints final scores.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
city: City name for weather data
|
| 187 |
+
task_id: Run specific task only (None = run all)
|
| 188 |
+
"""
|
| 189 |
+
print("\n" + "="*50)
|
| 190 |
+
print(" SMART FARM IRRIGATION β BASELINE SCORES")
|
| 191 |
+
print("="*50)
|
| 192 |
+
print(f"City: {city}")
|
| 193 |
+
print(f"Agent: Simple Rule-Based Agent")
|
| 194 |
+
|
| 195 |
+
# Create environment
|
| 196 |
+
env = FarmEnvironment()
|
| 197 |
+
|
| 198 |
+
# Determine which tasks to run
|
| 199 |
+
tasks_to_run = [task_id] if task_id else [1, 2, 3]
|
| 200 |
+
|
| 201 |
+
# Run tasks and collect results
|
| 202 |
+
results = []
|
| 203 |
+
for tid in tasks_to_run:
|
| 204 |
+
result = run_task(env, tid, city=city)
|
| 205 |
+
results.append(result)
|
| 206 |
+
|
| 207 |
+
# Print final summary
|
| 208 |
+
print("\n" + "="*50)
|
| 209 |
+
print(" FINAL BASELINE SCORES")
|
| 210 |
+
print("="*50)
|
| 211 |
+
for result in results:
|
| 212 |
+
print(f"Task {result['task_id']} ({result['task_name']}): "
|
| 213 |
+
f"{result['score']}")
|
| 214 |
+
|
| 215 |
+
# Calculate average
|
| 216 |
+
avg = sum(r["score"] for r in results) / len(results)
|
| 217 |
+
print(f"\nAverage Score: {round(avg, 2)}")
|
| 218 |
+
print("="*50)
|
| 219 |
+
|
| 220 |
+
return results
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
if __name__ == "__main__":
|
| 224 |
+
parser = argparse.ArgumentParser(
|
| 225 |
+
description="Run baseline agent on Smart Farm Environment"
|
| 226 |
+
)
|
| 227 |
+
parser.add_argument(
|
| 228 |
+
"--city",
|
| 229 |
+
type=str,
|
| 230 |
+
default="Indore",
|
| 231 |
+
help="City name for weather data (default: Indore)"
|
| 232 |
+
)
|
| 233 |
+
parser.add_argument(
|
| 234 |
+
"--task",
|
| 235 |
+
type=int,
|
| 236 |
+
default=None,
|
| 237 |
+
choices=[1, 2, 3],
|
| 238 |
+
help="Run specific task only (default: run all tasks)"
|
| 239 |
+
)
|
| 240 |
+
args = parser.parse_args()
|
| 241 |
+
main(city=args.city, task_id=args.task)
|
my_env/graders.py
CHANGED
|
@@ -1,9 +1,22 @@
|
|
| 1 |
# graders.py β reward functions and graders for all 3 tasks
|
| 2 |
|
| 3 |
-
|
| 4 |
-
# βββββββββββββββββββββββββββββ
|
| 5 |
# REWARD β called every single day
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
def compute_reward(soil_moisture, crop_health, water_action, rainfall):
|
| 9 |
"""
|
|
@@ -34,10 +47,7 @@ def compute_reward(soil_moisture, crop_health, water_action, rainfall):
|
|
| 34 |
# Keep between -1.0 and 1.0
|
| 35 |
return round(max(-1.0, min(1.0, reward)), 2)
|
| 36 |
|
| 37 |
-
|
| 38 |
-
# βββββββββββββββββββββββββββββ
|
| 39 |
# TASK 1 GRADER β Easy (7 days)
|
| 40 |
-
# βββββββββββββββββββββββββββββ
|
| 41 |
|
| 42 |
def grade_task1(episode_history):
|
| 43 |
"""
|
|
@@ -56,10 +66,7 @@ def grade_task1(episode_history):
|
|
| 56 |
score = days_in_range / len(episode_history)
|
| 57 |
return round(score, 2)
|
| 58 |
|
| 59 |
-
|
| 60 |
-
# βββββββββββββββββββββββββββββ
|
| 61 |
# TASK 2 GRADER β Medium (14 days)
|
| 62 |
-
# βββββββββββββββββββββββββββββ
|
| 63 |
|
| 64 |
def grade_task2(episode_history):
|
| 65 |
"""
|
|
@@ -75,7 +82,7 @@ def grade_task2(episode_history):
|
|
| 75 |
for record in episode_history:
|
| 76 |
daily = compute_reward(
|
| 77 |
record.get("soil_moisture", 0),
|
| 78 |
-
record.get("crop_health",
|
| 79 |
record.get("water_action", 0),
|
| 80 |
record.get("rainfall", 0)
|
| 81 |
)
|
|
@@ -84,10 +91,7 @@ def grade_task2(episode_history):
|
|
| 84 |
score = total_reward / max_possible if max_possible > 0 else 0.0
|
| 85 |
return round(max(0.0, min(1.0, score)), 2)
|
| 86 |
|
| 87 |
-
|
| 88 |
-
# βββββββββββββββββββββββββββββ
|
| 89 |
# TASK 3 GRADER β Hard (30 days)
|
| 90 |
-
# βββββββββββββββββββββββββββββ
|
| 91 |
|
| 92 |
def grade_task3(episode_history):
|
| 93 |
"""
|
|
@@ -103,7 +107,7 @@ def grade_task3(episode_history):
|
|
| 103 |
for record in episode_history:
|
| 104 |
day = record.get("day", 1)
|
| 105 |
moisture = record.get("soil_moisture", 0)
|
| 106 |
-
crop_health = record.get("crop_health",
|
| 107 |
|
| 108 |
# Each stage needs different moisture
|
| 109 |
if day <= 10: # Seedling
|
|
@@ -123,10 +127,7 @@ def grade_task3(episode_history):
|
|
| 123 |
score = sum(day_scores) / len(day_scores)
|
| 124 |
return round(score, 2)
|
| 125 |
|
| 126 |
-
|
| 127 |
-
# βββββββββββββββββββββββββββββ
|
| 128 |
# TEST β run this file to verify
|
| 129 |
-
# βββββββββββββββββββββββββββββ
|
| 130 |
|
| 131 |
if __name__ == "__main__":
|
| 132 |
# Fake data to test all 3 graders
|
|
|
|
| 1 |
# graders.py β reward functions and graders for all 3 tasks
|
| 2 |
|
|
|
|
|
|
|
| 3 |
# REWARD β called every single day
|
| 4 |
+
|
| 5 |
+
def health_to_number(crop_health_str: str) -> int:
|
| 6 |
+
"""
|
| 7 |
+
Converts crop health string to number for grading.
|
| 8 |
+
poor=25, fair=50, good=75, excellent=100
|
| 9 |
+
"""
|
| 10 |
+
mapping = {
|
| 11 |
+
"poor": 25,
|
| 12 |
+
"fair": 50,
|
| 13 |
+
"good": 75,
|
| 14 |
+
"excellent": 100
|
| 15 |
+
}
|
| 16 |
+
# Handle both string and already-numeric values
|
| 17 |
+
if isinstance(crop_health_str, (int, float)):
|
| 18 |
+
return crop_health_str
|
| 19 |
+
return mapping.get(str(crop_health_str).lower(), 50)
|
| 20 |
|
| 21 |
def compute_reward(soil_moisture, crop_health, water_action, rainfall):
|
| 22 |
"""
|
|
|
|
| 47 |
# Keep between -1.0 and 1.0
|
| 48 |
return round(max(-1.0, min(1.0, reward)), 2)
|
| 49 |
|
|
|
|
|
|
|
| 50 |
# TASK 1 GRADER β Easy (7 days)
|
|
|
|
| 51 |
|
| 52 |
def grade_task1(episode_history):
|
| 53 |
"""
|
|
|
|
| 66 |
score = days_in_range / len(episode_history)
|
| 67 |
return round(score, 2)
|
| 68 |
|
|
|
|
|
|
|
| 69 |
# TASK 2 GRADER β Medium (14 days)
|
|
|
|
| 70 |
|
| 71 |
def grade_task2(episode_history):
|
| 72 |
"""
|
|
|
|
| 82 |
for record in episode_history:
|
| 83 |
daily = compute_reward(
|
| 84 |
record.get("soil_moisture", 0),
|
| 85 |
+
health_to_number(record.get("crop_health", "fair")),
|
| 86 |
record.get("water_action", 0),
|
| 87 |
record.get("rainfall", 0)
|
| 88 |
)
|
|
|
|
| 91 |
score = total_reward / max_possible if max_possible > 0 else 0.0
|
| 92 |
return round(max(0.0, min(1.0, score)), 2)
|
| 93 |
|
|
|
|
|
|
|
| 94 |
# TASK 3 GRADER β Hard (30 days)
|
|
|
|
| 95 |
|
| 96 |
def grade_task3(episode_history):
|
| 97 |
"""
|
|
|
|
| 107 |
for record in episode_history:
|
| 108 |
day = record.get("day", 1)
|
| 109 |
moisture = record.get("soil_moisture", 0)
|
| 110 |
+
crop_health = health_to_number(record.get("crop_health", "fair"))
|
| 111 |
|
| 112 |
# Each stage needs different moisture
|
| 113 |
if day <= 10: # Seedling
|
|
|
|
| 127 |
score = sum(day_scores) / len(day_scores)
|
| 128 |
return round(score, 2)
|
| 129 |
|
|
|
|
|
|
|
| 130 |
# TEST β run this file to verify
|
|
|
|
| 131 |
|
| 132 |
if __name__ == "__main__":
|
| 133 |
# Fake data to test all 3 graders
|