CoolFace
Apppublic

jeffrey1963/Cattle-Elk-R5

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
feedback_fcns.py168 linesDownload Raw Back to root
1import os2import random3import numpy as np4import matplotlib.pyplot as plt5from openai import OpenAI6from Sim_Engine import simulate_period7 8client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))9 10def summarize_initial_conditions(n_rows, n_cols):11    num_parcels = n_rows * n_cols12    avg_forage = round(random.uniform(6.5, 8.0), 1)13    degraded_pct = round(random.uniform(0.0, 2.0), 1)14    riparian_health = random.choice(["excellent", "moderate", "fragile"])15    elk_corridor_status = random.choice([16        "completely intact and lightly used",17        "intact but under slight pressure from cattle movement",18        "showing signs of fragmentation near key crossings"19    ])20    rainfall_outlook = random.choice(["normal", "below average", "above average"])21 22    return (23        f"There are {num_parcels} parcels in total. Grazing has not yet occurred.\n"24        f"Average forage availability is {avg_forage} AUMs per parcel, with about {degraded_pct}% of land already degraded due to prior conditions.\n"25        f"Riparian zone condition is {riparian_health}, and the elk movement corridor is {elk_corridor_status}.\n"26        f"The seasonal rainfall outlook is {rainfall_outlook}."27    )28 29def plot_forage_map_to_file(parcel_dict, n_rows, n_cols, title="Forage Map", save_path="forage_map.png"):30    forage_map = np.array([31        [parcel_dict[(i, j)]["forage"] for j in range(n_cols)]32        for i in range(n_rows)33    ])34    fig, ax = plt.subplots(figsize=(8, 6))35    cax = ax.imshow(forage_map, cmap='YlGn', origin='upper')36    fig.colorbar(cax, label="Forage AUMs")37    ax.set_title(title)38    ax.axis('off')39    plt.tight_layout()40    plt.savefig(save_path)41    plt.close(fig)42 43def elk_feedback(plan_choice, current_summary):44    prompt = f"""45You represent a coalition of elk-related interests: conservationists, hunting advocates, and the hospitality/lodging industry.46A student has selected the **'{plan_choice}'** cattle grazing strategy. Below are the current ecological conditions:47-----48{current_summary}49-----50Please do the following:51- Explicitly choose **one elk management strategy** from the list:52  - **Preserve**: strict elk protections, no hunting, unrestricted movement53  - **Cooperate**: shared use corridor, some riparian restrictions, sustainable elk population54  - **Exploit**: prioritize hunting/tourism, tolerate reduced elk numbers and access55- Reflect each group's view briefly, but unify the final position.56- Justify your strategy choice based on the above ecological indicators.57"""58    response = client.chat.completions.create(59        model="gpt-3.5-turbo",60        messages=[{"role": "user", "content": prompt}],61        temperature=0.862    )63    return response.choices[0].message.content64 65def usfs_feedback(plan_choice, student_essay, current_summary):66    # Extract the AUM line from the summary67    aum_line = ""68    for line in current_summary.split("\n"):69        if "Average forage availability" in line:70            aum_line = line.strip()71            break72 73    prompt = f"""74You are a USFS land management agent evaluating a student’s cattle grazing proposal.75 76The student selected the **'{plan_choice}'** strategy and submitted this justification:77-----78{student_essay}79-----80 81Here are the current rangeland conditions:82-----83{current_summary}84-----85 86🚨 **Must Include Block**:87You must include this sentence exactly in your response:88→ "{aum_line}"89 90Then provide your evaluation:91- Comment on forage, degradation, riparian and corridor health92- State whether the plan is ecologically sound93- Suggest improvements if needed94- Keep the tone professional, clear, and grounded in the data95"""96 97    response = client.chat.completions.create(98        model="gpt-3.5-turbo",99        messages=[{"role": "user", "content": prompt}],100        temperature=0.7101    )102    return response.choices[0].message.content103 104def simulate_and_summarizeold(plan_choice, round_counter, parcel_dict, parcel_map, cluster_labels, n_rows, n_cols, elk_pressure):105    # Interpret strategy106    strategy_map = {107        "conservative": "conservative",108        "normal": "moderate",109        "aggressive": "aggressive"110    }111    strategy = strategy_map.get(plan_choice.lower(), "moderate")112 113    # ✅ Reuse incoming parcel_dict — do not reset114    simulate_period(parcel_dict, grazing_strategy=strategy, elk_pressure=elk_pressure)115 116    # Extract summary117    forage_vals = [p["forage"] for p in parcel_dict.values()]118    avg_forage = sum(forage_vals) / len(forage_vals)119    degraded_pct = 100 * sum(p["health"] < 0.5 for p in parcel_dict.values()) / len(parcel_dict)120 121    summary = (122        f"After Round {round_counter} with the '{plan_choice}' plan:\n"123        f"Avg forage: {avg_forage:.1f} AUMs, Parcels with low health (<0.5): {degraded_pct:.1f}%"124    )125 126    # Generate map visuals127    from Sim_Engine import get_forage_map, get_health_map, plot_forage_map, plot_health_map128    forage_map = get_forage_map(parcel_dict, n_rows, n_cols)129    health_map = get_health_map(parcel_dict, n_rows, n_cols)130    plot_forage_map(forage_map, title=f"Forage Map (Round {round_counter})", save_path="forage_map.png")131    plot_health_map(health_map, title=f"Health Map (Round {round_counter})", save_path="health_map.png")132 133    return summary, "forage_map.png", "health_map.png", round_counter + 1, parcel_dict134 135def simulate_and_summarize(plan_choice, round_counter, parcel_map, cluster_labels, n_rows, n_cols, run_full_simulation, history):136 137    strategy_map = {138        "conservative": "conservative",139        "normal": "moderate",140        "aggressive": "aggressive"141    }142    strategy = strategy_map.get(plan_choice.lower())143    parcel_dict = run_full_simulation(parcel_map, cluster_labels, n_rows, n_cols, strategy=strategy)144 145    plot_forage_map_to_file(parcel_dict, n_rows, n_cols, title=f"Round {round_counter} Forage Map")146 147    # ✅ ADD THIS BLOCK148    from Sim_Engine import get_health_map, plot_health_map149    health_map = get_health_map(parcel_dict, n_rows, n_cols)150    plot_health_map(health_map, title=f"Round {round_counter} Health Map", save_path="health_map.png")151 152    153    forage_vals = [p["forage"] for p in parcel_dict.values()]154    avg_forage = sum(forage_vals) / len(forage_vals)155    degraded_pct = 100 * sum(p["degraded"] for p in parcel_dict.values()) / len(parcel_dict)156 157    summary = (158        f"After Round {round_counter} with the '{plan_choice}' plan:\n"159        f"Avg forage: {avg_forage:.1f} AUMs, Degraded parcels: {degraded_pct:.1f}%"160    )161    return summary, "forage_map.png", "health_map.png", round_counter + 1162 163 164def full_response(plan_choice, essay_text, current_summary):165    elk_resp = elk_feedback(plan_choice, current_summary)166    usfs_resp = usfs_feedback(plan_choice, essay_text, current_summary)167    return elk_resp, usfs_resp168