Wednesday, December 3, 2025

#7 Agricultural Decision Making using Python code

 Here is a clear and simple explanation of how the outputs from your time-series analysis (trend, prediction, seasonal pattern, residuals, RMSE, Mann–Kendall test) can be used for practical agricultural decision-making.

Short sentences. Simple language. Neutral tone.


How These Outputs Help in Agriculture

1. Trend Analysis → Long-Term Planning

Trend shows whether a variable is rising or falling over years.

Useful for

  • Water demand planning

    • Increasing trend → more irrigation water needed.

    • Decreasing trend → improved efficiency or reduced crop area.

  • Crop yield forecasting

    • Rising trend → stable or improving practices.

    • Falling trend → soil issues, climate stress.

  • Pest and disease monitoring

    • Upward trend → need for early preventive action.


2. Seasonal Decomposition → Timing of Agricultural Activities

Seasonality shows repeating patterns within a year.

Useful for

  • Irrigation scheduling

    • Identify months of peak water need.

  • Fertilizer and pesticide planning

    • Plan for months with high crop stress.

  • Harvest planning

    • Know peak growth periods.

  • Labour management

    • Demand prediction based on seasonal peaks.


3. Predictions → Actionable Forecasts

Short-term and long-term predictions help farmers and planners prepare.

Useful for

  • Water storage and canal operation

    • Predict water requirement for coming months.

  • Market price planning

    • Estimate expected supply.

  • Selecting crop varieties

    • If temperature or rainfall prediction is low/high.

  • Risk management

    • Prepare for drought or heavy rain conditions.


4. Mann–Kendall Test → Evidence-Based Policy Decisions

This test confirms if a trend is statistically meaningful.

Useful for

  • Government planning

    • Justify irrigation projects with scientific evidence.

  • Climate adaptation decisions

    • If decreasing rainfall trend is significant → shift cropping pattern.

  • Water allocation rules

    • Identify areas that need more support.


5. Residual Analysis → Model Reliability

Residuals show how well the model fits.

Useful for

  • Checking forecast trustworthiness

    • Random residuals → reliable model.

    • Patterned residuals → hidden climate or soil factors.

  • Identifying unusual years

    • Extreme deviations → flood, drought, pest outbreak.

This helps in risk planning and crop insurance analysis.


6. RMSE & MAE → Selecting Best Model for Decisions

Accuracy metrics help compare models.

Useful for

  • Choosing forecasting model for policy

    • Lower RMSE → more reliable.

  • Confidence level in water budgeting

    • High error → avoid risky decisions.

  • Comparing multiple crops or regions

    • Identify where forecasting is easy or difficult.


How Administrators/Farmers Can Use This Together

Example 1: Irrigation Department

  • Trend → long-term water requirement growing.

  • Seasonal pattern → peak need in Feb–Apr.

  • Prediction → next year demand will be higher.

  • Mann–Kendall → trend is significant.

  • RMSE → model is reliable.

Decision: Increase reservoir storage and canal release before summer.


Example 2: Crop Planning

  • Trend shows rainfall decreasing.

  • Predictions indicate low rainfall next year.

  • Seasonal decomposition confirms short monsoon period.

  • Mann–Kendall test shows significant decline.

Decision: Shift to drought-resistant crops.


Example 3: Fertilizer Use

  • Seasonal component shows nutrient demand peaks in specific months.

  • Predictions show higher stress in next season.

Decision: Increase fertilizer availability during peak demand.


Example 4: Pest Management

  • Trend rising → pest population increasing.

  • Seasonal peaks match specific months.

  • Predictions indicate upcoming outbreak.

Decision: Pre-spray advisories and biological control measures.


Final Summary

Your model outputs help in:

  • Long-term agricultural policy

  • Crop choice

  • Irrigation planning

  • Fertilizer schedule

  • Pest and disease control

  • Risk management

  • Climate adaptation

  • Market forecasting

They convert raw data into actionable decisions.


Below is clean, simple, single-file Python code that reads your model output Excel file (with Actual, Predicted, Trend, Seasonality, Residuals, RMSE, MAE, MK-test results) and auto-generates agricultural decisions for the four examples:

  • Example 1 – Irrigation Planning

  • Example 2 – Crop Planning

  • Example 3 – Fertilizer Scheduling

  • Example 4 – Pest Management

Short sentences. Simple language.

You can run this as agri_decision_engine.py.


Python Code: Agricultural Decision Generator

import pandas as pd

def load_model_output(file_path):
    """Load Excel model output."""
    return pd.read_excel(file_path)


# -----------------------------------------------------------
# 1. Irrigation Planning Decision
# -----------------------------------------------------------
def irrigation_decision(df):
    trend_slope = df["Trend"].dropna().diff().mean()
    predicted_next = df["Predicted"].iloc[-1]
    season_peak_month = df["Seasonal"].idxmax()

    msg = []

    # Trend-based decision
    if trend_slope > 0:
        msg.append("Water demand is rising. Increase storage and canal release planning.")
    elif trend_slope < 0:
        msg.append("Water demand is falling. Storage pressure is lower.")
    else:
        msg.append("Water demand is stable.")

    # Prediction-based decision
    if predicted_next > df["Actual"].mean():
        msg.append("Next season water requirement is high. Prepare early.")
    else:
        msg.append("Next season water requirement is average.")

    # Seasonal need
    msg.append(f"Peak water demand occurs around data index {season_peak_month}.")

    return "\n".join(msg)


