Feature: Yield Prediction
Relevant source files
The following files were used as context for generating this wiki page:
The Yield Prediction feature is an AI-powered system designed to provide grape farmers with predictive analytics for harvest yield, quality, and economic outcomes. It is a key component of the AI Analytics Dashboard and aims to transform the application from a reactive tool into a proactive advisory system. By analyzing historical data, current season conditions, weather patterns, and management practices, the system generates optimistic, realistic, and pessimistic yield scenarios, along with actionable recommendations and risk assessments.
This feature is part of the Phase 2 AI integration, which is marked as complete. It provides farmers with multi-factor regression analysis to forecast yield, quality, and profitability, helping them make informed decisions to optimize their operations. The user interface for this feature is located at the /crop-yield-prediction URL path.
Sources: context/PRD.md:73-76, 212-214, public/sitemap.xml:170-174, src/lib/yield-prediction.ts
System Architecture
The Yield Prediction system is composed of a front-end React component and a back-end prediction engine encapsulated within a single TypeScript module. The system does not rely on external API calls for the core prediction logic; instead, it performs all calculations on the client side.
Components
| Component | File | Description |
|---|---|---|
YieldPredictionEngine | src/lib/yield-prediction.ts | A static class that contains the core business logic for calculating yield, quality, and economic predictions. |
YieldPredictionComponent | src/components/calculators/YieldPrediction.tsx | The main React component that provides the user interface for inputting data and displaying prediction results. |
Sources: src/lib/yield-prediction.ts:213, src/components/calculators/YieldPrediction.tsx:39
Data Flow
The user interacts with the YieldPredictionComponent, which manages the state of all inputs. When the user requests a prediction, the component calls the YieldPredictionEngine.predictYield static method, passing the complete set of inputs. The engine processes this data and returns a comprehensive results object, which the component then uses to render the prediction, quality, economics, risks, and recommendations.
This diagram illustrates the data flow from user input to the final displayed prediction.
Core Logic: YieldPredictionEngine
The core of the feature resides in the YieldPredictionEngine class. It exposes a single static method, predictYield, which orchestrates the entire prediction process.
Sources: src/lib/yield-prediction.ts:213
predictYield() Method Flow
The predictYield method follows a structured sequence of calculations to generate the final results.
This diagram shows the step-by-step process within the predictYield method.
Sources: src/lib/yield-prediction.ts:214-243
Adjustment Factors
The engine adjusts a base yield by calculating several factors. Each factor is a multiplier derived from specific input data.
| Factor | Calculation Logic | Source File |
|---|---|---|
| Weather | Compares current season temperature, rainfall, and sunlight hours to optimal values. Adjusts for variety-specific heat and drought tolerance. | src/lib/yield-prediction.ts:333-366 |
| Management | Evaluates pruning intensity, irrigation amount, fertilization, and canopy management against predefined multipliers. | src/lib/yield-prediction.ts:368-392 |
| Soil | Assesses organic matter, nutrient balance (N, P, K), pH, and drainage against optimal values. | src/lib/yield-prediction.ts:394-419 |
| Variety | Applies a tradeoff factor based on the selected grape variety and the target quality (premium, standard, bulk). | src/lib/yield-prediction.ts:421-434 |
| Vine Age | Applies a multiplier based on the age of the vines, with different factors for young, mature, and old vines. | src/lib/yield-prediction.ts:436-448 |
The final adjusted yield is calculated by multiplying the base yield by all these factors.
Adjusted Yield = Base Yield * Weather * Management * Soil * Variety * Vine Age
Sources: src/lib/yield-prediction.ts:454-455
Variety-Specific Parameters
The engine uses a constant VARIETY_PARAMETERS to store base yield, quality tradeoffs, and tolerance levels for different grape varieties. This allows the model to be tailored to the specific grape being cultivated.
| Variety | Base Yield (kg/ha) | Quality/Yield Tradeoff | Heat Tolerance | Drought Tolerance |
|---|---|---|---|---|
cabernet_sauvignon | 12000 | 0.85 | 0.8 | 0.9 |
chardonnay | 14000 | 0.75 | 0.6 | 0.7 |
pinot_noir | 10000 | 0.90 | 0.4 | 0.5 |
merlot | 13000 | 0.80 | 0.7 | 0.8 |
sauvignon_blanc | 15000 | 0.70 | 0.5 | 0.6 |
riesling | 16000 | 0.65 | 0.3 | 0.4 |
Sources: src/lib/yield-prediction.ts:176-211
Data Models & Interfaces
The feature relies on a set of well-defined interfaces to structure its inputs and outputs.
This class diagram shows the relationships between the main data interfaces used in the yield prediction feature.
Sources: src/lib/yield-prediction.ts:1-174
YieldPredictionInputs
This interface defines the complete set of data required by the prediction engine.
| Property | Type | Description |
|---|---|---|
historicalData | HistoricalYieldData[] | An array of data from previous years. |
currentSeasonData | object | Data for the current growing season, including vine age, variety, weather, and planned management. |
economicFactors | object | Economic parameters like target price and production costs. |
Sources: src/lib/yield-prediction.ts:50-69
YieldPredictionResults
This interface encapsulates all outputs from the prediction engine.
| Property | Type | Description |
|---|---|---|
prediction | YieldPredictionModel | Contains the base yield, adjustments, and optimistic/realistic/pessimistic scenarios. |
quality | QualityPrediction | Predicted sugar content, acidity, overall quality score, and optimal harvest window. |
economics | EconomicAnalysis | Projections for revenue, costs, profitability, and ROI. |
riskFactors | object[] | A list of identified risks and potential mitigation strategies. |
recommendations | object[] | Actionable recommendations for irrigation, nutrition, etc. |
confidence | number | A score (0-100) indicating the model's confidence in the prediction. |
dataQuality | object | An assessment of the input data's completeness and relevance. |
Sources: src/lib/yield-prediction.ts:143-174
User Interface: YieldPredictionComponent
The UI is a multi-tabbed interface that guides the user through the data input process and presents the results in a structured format.
Sources: src/components/calculators/YieldPrediction.tsx:39
UI Structure
The component uses a Tabs component from shadcn/ui to organize the user journey into five distinct sections:
- Setup: Basic vineyard configuration and economic parameters.
- Historical Data: Interface to add and view data from previous seasons.
- Current Season: Inputs for current weather and planned management practices.
- Prediction: The main results tab, showing yield scenarios, quality predictions, risks, and recommendations.
- Economics: Detailed breakdown of revenue, cost, profitability, and ROI.
Sources: src/components/calculators/YieldPrediction.tsx:361-367
State Management
The component uses the useState hook to manage all user inputs and the final prediction results.
inputs: A state variable of typeYieldPredictionInputsholds all data entered by the user across the different tabs.results: A state variable of typeYieldPredictionResults | nullstores the output from theYieldPredictionEngine. It is initiallynulland gets populated after the prediction is generated.isCalculating: A boolean state to manage the loading state while the prediction is being computed.
Sources: src/components/calculators/YieldPrediction.tsx:41-60, 317
Related Analytics
While the YieldPredictionEngine performs a forward-looking forecast, the AnalyticsService provides a backward-looking analysis of yield. The calculateYieldAnalysis method in analytics-service.ts calculates current yield per hectare, compares it to regional and optimal benchmarks, and identifies historical trends. This complements the predictive feature by grounding it in historical performance analysis.
Sources: src/lib/analytics-service.ts:153-201
Conclusion
The Yield Prediction feature is a sophisticated client-side calculation engine that provides comprehensive forecasting for grape farming. It integrates agronomic principles (vine age, soil, weather) with management practices and economic factors to deliver a multi-faceted prediction. The system is designed to be data-driven, with its confidence and accuracy improving as more historical data is provided. By encapsulating the logic within the YieldPredictionEngine and providing a clear UI via the YieldPredictionComponent, the feature empowers farmers with the insights needed to optimize yield, quality, and profitability.