Spaces:
Sleeping
Sleeping
Download my_env/baseline.py from SheSync/meta-hackathon-project: direct link, hf CLI and curl.
- Browser
- Download file 7.06 kB
-
https://huggingface.co/spaces/SheSync/meta-hackathon-project/resolve/main/my_env/baseline.py
- Command line
-
hf download hf://spaces/SheSync/meta-hackathon-project/my_env/baseline.py
-
curl -L -o baseline.py https://huggingface.co/spaces/SheSync/meta-hackathon-project/resolve/main/my_env/baseline.py
7.06 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. | |
| """ | |
| Baseline Inference Script for Smart Farm Irrigation Environment. | |
| This script runs a simple rule-based agent through all 3 tasks | |
| and produces reproducible baseline scores. | |
| The agent uses smart rules considering BOTH moisture AND temperature: | |
| - Hot day (>=38C) + dry soil β water more | |
| - Rainy day (>15mm) β don't water | |
| - Normal rules based on moisture level | |
| Usage: | |
| python baseline.py | |
| python baseline.py --city Mumbai | |
| python baseline.py --city Delhi --task 1 | |
| """ | |
| import argparse | |
| import sys | |
| import os | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from server.my_env_environment import FarmEnvironment | |
| from graders import grade_task1, grade_task2, grade_task3 | |
| from tasks import get_all_tasks | |
| def simple_agent(observation: dict) -> str: | |
| """ | |
| A smart rule-based agent that decides how much to water | |
| based on soil moisture, temperature AND rainfall. | |
| Rules: | |
| - Heavy rain (>15mm) β no water (already raining!) | |
| - Very hot (>=38C) + dry β water high | |
| - Very hot (>=38C) + okay β water medium | |
| - Dry (<40%) β water high | |
| - Slightly dry (<55%) β water medium | |
| - Slightly moist (<65%) β water low | |
| - Good moisture (>=65%) β no water | |
| Args: | |
| observation: Current farm state dictionary | |
| Returns: | |
| water_amount string: "none"/"low"/"medium"/"high" | |
| """ | |
| moisture = observation.get("soil_moisture", 50) | |
| rainfall = observation.get("rainfall", 0) | |
| temperature = observation.get("temperature", 30) | |
| # Rule 1 β Don't water if already raining heavily | |
| if rainfall > 15: | |
| return "none" | |
| # Rule 2 β Very hot day needs more water | |
| if temperature >= 38: | |
| if moisture < 45: | |
| return "high" | |
| elif moisture < 60: | |
| return "medium" | |
| elif moisture < 70: | |
| return "low" | |
| else: | |
| return "none" | |
| # Rule 3 β Warm day normal rules | |
| if temperature >= 30: | |
| if moisture < 40: | |
| return "high" | |
| elif moisture < 55: | |
| return "medium" | |
| elif moisture < 65: | |
| return "low" | |
| else: | |
| return "none" | |
| # Rule 4 β Cool day needs less water | |
| if moisture < 35: | |
| return "medium" | |
| elif moisture < 50: | |
| return "low" | |
| else: | |
| return "none" | |
| def run_task(env, task_id: int, city: str = "Indore") -> dict: | |
| """ | |
| Runs the agent through a single task and returns results. | |
| """ | |
| task_config = { | |
| 1: {"max_steps": 7, "name": "Basic Moisture Control"}, | |
| 2: {"max_steps": 14, "name": "Weather Adaptive Irrigation"}, | |
| 3: {"max_steps": 30, "name": "Full Season Management"}, | |
| } | |
| config = task_config[task_id] | |
| max_steps = config["max_steps"] | |
| task_name = config["name"] | |
| print(f"\n{'='*50}") | |
| print(f"Running Task {task_id}: {task_name}") | |
| print(f"City: {city} | Max Steps: {max_steps}") | |
| print(f"{'='*50}") | |
| # Reset environment | |
| obs = env.reset(city=city) | |
| obs_dict = { | |
| "temperature": obs.temperature, | |
| "rainfall": obs.rainfall, | |
| "soil_moisture": obs.soil_moisture, | |
| "crop_health": obs.crop_health.value, | |
| "day_number": obs.day_number, | |
| "crop_stage": obs.crop_stage.value, | |
| } | |
| episode_history = [] | |
| for step in range(max_steps): | |
| # Agent decides action | |
| water_amount = simple_agent(obs_dict) | |
| action_map = { | |
| "none": 0, | |
| "low": 1, | |
| "medium": 2, | |
| "high": 3 | |
| } | |
| # Record this step BEFORE taking action | |
| episode_history.append({ | |
| "day": obs_dict["day_number"], | |
| "soil_moisture": obs_dict["soil_moisture"], | |
| "crop_health": obs_dict["crop_health"], | |
| "water_action": action_map[water_amount], | |
| "rainfall": obs_dict["rainfall"], | |
| "temperature": obs_dict["temperature"], | |
| "crop_stage": obs_dict["crop_stage"], | |
| }) | |
| print(f"Day {obs_dict['day_number']:2d} | " | |
| f"Moisture: {obs_dict['soil_moisture']:5.1f}% | " | |
| f"Temp: {obs_dict['temperature']:4.1f}C | " | |
| f"Rain: {obs_dict['rainfall']:4.1f}mm | " | |
| f"Action: {water_amount}") | |
| # Take action | |
| from models import FarmAction, WaterAmount | |
| action = FarmAction(water_amount=WaterAmount(water_amount)) | |
| result = env.step(action) | |
| # Check if done | |
| if result.done: | |
| break | |
| # Update observation for next step | |
| obs_dict = { | |
| "temperature": result.temperature, | |
| "rainfall": result.rainfall, | |
| "soil_moisture": result.soil_moisture, | |
| "crop_health": result.crop_health.value, | |
| "day_number": result.day_number, | |
| "crop_stage": result.crop_stage.value, | |
| } | |
| # Grade the episode | |
| graders = { | |
| 1: grade_task1, | |
| 2: grade_task2, | |
| 3: grade_task3, | |
| } | |
| score = graders[task_id](episode_history) | |
| print(f"\nTask {task_id} Final Score: {score}") | |
| return { | |
| "task_id": task_id, | |
| "task_name": task_name, | |
| "score": score, | |
| "steps_completed": len(episode_history), | |
| "episode_history": episode_history, | |
| } | |
| def main(city: str = "Indore", task_id: int = None): | |
| """ | |
| Main function β runs agent through all 3 tasks. | |
| """ | |
| print("\n" + "="*50) | |
| print(" SMART FARM IRRIGATION β BASELINE SCORES") | |
| print("="*50) | |
| print(f"City: {city}") | |
| print(f"Agent: Smart Rule-Based Agent (moisture + temperature)") | |
| env = FarmEnvironment() | |
| tasks_to_run = [task_id] if task_id else [1, 2, 3] | |
| results = [] | |
| for tid in tasks_to_run: | |
| result = run_task(env, tid, city=city) | |
| results.append(result) | |
| print("\n" + "="*50) | |
| print(" FINAL BASELINE SCORES") | |
| print("="*50) | |
| for result in results: | |
| print(f"Task {result['task_id']} ({result['task_name']}): " | |
| f"{result['score']}") | |
| avg = sum(r["score"] for r in results) / len(results) | |
| print(f"\nAverage Score: {round(avg, 2)}") | |
| print("="*50) | |
| return results | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser( | |
| description="Run baseline agent on Smart Farm Environment" | |
| ) | |
| parser.add_argument( | |
| "--city", | |
| type=str, | |
| default="Indore", | |
| help="City name for weather data (default: Indore)" | |
| ) | |
| parser.add_argument( | |
| "--task", | |
| type=int, | |
| default=None, | |
| choices=[1, 2, 3], | |
| help="Run specific task only (default: run all tasks)" | |
| ) | |
| args = parser.parse_args() | |
| main(city=args.city, task_id=args.task) |