# -----------------------------------------------------------
# 2. Crop Planning Decision
# -----------------------------------------------------------
def crop_planning_decision(df):
    trend_slope = df["Trend"].dropna().diff().mean()
    mk_result = df["MK_Trend"].iloc[0] if "MK_Trend" in df.columns else "no-data"

    msg = []

    # Long-term climate trend
    if trend_slope < 0:
        msg.append("Rainfall decreasing. Prefer drought-tolerant crops.")
    elif trend_slope > 0:
        msg.append("Rainfall increasing. Water-intensive crops are suitable.")
    else:
        msg.append("Rainfall stable. Normal crop planning can continue.")

    # Mann–Kendall significance
    if mk_result == "significant-decrease":
        msg.append("Trend is significant. Shift cropping pattern immediately.")
    elif mk_result == "significant-increase":
        msg.append("Trend is significant. Expect higher rainfall.")

    return "\n".join(msg)


# -----------------------------------------------------------
# 3. Fertilizer Scheduling Decision
# -----------------------------------------------------------
def fertilizer_decision(df):
    seasonal = df["Seasonal"]
    peak_index = seasonal.idxmax()

    msg = [
        f"Peak nutrient demand is expected near data index {peak_index}.",
        "Schedule fertilizers before this peak month.",
    ]

    if seasonal.std() > 0.5:
        msg.append("Seasonality is strong. Follow strict fertilizer schedule.")
    else:
        msg.append("Seasonality is mild. Standard schedule is enough.")

    return "\n".join(msg)


# -----------------------------------------------------------
# 4. Pest/Disease Management Decision
# -----------------------------------------------------------
def pest_management_decision(df):
    trend_slope = df["Trend"].dropna().diff().mean()
    residuals = df["Residuals"]

    msg = []

    # Trend
    if trend_slope > 0:
        msg.append("Risk of pest increase. Plan preventive spraying.")
    else:
        msg.append("Pest pressure stable or decreasing.")

    # Residual pattern → anomalies/outbreaks
    if residuals.abs().max() > residuals.std() * 2:
        msg.append("Unusual variation detected. Possible outbreak year.")

    return "\n".join(msg)


# -----------------------------------------------------------
# Main Driver
# -----------------------------------------------------------
def generate_decision_report(file_path, output_path="agri_decision_report.txt"):
    df = load_model_output(file_path)

    report = []
    report.append("=== Irrigation Planning Decision ===\n" + irrigation_decision(df) + "\n")
    report.append("=== Crop Planning Decision ===\n" + crop_planning_decision(df) + "\n")
    report.append("=== Fertilizer Scheduling Decision ===\n" + fertilizer_decision(df) + "\n")
    report.append("=== Pest Management Decision ===\n" + pest_management_decision(df) + "\n")

    final_report = "\n".join(report)

    with open(output_path, "w") as f:
        f.write(final_report)

    print("\nReport Generated:", output_path)
    print("\n--- Summary ---\n")
    print(final_report)


# -----------------------------------------------------------
# Run Example
# -----------------------------------------------------------
if __name__ == "__main__":
    input_excel = "model_output.xlsx"  # change file name
    generate_decision_report(input_excel)

Input Expected (model_output.xlsx)

Your Excel must contain these columns:

Column Name Meaning
Actual Real observed values
Predicted Model forecast
Trend Trend component
Seasonal Seasonal component
Residuals Model residuals
MK_Trend "significant-increase" / "significant-decrease" / "none"

Works with any number of rows.


Output (agri_decision_report.txt)

Example output:

=== Irrigation Planning Decision ===
Water demand is rising. Increase storage and canal release planning.
Next season water requirement is high. Prepare early.
Peak water demand occurs around data index 5.

=== Crop Planning Decision ===
Rainfall decreasing. Prefer drought-tolerant crops.
Trend is significant. Shift cropping pattern immediately.

=== Fertilizer Scheduling Decision ===
Peak nutrient demand is expected near data index 3.
Schedule fertilizers before this peak month.
Seasonality is strong. Follow strict fertilizer schedule.

=== Pest Management Decision ===
Risk of pest increase. Plan preventive spraying.
Unusual variation detected. Possible outbreak year.

If you want

I can also add:

✅ PDF report
✅ Plots in report
✅ Dashboard UI
✅ Integration inside your existing rain-project app
✅ SMS alerts or mobile format

Tell me your choice!

No comments:

Post a Comment

#8 Inferences and Agri Action oriented Decisions

 Below is a complete, clean, single-file Streamlit app that: Loads a model output Excel (or multiple files) which contains model output...