Subelinha commited on
Commit
a22636b
·
verified ·
1 Parent(s): 8590fce

Upload 6 files

Browse files
huggingface_upload_package/README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Wine Production Predictor
3
+ emoji: 🍷
4
+ colorFrom: blue
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 6.19.0
8
+ python_version: '3.13'
9
+ app_file: app.py
10
+ pinned: false
11
+ short_description: Predict annual wine production by region in Portugal
12
+ ---
13
+
14
+ # Wine Production Predictor
15
+
16
+ This Space is an interactive prototype for the Practical Machine Learning final
17
+ project on Portuguese wine-production forecasting.
18
+
19
+ It estimates experimental 2026/27 wine production by viticultural region using
20
+ official IVV data, lagged production features, vineyard area, rolling-origin
21
+ validation, and a one-step-ahead forecasting workflow.
22
+
23
+ ## What the app does
24
+
25
+ - Selects the best one-step-ahead model using rolling validation from
26
+ 2018 to 2022.
27
+ - Reports final one-step-ahead test metrics for 2023 to 2025.
28
+ - Forecasts 2026/27 production for each Portuguese wine region.
29
+ - Allows the user to adjust vineyard area as a scenario input.
30
+ - Shows an empirical uncertainty band around the predicted production.
31
+
32
+ ## Important interpretation
33
+
34
+ The vineyard-area input creates a scenario, not a causal estimate. Changing the
35
+ area in the interface shows how the model output changes under that assumption;
36
+ it does not prove that changing vineyard area would directly cause the predicted
37
+ production change.
38
+
39
+ The 90% interval shown by the app is empirical and based on observed validation
40
+ errors. It is a practical uncertainty indication, not a formal statistical
41
+ confidence interval.
42
+
43
+ ## Related repository
44
+
45
+ Main project repository:
46
+ <https://github.com/oxedanda/pml_final_project>
huggingface_upload_package/app.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interactive Gradio app for the experimental wine-production forecast.
2
+
3
+ Run from the repository root with:
4
+ python src/app.py
5
+
6
+ The app is intentionally a visual prototype. It uses the same forecasting logic
7
+ as ``src/future_forecast.py`` and does not make causal claims about vineyard
8
+ area changes.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import pandas as pd
14
+ import gradio as gr
15
+
16
+ try:
17
+ from future_forecast import evaluate_forecasters, forecast_2026, load_history
18
+ except ModuleNotFoundError:
19
+ from src.future_forecast import evaluate_forecasters, forecast_2026, load_history
20
+
21
+
22
+ def format_forecast_table(data: pd.DataFrame) -> pd.DataFrame:
23
+ """Return a human-readable forecast table for display in Gradio."""
24
+ view = data.copy()
25
+ numeric_columns = [
26
+ "vineyard_area_ha",
27
+ "predicted_production_hl",
28
+ "lower_90_hl",
29
+ "upper_90_hl",
30
+ ]
31
+ for column in numeric_columns:
32
+ if column in view.columns:
33
+ view[column] = view[column].map(
34
+ lambda value: f"{value:,.0f}" if pd.notna(value) else ""
35
+ )
36
+
37
+ return view.rename(
38
+ columns={
39
+ "region": "Region",
40
+ "year_start": "Year",
41
+ "vineyard_area_ha": "Area (ha)",
42
+ "selected_model": "Selected model",
43
+ "predicted_production_hl": "Predicted production (hl)",
44
+ "lower_90_hl": "Lower empirical 90% (hl)",
45
+ "upper_90_hl": "Upper empirical 90% (hl)",
46
+ }
47
+ )
48
+
49
+
50
+ history = load_history()
51
+ evaluation = evaluate_forecasters()
52
+ base_forecast = forecast_2026(evaluation=evaluation)
53
+
54
+ latest_area = (
55
+ history.sort_values(["region", "year_start"])
56
+ .groupby("region", as_index=False)
57
+ .tail(1)[["region", "vineyard_area_ha"]]
58
+ )
59
+
60
+ region_choices = sorted(base_forecast["region"].astype(str).unique().tolist())
61
+ default_region = region_choices[0]
62
+ area_map = dict(zip(latest_area["region"].astype(str), latest_area["vineyard_area_ha"]))
63
+
64
+ validation_metrics = (
65
+ evaluation.metrics.query("split == 'rolling_validation_2018_2022'")
66
+ .sort_values("MAE")
67
+ .reset_index(drop=True)
68
+ )
69
+ test_metrics = (
70
+ evaluation.metrics.query("split == 'test_2023_2025'")
71
+ .sort_values("MAE")
72
+ .reset_index(drop=True)
73
+ )
74
+
75
+
76
+ def update_area(region: str):
77
+ """Reset the area input to the latest observed area for the chosen region."""
78
+ return gr.update(value=round(float(area_map.get(region, 0.0)), 2))
79
+
80
+
81
+ def simulate(region: str, area_ha: float):
82
+ """Forecast one region under the selected vineyard-area scenario."""
83
+ if not region:
84
+ raise gr.Error("Please choose a region.")
85
+ if area_ha is None or area_ha <= 0:
86
+ raise gr.Error("Area (ha) must be greater than 0.")
87
+
88
+ result = forecast_2026(
89
+ evaluation=evaluation,
90
+ area_overrides={region: float(area_ha)},
91
+ )
92
+ selected = result[result["region"] == region].copy().reset_index(drop=True)
93
+ if selected.empty:
94
+ raise gr.Error(f"No forecast returned for region: {region}")
95
+
96
+ row = selected.iloc[0]
97
+ summary = f"""
98
+ <div class="summary-card">
99
+ <h3>Forecast summary</h3>
100
+ <p><b>Region:</b> {row['region']}</p>
101
+ <p><b>Campaign:</b> 2026/27</p>
102
+ <p><b>Selected model:</b> {row['selected_model']}</p>
103
+ <p><b>Vineyard area scenario:</b> {row['vineyard_area_ha']:,.2f} ha</p>
104
+ <p><b>Predicted production:</b> {row['predicted_production_hl']:,.0f} hl</p>
105
+ <p><b>Empirical 90% interval:</b> {row['lower_90_hl']:,.0f}
106
+ to {row['upper_90_hl']:,.0f} hl</p>
107
+ </div>
108
+ """
109
+ return summary, format_forecast_table(selected)
110
+
111
+
112
+ custom_css = """
113
+ .gradio-container {
114
+ max-width: 1120px !important;
115
+ }
116
+ .summary-card {
117
+ border: 1px solid #ead7d7;
118
+ border-radius: 14px;
119
+ padding: 18px;
120
+ background: #fff8f8;
121
+ }
122
+ """
123
+
124
+ theme = gr.themes.Soft(primary_hue="rose", secondary_hue="orange")
125
+
126
+ with gr.Blocks(
127
+ title="Wine Production Predictor",
128
+ theme=theme,
129
+ css=custom_css,
130
+ ) as demo:
131
+ gr.Markdown(
132
+ """
133
+ # Wine Production Predictor
134
+
135
+ Experimental 2026/27 wine-production forecast by Portuguese
136
+ viticultural region.
137
+
138
+ **Important interpretation:** the vineyard-area input creates a
139
+ scenario, not a causal estimate. The empirical 90% interval is based on
140
+ observed validation errors and should not be read as a formal
141
+ statistical confidence interval.
142
+ """
143
+ )
144
+
145
+ gr.Markdown(
146
+ f"""
147
+ **Selected one-step-ahead model:** `{evaluation.selected_model}`
148
+
149
+ **Empirical 90% interval half-width:** `{evaluation.interval_half_width:,.0f} hl`
150
+ """
151
+ )
152
+
153
+ with gr.Row():
154
+ with gr.Column(scale=1):
155
+ gr.Markdown("### Simulation inputs")
156
+ region = gr.Dropdown(
157
+ choices=region_choices,
158
+ value=default_region,
159
+ label="Region",
160
+ info="Choose a Portuguese wine region.",
161
+ )
162
+ area = gr.Number(
163
+ value=round(float(area_map.get(default_region, 0.0)), 2),
164
+ label="Vineyard area (ha)",
165
+ precision=2,
166
+ info=(
167
+ "Adjust vineyard area as a scenario input; this is not a "
168
+ "causal effect estimate."
169
+ ),
170
+ )
171
+ run_button = gr.Button("Forecast 2026/27", variant="primary")
172
+
173
+ with gr.Column(scale=2):
174
+ gr.Markdown("### Prediction result")
175
+ summary = gr.HTML()
176
+ result_table = gr.Dataframe(label="Forecast result", interactive=False)
177
+
178
+ with gr.Accordion("Validation metrics", open=False):
179
+ gr.Dataframe(
180
+ value=validation_metrics[["model", "MAE", "RMSE", "R2"]],
181
+ label="Rolling validation 2018-2022",
182
+ interactive=False,
183
+ )
184
+
185
+ with gr.Accordion("Final one-step-ahead test metrics", open=False):
186
+ gr.Dataframe(
187
+ value=test_metrics[["model", "MAE", "RMSE", "R2"]],
188
+ label="Test years 2023-2025",
189
+ interactive=False,
190
+ )
191
+
192
+ with gr.Accordion("Forecast table for all regions", open=False):
193
+ gr.Dataframe(
194
+ value=format_forecast_table(base_forecast),
195
+ label="Default 2026/27 forecasts for all regions",
196
+ interactive=False,
197
+ )
198
+
199
+ region.change(fn=update_area, inputs=region, outputs=area)
200
+ run_button.click(fn=simulate, inputs=[region, area], outputs=[summary, result_table])
201
+ demo.load(fn=simulate, inputs=[region, area], outputs=[summary, result_table])
202
+
203
+
204
+ if __name__ == "__main__":
205
+ demo.launch()
huggingface_upload_package/data/processed/vineyard_area_by_region_clean.csv ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ region,year_start,vineyard_area_ha
2
+ Alentejo,1989,11510.0
3
+ Algarve,1989,2750.0
4
+ Açores,1989,2489.0
5
+ Lisboa,1989,46046.0
6
+ Madeira,1989,1803.0
7
+ P. Setúbal,1989,11396.0
8
+ Tejo,1989,28124.0
9
+ Verdes,1989,38349.0
10
+ Alentejo,1999,13457.0
11
+ Algarve,1999,1933.0
12
+ Açores,1999,1700.0
13
+ Lisboa,1999,38750.0
14
+ Madeira,1999,1603.92
15
+ P. Setúbal,1999,9367.0
16
+ Tejo,1999,23532.0
17
+ Verdes,1999,39638.0
18
+ Alentejo,2000,16123.0
19
+ Algarve,2000,2154.0
20
+ Açores,2000,1700.0
21
+ Lisboa,2000,21875.0
22
+ Madeira,2000,1512.76
23
+ P. Setúbal,2000,9283.0
24
+ Tejo,2000,29765.0
25
+ Verdes,2000,34035.0
26
+ Alentejo,2001,18420.0
27
+ Algarve,2001,2140.0
28
+ Açores,2001,1700.0
29
+ Lisboa,2001,28548.0
30
+ Madeira,2001,1512.76
31
+ P. Setúbal,2001,9253.0
32
+ Tejo,2001,21637.0
33
+ Verdes,2001,34255.0
34
+ Alentejo,2002,20760.2
35
+ Algarve,2002,2148.29
36
+ Açores,2002,1700.0
37
+ Lisboa,2002,27245.9
38
+ Madeira,2002,1512.76
39
+ P. Setúbal,2002,9309.19
40
+ Tejo,2002,21171.5
41
+ Verdes,2002,34018.4
42
+ Alentejo,2003,21691.15
43
+ Algarve,2003,2133.05
44
+ Açores,2003,1700.0
45
+ Lisboa,2003,26390.61
46
+ Madeira,2003,1512.76
47
+ P. Setúbal,2003,9052.38
48
+ Tejo,2003,20808.21
49
+ Verdes,2003,33675.82
50
+ Alentejo,2004,21740.9
51
+ Algarve,2004,2097.67
52
+ Açores,2004,1700.0
53
+ Lisboa,2004,25339.15
54
+ Madeira,2004,1512.76
55
+ P. Setúbal,2004,9041.48
56
+ Tejo,2004,20238.48
57
+ Verdes,2004,32881.09
58
+ Alentejo,2005,22654.58
59
+ Algarve,2005,2094.79
60
+ Açores,2005,1700.0
61
+ Lisboa,2005,25693.01
62
+ Madeira,2005,1512.76
63
+ P. Setúbal,2005,9209.12
64
+ Tejo,2005,20002.73
65
+ Verdes,2005,32658.57
66
+ Alentejo,2006,22958.55
67
+ Algarve,2006,2082.63
68
+ Açores,2006,1700.0
69
+ Lisboa,2006,25629.84
70
+ Madeira,2006,1512.76
71
+ P. Setúbal,2006,9203.45
72
+ Tejo,2006,19989.03
73
+ Verdes,2006,32235.79
74
+ Alentejo,2007,23490.66
75
+ Algarve,2007,2063.2
76
+ Açores,2007,1700.0
77
+ Lisboa,2007,25198.41
78
+ Madeira,2007,1512.76
79
+ P. Setúbal,2007,9282.14
80
+ Tejo,2007,19518.16
81
+ Verdes,2007,31815.54
82
+ Alentejo,2008,23089.0
83
+ Algarve,2008,2060.0
84
+ Açores,2008,1700.0
85
+ Lisboa,2008,25107.0
86
+ Madeira,2008,1426.27
87
+ P. Setúbal,2008,9313.0
88
+ Tejo,2008,19304.0
89
+ Verdes,2008,31622.0
90
+ Alentejo,2009,23490.0
91
+ Algarve,2009,1983.0
92
+ Açores,2009,1700.0
93
+ Lisboa,2009,24799.0
94
+ Madeira,2009,1458.66
95
+ P. Setúbal,2009,9210.0
96
+ Tejo,2009,18743.0
97
+ Verdes,2009,31009.7
98
+ Alentejo,2010,23784.81
99
+ Algarve,2010,1984.53
100
+ Açores,2010,1700.0
101
+ Lisboa,2010,24526.82
102
+ Madeira,2010,1423.0
103
+ P. Setúbal,2010,9181.88
104
+ Tejo,2010,18082.17
105
+ Verdes,2010,30902.52
106
+ Alentejo,2011,23903.93
107
+ Algarve,2011,1985.82
108
+ Açores,2011,1700.0
109
+ Lisboa,2011,24506.8
110
+ Madeira,2011,1435.93
111
+ P. Setúbal,2011,9195.95
112
+ Tejo,2011,17892.34
113
+ Verdes,2011,31060.31
114
+ Alentejo,2012,23438.4
115
+ Algarve,2012,1976.08
116
+ Açores,2012,1700.0
117
+ Lisboa,2012,24241.13
118
+ Madeira,2012,1433.0
119
+ P. Setúbal,2012,9010.62
120
+ Tejo,2012,17230.34
121
+ Verdes,2012,30564.92
122
+ Alentejo,2013,23204.02
123
+ Algarve,2013,1963.04
124
+ Açores,2013,1700.0
125
+ Lisboa,2013,23756.31
126
+ Madeira,2013,1090.26
127
+ P. Setúbal,2013,8740.3
128
+ Tejo,2013,16196.52
129
+ Verdes,2013,29036.68
130
+ Alentejo,2014,23188.0
131
+ Algarve,2014,1773.0
132
+ Açores,2014,1700.0
133
+ Douro,2014,43611.0
134
+ Lisboa,2014,22425.0
135
+ Madeira,2014,1071.15
136
+ P. Setúbal,2014,8622.0
137
+ T. Montes,2014,23303.0
138
+ Tejo,2014,15653.0
139
+ Verdes,2014,27432.0
140
+ Alentejo,2015,21816.0
141
+ Algarve,2015,1858.0
142
+ Açores,2015,1700.0
143
+ Douro,2015,42184.0
144
+ Lisboa,2015,20359.0
145
+ Madeira,2015,1060.55
146
+ P. Setúbal,2015,7556.0
147
+ T. Montes,2015,17788.0
148
+ Tejo,2015,13589.0
149
+ Verdes,2015,20433.0
150
+ Alentejo,2016,23375.4
151
+ Algarve,2016,1722.34
152
+ Açores,2016,1700.0
153
+ Bairrada,2016,15086.14
154
+ Beira Interior,2016,15687.02
155
+ Douro,2016,42766.28
156
+ Dão,2016,14646.57
157
+ Lisboa,2016,19186.09
158
+ Madeira,2016,1052.0
159
+ P. Setúbal,2016,7202.54
160
+ T. Montes,2016,14380.78
161
+ Tejo,2016,12873.56
162
+ Távora-Varosa,2016,2520.43
163
+ Verdes,2016,21019.73
164
+ Alentejo,2017,23878.98
165
+ Algarve,2017,1433.56
166
+ Açores,2017,1700.0
167
+ Bairrada,2017,15134.45
168
+ Beira Interior,2017,15520.46
169
+ Douro,2017,42023.42
170
+ Dão,2017,14837.46
171
+ Lisboa,2017,18640.87
172
+ Madeira,2017,1050.62
173
+ P. Setúbal,2017,7213.05
174
+ T. Montes,2017,14510.35
175
+ Tejo,2017,12221.08
176
+ Távora-Varosa,2017,2160.85
177
+ Verdes,2017,21306.89
178
+ Alentejo,2018,24544.14
179
+ Algarve,2018,1351.84
180
+ Açores,2018,1707.91
181
+ Bairrada,2018,14630.3
182
+ Beira Interior,2018,15110.47
183
+ Douro,2018,42555.81
184
+ Dão,2018,14475.99
185
+ Lisboa,2018,17989.07
186
+ Madeira,2018,1052.0
187
+ P. Setúbal,2018,7265.37
188
+ T. Montes,2018,13538.66
189
+ Tejo,2018,11943.65
190
+ Távora-Varosa,2018,2183.89
191
+ Verdes,2018,21972.97
192
+ Alentejo,2019,24709.35
193
+ Algarve,2019,1404.35
194
+ Açores,2019,1707.91
195
+ Bairrada,2019,13692.82
196
+ Beira Interior,2019,14327.97
197
+ Douro,2019,43862.69
198
+ Dão,2019,13723.06
199
+ Lisboa,2019,19287.34
200
+ Madeira,2019,1047.1
201
+ P. Setúbal,2019,7865.89
202
+ T. Montes,2019,12252.48
203
+ Tejo,2019,12517.06
204
+ Távora-Varosa,2019,2345.76
205
+ Verdes,2019,23999.45
206
+ Alentejo,2020,25056.52
207
+ Algarve,2020,1399.83
208
+ Açores,2020,1707.91
209
+ Bairrada,2020,13314.01
210
+ Beira Interior,2020,13913.72
211
+ Douro,2020,44161.6
212
+ Dão,2020,13320.94
213
+ Lisboa,2020,19638.97
214
+ Madeira,2020,1025.38
215
+ P. Setúbal,2020,7985.99
216
+ T. Montes,2020,11613.03
217
+ Tejo,2020,12750.94
218
+ Távora-Varosa,2020,2271.93
219
+ Verdes,2020,24240.29
220
+ Alentejo,2021,25460.87
221
+ Algarve,2021,1426.76
222
+ Açores,2021,1707.91
223
+ Bairrada,2021,13258.64
224
+ Beira Interior,2021,13874.26
225
+ Douro,2021,44180.26
226
+ Dão,2021,13408.87
227
+ Lisboa,2021,19869.34
228
+ Madeira,2021,681.0
229
+ P. Setúbal,2021,8026.98
230
+ T. Montes,2021,10701.41
231
+ Tejo,2021,12846.59
232
+ Távora-Varosa,2021,2214.88
233
+ Verdes,2021,24371.07
234
+ Alentejo,2022,25924.0
235
+ Algarve,2022,1442.0
236
+ Açores,2022,1708.0
237
+ Bairrada,2022,13391.0
238
+ Beira Interior,2022,14060.0
239
+ Douro,2022,43466.0
240
+ Dão,2022,13409.0
241
+ Lisboa,2022,19869.0
242
+ Madeira,2022,681.0
243
+ P. Setúbal,2022,8027.0
244
+ T. Montes,2022,9701.0
245
+ Tejo,2022,12847.0
246
+ Távora-Varosa,2022,2274.0
247
+ Verdes,2022,24371.0
248
+ Alentejo,2023,26443.0
249
+ Algarve,2023,1355.0
250
+ Açores,2023,1737.0
251
+ Bairrada,2023,9440.0
252
+ Beira Interior,2023,11738.0
253
+ Douro,2023,44224.0
254
+ Dão,2023,12898.0
255
+ Lisboa,2023,17857.0
256
+ Madeira,2023,669.0
257
+ P. Setúbal,2023,7417.0
258
+ T. Montes,2023,9419.0
259
+ Tejo,2023,11847.0
260
+ Távora-Varosa,2023,2169.0
261
+ Verdes,2023,23147.0
262
+ Alentejo,2024,26066.74
263
+ Algarve,2024,1243.59
264
+ Açores,2024,1356.41
265
+ Bairrada,2024,9304.66
266
+ Beira Interior,2024,11654.57
267
+ Douro,2024,43897.88
268
+ Dão,2024,9826.72
269
+ Lisboa,2024,17942.18
270
+ Madeira,2024,656.38
271
+ P. Setúbal,2024,7433.17
272
+ T. Montes,2024,4565.43
273
+ Tejo,2024,11973.57
274
+ Távora-Varosa,2024,2107.9
275
+ Verdes,2024,23234.49
276
+ Alentejo,2025,25421.93
277
+ Algarve,2025,1201.75
278
+ Açores,2025,1334.12
279
+ Bairrada,2025,9180.68
280
+ Beira Interior,2025,11360.82
281
+ Douro,2025,43929.72
282
+ Dão,2025,9834.17
283
+ Lisboa,2025,17819.98
284
+ Madeira,2025,645.88
285
+ P. Setúbal,2025,7355.33
286
+ T. Montes,2025,4520.63
287
+ Tejo,2025,11713.12
288
+ Távora-Varosa,2025,2072.41
289
+ Verdes,2025,23272.15
huggingface_upload_package/data/processed/wine_production_by_region_clean.csv ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ region,campaign_year,year_start,total_production_hl,dop_production_hl,igp_production_hl,year_variety_production_hl,non_certified_production_hl
2
+ Alentejo,2009/10,2009,810338,356783,449833,995,2728
3
+ Algarve,2009/10,2009,23650,4680,11797,0,7173
4
+ Açores,2009/10,2009,13754,2771,2832,6,8145
5
+ Bairrada,2009/10,2009,246705,69459,64138,1068,112041
6
+ Beira Interior,2009/10,2009,192084,50158,20570,14,121342
7
+ Douro,2009/10,2009,1351949,1186358,26986,0,138605
8
+ Dão,2009/10,2009,297483,221529,23022,0,52932
9
+ Lisboa,2009/10,2009,962323,55210,323594,0,583519
10
+ Madeira,2009/10,2009,45449,39285,223,0,5940
11
+ P. Setúbal,2009/10,2009,379371,108271,178274,507,92319
12
+ T. Montes,2009/10,2009,110614,9959,31082,0,69574
13
+ Tejo,2009/10,2009,544935,55427,104937,813,383758
14
+ Távora-Varosa,2009/10,2009,47872,14126,4907,500,28339
15
+ Verdes,2009/10,2009,866985,844162,18577,0,4246
16
+ Alentejo,2010/11,2010,1189719,449096,725657,1387,13580
17
+ Algarve,2010/11,2010,19190,5439,5608,0,8143
18
+ Açores,2010/11,2010,4783,527,599,0,3657
19
+ Bairrada,2010/11,2010,297704,85674,45904,3840,162286
20
+ Beira Interior,2010/11,2010,224735,41155,43683,1000,138897
21
+ Douro,2010/11,2010,1660408,1331976,50467,0,277965
22
+ Dão,2010/11,2010,355687,237411,34064,5203,79009
23
+ Lisboa,2010/11,2010,1204098,67503,360915,2263,773417
24
+ Madeira,2010/11,2010,36782,32290,156,0,4335
25
+ P. Setúbal,2010/11,2010,431696,115260,192981,5510,117946
26
+ T. Montes,2010/11,2010,119367,15338,23464,502,80063
27
+ Tejo,2010/11,2010,630548,64790,167191,6637,391929
28
+ Távora-Varosa,2010/11,2010,61036,21550,1994,0,37491
29
+ Verdes,2010/11,2010,912176,864977,40776,0,6423
30
+ Alentejo,2011/12,2011,969832,413347,550665,560,5261
31
+ Algarve,2011/12,2011,13150,2770,5257,0,5123
32
+ Açores,2011/12,2011,11192,1719,1568,0,7905
33
+ Bairrada,2011/12,2011,292596,84622,35018,10571,162385
34
+ Beira Interior,2011/12,2011,184759,42639,30288,1215,110618
35
+ Douro,2011/12,2011,1329423,1052363,24886,0,252174
36
+ Dão,2011/12,2011,293537,193468,30415,5916,63739
37
+ Lisboa,2011/12,2011,826666,51865,258878,752,515170
38
+ Madeira,2011/12,2011,38769,35671,177,0,2922
39
+ P. Setúbal,2011/12,2011,308857,86072,157851,2368,62566
40
+ T. Montes,2011/12,2011,102005,15871,12864,435,72835
41
+ Tejo,2011/12,2011,382276,45938,133898,6470,195971
42
+ Távora-Varosa,2011/12,2011,45959,19465,7369,0,19125
43
+ Verdes,2011/12,2011,823341,764667,42907,0,15767
44
+ Alentejo,2012/13,2012,970124,399297,503636,152,67810
45
+ Algarve,2012/13,2012,12338,3240,7086,0,2013
46
+ Açores,2012/13,2012,4991,607,625,0,3747
47
+ Bairrada,2012/13,2012,283897,73460,22683,7968,179524
48
+ Beira Interior,2012/13,2012,217693,44539,40849,0,132405
49
+ Douro,2012/13,2012,1346152,1100360,14585,33,230373
50
+ Dão,2012/13,2012,356454,227007,29541,6790,91069
51
+ Lisboa,2012/13,2012,1097712,58334,394632,1658,642695
52
+ Madeira,2012/13,2012,49637,45147,263792,0,3698
53
+ P. Setúbal,2012/13,2012,517797,136108,219979,4500,156254
54
+ T. Montes,2012/13,2012,108615,13307,18515,470,76323
55
+ Tejo,2012/13,2012,641789,63864,187066,5584,384967
56
+ Távora-Varosa,2012/13,2012,64655,20726,2743,0,41372
57
+ Verdes,2012/13,2012,655253,618242,32743,0,4268
58
+ Alentejo,2013/14,2013,1127910,470086,633255,150,24419
59
+ Algarve,2013/14,2013,11676,1668,7794,0,2214
60
+ Açores,2013/14,2013,6595,1273,973,0,4350
61
+ Bairrada,2013/14,2013,255333,71787,28633,34263,120649
62
+ Beira Interior,2013/14,2013,215783,42852,35930,0,137000
63
+ Douro,2013/14,2013,1516925,1215249,42631,0,259045
64
+ Dão,2013/14,2013,304824,195362,30702,4887,73873
65
+ Lisboa,2013/14,2013,885742,47388,503749,756,333848
66
+ Madeira,2013/14,2013,43136,40695,35,0,2405
67
+ P. Setúbal,2013/14,2013,407853,124146,190009,30,93668
68
+ T. Montes,2013/14,2013,96615,12070,7600,1204,75741
69
+ Tejo,2013/14,2013,500807,55136,159846,3030,282795
70
+ Távora-Varosa,2013/14,2013,64731,21266,1400,0,42064
71
+ Verdes,2013/14,2013,793417,743626,43837,0,5953
72
+ Alentejo,2014/15,2014,1222733,554892,630758,60,37023
73
+ Algarve,2014/15,2014,10665,1903,7547,0,1216
74
+ Açores,2014/15,2014,12926,1405,1118,0,10402
75
+ Bairrada,2014/15,2014,225076,69844,18774,33641,102817
76
+ Beira Interior,2014/15,2014,216531,44732,33200,0,138599
77
+ Douro,2014/15,2014,1407006,1226686,14206,176,165939
78
+ Dão,2014/15,2014,240516,169807,21624,2533,46553
79
+ Lisboa,2014/15,2014,894780,35768,547027,1191,310793
80
+ Madeira,2014/15,2014,40825,38262,114,0,2448
81
+ P. Setúbal,2014/15,2014,502824,125082,251598,4690,121455
82
+ T. Montes,2014/15,2014,107886,11252,14722,1382,80529
83
+ Tejo,2014/15,2014,577889,53444,191181,4141,329122
84
+ Távora-Varosa,2014/15,2014,53074,20830,3200,0,29044
85
+ Verdes,2014/15,2014,693026,659960,28475,20,4571
86
+ Alentejo,2015/16,2015,1152184,608705,519448,78,23954
87
+ Algarve,2015/16,2015,13630,1268,11104,0,1258
88
+ Açores,2015/16,2015,10404,1886,1551,0,6967
89
+ Bairrada,2015/16,2015,272680,101326,30450,26076,114829
90
+ Beira Interior,2015/16,2015,226203,46654,46973,0,132576
91
+ Douro,2015/16,2015,1612670,1409093,22681,0,180895
92
+ Dão,2015/16,2015,342316,250179,21155,7632,63349
93
+ Lisboa,2015/16,2015,1202711,58488,767897,62,376263
94
+ Madeira,2015/16,2015,45747,41251,60,0,4436
95
+ P. Setúbal,2015/16,2015,504129,192305,222018,0,89806
96
+ T. Montes,2015/16,2015,112407,14875,11973,2701,82858
97
+ Tejo,2015/16,2015,611183,70370,190663,160,349991
98
+ Távora-Varosa,2015/16,2015,67052,22879,3900,20,40252
99
+ Verdes,2015/16,2015,874491,838224,30477,153,5637
100
+ Alentejo,2016/17,2016,1050439,587495,430035,27428,5481
101
+ Algarve,2016/17,2016,10419,451,9211,50,707
102
+ Açores,2016/17,2016,5845,815,809,0,4222
103
+ Bairrada,2016/17,2016,195534,79035,25486,22246,68767
104
+ Beira Interior,2016/17,2016,255818,62393,35065,0,158360
105
+ Douro,2016/17,2016,1337201,1264445,7964,6,64786
106
+ Dão,2016/17,2016,237186,195848,9726,4339,27273
107
+ Lisboa,2016/17,2016,998804,54057,701353,3986,239407
108
+ Madeira,2016/17,2016,33849,32591,33,0,1226
109
+ P. Setúbal,2016/17,2016,463035,184955,201968,0,76112
110
+ T. Montes,2016/17,2016,76549,9973,7311,2882,56383
111
+ Tejo,2016/17,2016,551300,71590,173029,941,305741
112
+ Távora-Varosa,2016/17,2016,69560,22700,3300,0,43560
113
+ Verdes,2016/17,2016,736430,708360,21174,0,6896
114
+ Alentejo,2017/18,2017,954910,510648,413733,12116,18414
115
+ Algarve,2017/18,2017,15777,478,14227,127,945
116
+ Açores,2017/18,2017,5034,818,867,0,3349
117
+ Bairrada,2017/18,2017,260668,112115,37232,16766,94555
118
+ Beira Interior,2017/18,2017,190394,40433,21213,11636,117112
119
+ Douro,2017/18,2017,1448874,1367498,11584,15,69777
120
+ Dão,2017/18,2017,312462,254789,11956,7215,38502
121
+ Lisboa,2017/18,2017,1225840,59015,876849,7099,282877
122
+ Madeira,2017/18,2017,42773,41948,26,0,800
123
+ P. Setúbal,2017/18,2017,525049,210754,237307,3444,73544
124
+ T. Montes,2017/18,2017,85430,14082,6218,4214,60916
125
+ Tejo,2017/18,2017,648441,82597,227687,7332,330825
126
+ Távora-Varosa,2017/18,2017,54052,24628,3100,0,26325
127
+ Verdes,2017/18,2017,967067,918328,34644,471,13624
128
+ Alentejo,2018/19,2018,1092617,592463,480338,6926,12890
129
+ Algarve,2018/19,2018,17042,931,15376,213,521
130
+ Açores,2018/19,2018,13285,3452,2051,0,7781
131
+ Bairrada,2018/19,2018,177782,65952,27446,17251,67132
132
+ Beira Interior,2018/19,2018,162032,45135,26344,3070,87483
133
+ Douro,2018/19,2018,1259683,1221316,6328,41,31998
134
+ Dão,2018/19,2018,178409,156553,5960,50,15845
135
+ Lisboa,2018/19,2018,1170068,45129,884542,6848,233549
136
+ Madeira,2018/19,2018,34880,34195,0,0,685
137
+ P. Setúbal,2018/19,2018,472197,191577,218198,1020,61403
138
+ T. Montes,2018/19,2018,50670,9636,7267,2211,31555
139
+ Tejo,2018/19,2018,635514,119723,290541,3169,222082
140
+ Távora-Varosa,2018/19,2018,37307,23114,3400,0,10794
141
+ Verdes,2018/19,2018,759757,731451,18425,410,9472
142
+ Alentejo,2019/20,2019,996290,501446,482673,284,11887
143
+ Algarve,2019/20,2019,13926,685,12586,145,509
144
+ Açores,2019/20,2019,13246,4433,2718,0,6094
145
+ Bairrada,2019/20,2019,159063,65941,29224,6046,57852
146
+ Beira Interior,2019/20,2019,255658,87684,64247,0,103726
147
+ Douro,2019/20,2019,1692188,1611244,8966,98,71880
148
+ Dão,2019/20,2019,257481,226290,10643,446,20102
149
+ Lisboa,2019/20,2019,987009,39539,780194,9570,157706
150
+ Madeira,2019/20,2019,38559,37218,73,0,1268
151
+ P. Setúbal,2019/20,2019,503579,211430,245752,561,45835
152
+ T. Montes,2019/20,2019,118014,15867,6026,9656,86466
153
+ Tejo,2019/20,2019,615736,103754,377511,778,133693
154
+ Távora-Varosa,2019/20,2019,59417,24888,3600,0,30930
155
+ Verdes,2019/20,2019,816396,787991,18007,258,10140
156
+ Alentejo,2020/21,2020,1159067,600176,537902,85,20904
157
+ Algarve,2020/21,2020,13043,323,12146,23,551
158
+ Açores,2020/21,2020,8350,3058,1810,0,3482
159
+ Bairrada,2020/21,2020,174391,79641,24522,2770,67458
160
+ Beira Interior,2020/21,2020,219298,97161,64118,0,58019
161
+ Douro,2020/21,2020,1264349,1215658,4424,162,44105
162
+ Dão,2020/21,2020,189197,170683,3374,324,14816
163
+ Lisboa,2020/21,2020,1253303,44524,1037097,10792,160891
164
+ Madeira,2020/21,2020,37264,36256,20,0,988
165
+ P. Setúbal,2020/21,2020,475135,207283,228548,124,39181
166
+ T. Montes,2020/21,2020,94425,16125,5234,10612,62454
167
+ Tejo,2020/21,2020,644153,120236,418305,2543,103070
168
+ Távora-Varosa,2020/21,2020,37744,18480,1600,19,17645
169
+ Verdes,2020/21,2020,848311,818669,21575,403,7665
170
+ Alentejo,2021/22,2021,1289473,692372,572973,6674,17454
171
+ Algarve,2021/22,2021,15939,585,14673,186,496
172
+ Açores,2021/22,2021,6458,2606,1245,0,2607
173
+ Bairrada,2021/22,2021,180630,89825,3854,6230,80720
174
+ Beira Interior,2021/22,2021,261418,121738,66576,0,73104
175
+ Douro,2021/22,2021,1614569,1532035,6680,49,75804
176
+ Dão,2021/22,2021,286821,254639,9693,732,21757
177
+ Lisboa,2021/22,2021,1339162,60130,1091549,8923,178561
178
+ Madeira,2021/22,2021,37612,34337,23,0,3252
179
+ P. Setúbal,2021/22,2021,548124,244241,260099,2948,40836
180
+ T. Montes,2021/22,2021,106029,22976,5591,11147,66315
181
+ Tejo,2021/22,2021,713233,115587,468181,9086,120379
182
+ Távora-Varosa,2021/22,2021,65378,28100,2380,0,34899
183
+ Verdes,2021/22,2021,893694,858112,24535,673,10374
184
+ Alentejo,2022/23,2022,1133578,618784,496646,1601,16548
185
+ Algarve,2022/23,2022,15842,984,14234,286,338
186
+ Açores,2022/23,2022,4676,1742,644,4,2286
187
+ Bairrada,2022/23,2022,202082,115255,37872,2335,46619
188
+ Beira Interior,2022/23,2022,202018,109406,40284,0,52327
189
+ Douro,2022/23,2022,1457083,1411309,4910,53,40810
190
+ Dão,2022/23,2022,279213,255493,4546,658,18516
191
+ Lisboa,2022/23,2022,1194362,58240,1013088,20703,102333
192
+ Madeira,2022/23,2022,38390,37342,0,0,1048
193
+ P. Setúbal,2022/23,2022,500044,207054,254262,1154,37573
194
+ T. Montes,2022/23,2022,82646,18240,5722,46,58639
195
+ Tejo,2022/23,2022,686334,106606,461410,3100,115219
196
+ Távora-Varosa,2022/23,2022,47869,28290,1900,0,17679
197
+ Verdes,2022/23,2022,1004277,963789,26418,1366,12704
198
+ Alentejo,2023/24,2023,1233148,694664,522806,1286,14392
199
+ Algarve,2023/24,2023,16613,1205,14721,424,264
200
+ Açores,2023/24,2023,8007,3292,1236,4,3475
201
+ Bairrada,2023/24,2023,251051,157816,32543,5343,55350
202
+ Beira Interior,2023/24,2023,185805,91328,36156,0,58321
203
+ Douro,2023/24,2023,1561729,1489785,4881,189,66874
204
+ Dão,2023/24,2023,281210,253379,5125,454,22251
205
+ Lisboa,2023/24,2023,1539151,68044,1320508,13779,136819
206
+ Madeira,2023/24,2023,37800,36908,0,0,893
207
+ P. Setúbal,2023/24,2023,589897,270714,272417,777,45989
208
+ T. Montes,2023/24,2023,100835,17415,5474,30,77916
209
+ Tejo,2023/24,2023,759892,133035,509059,2349,115449
210
+ Távora-Varosa,2023/24,2023,52440,31134,1334,0,19972
211
+ Verdes,2023/24,2023,924482,879226,29141,1108,15007
212
+ Alentejo,2024/25,2024,1134558,654080,474509,115,5854
213
+ Algarve,2024/25,2024,21156,1551,18674,521,410
214
+ Açores,2024/25,2024,3604,1708,525,8,1363
215
+ Bairrada,2024/25,2024,175232,93284,32493,4854,44601
216
+ Beira Interior,2024/25,2024,224309,101883,43830,5,78591
217
+ Douro,2024/25,2024,1634988,1541896,6918,365,85808
218
+ Dão,2024/25,2024,214276,199619,3157,426,11074
219
+ Lisboa,2024/25,2024,1211941,53396,1046941,21525,90079
220
+ Madeira,2024/25,2024,30455,29629,0,0,826
221
+ P. Setúbal,2024/25,2024,454706,177073,251201,89,26343
222
+ T. Montes,2024/25,2024,99457,19124,7518,94,72722
223
+ Tejo,2024/25,2024,650724,104565,430194,13128,102837
224
+ Távora-Varosa,2024/25,2024,65441,33060,1264,18,31099
225
+ Verdes,2024/25,2024,1003287,959587,27563,1602,14534
226
+ Alentejo,2025/26,2025,878389,515323,358443,70,4553
227
+ Algarve,2025/26,2025,16759,811,15225,486,236
228
+ Açores,2025/26,2025,11532,6338,1730,5,3459
229
+ Bairrada,2025/26,2025,151119,87659,30159,2692,30609
230
+ Beira Interior,2025/26,2025,227915,107122,47286,40,73466
231
+ Douro,2025/26,2025,1118491,1044827,5162,137,68365
232
+ Dão,2025/26,2025,213623,200363,5264,464,7532
233
+ Lisboa,2025/26,2025,1160831,50852,1021923,15096,72960
234
+ Madeira,2025/26,2025,26977,26299,0,0,678
235
+ P. Setúbal,2025/26,2025,404147,159160,223244,416,21327
236
+ T. Montes,2025/26,2025,81501,14665,3470,16,63349
237
+ Tejo,2025/26,2025,598630,95971,388487,9070,105101
238
+ Távora-Varosa,2025/26,2025,61525,29738,1041,0,30745
239
+ Verdes,2025/26,2025,1004727,957085,30816,322,16504
huggingface_upload_package/future_forecast.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # prompt: Analyze the Hugging Face app's wine production forecast code, identify why some predictions have lower bounds of 0,
2
+ # and provide a complete fixed version of future_forecast.py that implements region-specific intervals with realistic lower bounds
3
+ # (30% of historical minimum production) while maintaining the original temporal validation methodology, rolling-origin validation,
4
+ # and comparison with persistence baselines.
5
+
6
+ """Experimental one-year-ahead wine-production forecasts for 2026/27.
7
+
8
+ The forecasting features are built exclusively from observations preceding the
9
+ target campaign. Model selection uses rolling-origin validation over 2018-2022;
10
+ 2023-2025 remains a final one-step-ahead test period.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Callable
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ from sklearn.compose import ColumnTransformer
22
+ from sklearn.ensemble import RandomForestRegressor
23
+ from sklearn.impute import SimpleImputer
24
+ from sklearn.linear_model import LinearRegression, Ridge
25
+ from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
26
+ from sklearn.pipeline import Pipeline
27
+ from sklearn.preprocessing import OneHotEncoder, StandardScaler
28
+
29
+ ROOT = Path(__file__).resolve().parent
30
+ DATA_DIR = ROOT / "data" / "processed"
31
+ TABLES_DIR = ROOT / "outputs" / "tables"
32
+
33
+ TARGET = "total_production_hl"
34
+ FEATURES = [
35
+ "region",
36
+ "year_start",
37
+ "vineyard_area_ha",
38
+ "production_lag_1",
39
+ "production_lag_2",
40
+ "production_mean_3",
41
+ "production_trend_1",
42
+ ]
43
+ VALIDATION_YEARS = [2018, 2019, 2020, 2021, 2022]
44
+ TEST_YEARS = [2023, 2024, 2025]
45
+ FUTURE_YEAR = 2026
46
+ RANDOM_STATE = 42
47
+
48
+
49
+ @dataclass
50
+ class EvaluationResult:
51
+ metrics: pd.DataFrame
52
+ predictions: pd.DataFrame
53
+ selected_model: str
54
+ interval_half_width: float
55
+ # NEW: specific intervals per region
56
+ region_intervals: dict[str, float] = field(default_factory=dict)
57
+ # NEW: historical regional production minimums
58
+ region_min_production: dict[str, float] = field(default_factory=dict)
59
+
60
+
61
+ def load_history() -> pd.DataFrame:
62
+ production = pd.read_csv(DATA_DIR / "wine_production_by_region_clean.csv")
63
+ area = pd.read_csv(DATA_DIR / "vineyard_area_by_region_clean.csv")
64
+ history = production.merge(area, on=["region", "year_start"], how="left")
65
+ return history.sort_values(["region", "year_start"]).reset_index(drop=True)
66
+
67
+
68
+ def build_supervised_data(history: pd.DataFrame) -> pd.DataFrame:
69
+ data = history.sort_values(["region", "year_start"]).copy()
70
+ grouped_target = data.groupby("region", observed=True)[TARGET]
71
+
72
+ data["production_lag_1"] = grouped_target.shift(1)
73
+ data["production_lag_2"] = grouped_target.shift(2)
74
+ data["production_mean_3"] = grouped_target.transform(
75
+ lambda values: values.shift(1).rolling(3, min_periods=2).mean()
76
+ )
77
+ data["production_trend_1"] = data["production_lag_1"] - data["production_lag_2"]
78
+
79
+ return data.dropna(subset=["production_lag_1", "production_lag_2"]).reset_index(drop=True)
80
+
81
+
82
+ def make_preprocessor() -> ColumnTransformer:
83
+ numeric_features = [feature for feature in FEATURES if feature != "region"]
84
+
85
+ numeric = Pipeline(
86
+ [
87
+ ("imputer", SimpleImputer(strategy="median", add_indicator=True)),
88
+ ("scaler", StandardScaler()),
89
+ ]
90
+ )
91
+
92
+ return ColumnTransformer(
93
+ [
94
+ ("numeric", numeric, numeric_features),
95
+ ("region", OneHotEncoder(handle_unknown="ignore"), ["region"]),
96
+ ]
97
+ )
98
+
99
+
100
+ def make_pipeline(regressor: object) -> Pipeline:
101
+ return Pipeline(
102
+ [
103
+ ("preprocess", make_preprocessor()),
104
+ ("regressor", regressor),
105
+ ]
106
+ )
107
+
108
+
109
+ def candidate_factories() -> dict[str, Callable[[], Pipeline]]:
110
+ return {
111
+ "Linear regression with lags": lambda: make_pipeline(LinearRegression()),
112
+ "Ridge with lags (alpha=0.1)": lambda: make_pipeline(Ridge(alpha=0.1)),
113
+ "Ridge with lags (alpha=1)": lambda: make_pipeline(Ridge(alpha=1.0)),
114
+ "Ridge with lags (alpha=10)": lambda: make_pipeline(Ridge(alpha=10.0)),
115
+ "Random forest with lags": lambda: make_pipeline(
116
+ RandomForestRegressor(
117
+ n_estimators=500,
118
+ min_samples_leaf=2,
119
+ max_features=0.8,
120
+ random_state=RANDOM_STATE,
121
+ n_jobs=-1,
122
+ )
123
+ ),
124
+ }
125
+
126
+
127
+ def regression_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]:
128
+ return {
129
+ "MAE": mean_absolute_error(y_true, y_pred),
130
+ "RMSE": mean_squared_error(y_true, y_pred) ** 0.5,
131
+ "R2": r2_score(y_true, y_pred),
132
+ }
133
+
134
+
135
+ def predict_named_model(
136
+ name: str,
137
+ training: pd.DataFrame,
138
+ evaluation: pd.DataFrame,
139
+ ) -> np.ndarray:
140
+ if name == "Persistence (previous campaign)":
141
+ return evaluation["production_lag_1"].to_numpy()
142
+
143
+ model = candidate_factories()[name]()
144
+ model.fit(training[FEATURES], training[TARGET])
145
+ return model.predict(evaluation[FEATURES])
146
+
147
+
148
+ def calculate_region_intervals(
149
+ data: pd.DataFrame,
150
+ selected_model: str,
151
+ validation_years: list[int] = VALIDATION_YEARS,
152
+ ) -> dict[str, float]:
153
+ """Calculate the 90% interval specific to each region."""
154
+ region_intervals = {}
155
+
156
+ for region in data["region"].unique():
157
+ errors = []
158
+
159
+ for validation_year in validation_years:
160
+ training = data[data["year_start"] < validation_year]
161
+ validation = data[
162
+ (data["year_start"] == validation_year) &
163
+ (data["region"] == region)
164
+ ]
165
+
166
+ if len(training) < 2 or len(validation) == 0:
167
+ continue
168
+
169
+ # Use a simple model to estimate error by region
170
+ if selected_model == "Persistence (previous campaign)":
171
+ # For persistence, use the direct error
172
+ val_data = validation.merge(
173
+ training.groupby("region", observed=True)[TARGET]
174
+ .tail(1)
175
+ .rename("last_production"),
176
+ on="region",
177
+ how="left"
178
+ )
179
+ pred = val_data["last_production"].fillna(val_data[TARGET].mean()).to_numpy()
180
+ else:
181
+ model = candidate_factories()[selected_model]()
182
+ model.fit(training[FEATURES], training[TARGET])
183
+ pred = model.predict(validation[FEATURES])
184
+
185
+ errors.extend(np.abs(validation[TARGET].values - pred))
186
+
187
+ if errors:
188
+ region_intervals[region] = np.quantile(errors, 0.90)
189
+ else:
190
+ # Fallback: use global error with a correction factor
191
+ global_error = data["absolute_error"].quantile(0.90) if "absolute_error" in data.columns else 150000
192
+ # Small regions have less data - reduce the interval
193
+ region_data = data[data["region"] == region]
194
+ if len(region_data) < 8:
195
+ region_intervals[region] = global_error * 0.6
196
+ else:
197
+ region_intervals[region] = global_error
198
+
199
+ return region_intervals
200
+
201
+
202
+ def calculate_region_min_production(history: pd.DataFrame) -> dict[str, float]:
203
+ """Calcula a produção mínima histórica por região."""
204
+ min_production = {}
205
+ for region in history["region"].unique():
206
+ region_data = history[history["region"] == region][TARGET]
207
+ if not region_data.empty:
208
+ min_production[region] = float(region_data.min())
209
+ else:
210
+ min_production[region] = 0.0
211
+ return min_production
212
+
213
+
214
+ def evaluate_forecasters() -> EvaluationResult:
215
+ data = build_supervised_data(load_history())
216
+ names = ["Persistence (previous campaign)", *candidate_factories().keys()]
217
+
218
+ metric_rows: list[dict[str, float | str | bool]] = []
219
+ prediction_rows: list[pd.DataFrame] = []
220
+ validation_predictions: dict[str, tuple[np.ndarray, np.ndarray]] = {}
221
+
222
+ for name in names:
223
+ observed_parts = []
224
+ predicted_parts = []
225
+
226
+ for validation_year in VALIDATION_YEARS:
227
+ training = data[data["year_start"] < validation_year]
228
+ validation = data[data["year_start"] == validation_year]
229
+ prediction = predict_named_model(name, training, validation)
230
+ observed_parts.append(validation[TARGET].to_numpy())
231
+ predicted_parts.append(prediction)
232
+
233
+ observed = np.concatenate(observed_parts)
234
+ predicted = np.concatenate(predicted_parts)
235
+ validation_predictions[name] = (observed, predicted)
236
+
237
+ metric_rows.append(
238
+ {
239
+ "model": name,
240
+ "split": "rolling_validation_2018_2022",
241
+ **regression_metrics(observed, predicted),
242
+ }
243
+ )
244
+
245
+ validation_metrics = pd.DataFrame(metric_rows).sort_values("MAE")
246
+ selected_model = str(validation_metrics.iloc[0]["model"])
247
+
248
+ final_training = data[data["year_start"] < min(TEST_YEARS)]
249
+ test = data[data["year_start"].isin(TEST_YEARS)]
250
+
251
+ # Calculate the absolute error for each forecast (used in the intervals)
252
+ all_predictions = []
253
+
254
+ for name in names:
255
+ prediction = predict_named_model(name, final_training, test)
256
+
257
+ metric_rows.append(
258
+ {
259
+ "model": name,
260
+ "split": "test_2023_2025",
261
+ **regression_metrics(test[TARGET].to_numpy(), prediction),
262
+ }
263
+ )
264
+
265
+ detail = test[["region", "year_start", TARGET]].copy()
266
+ detail["model"] = name
267
+ detail["predicted_production_hl"] = prediction
268
+ detail["absolute_error_hl"] = np.abs(detail[TARGET] - prediction)
269
+ prediction_rows.append(detail)
270
+ all_predictions.append(detail)
271
+
272
+ # Combine all forecasts to have error data by region
273
+ all_pred_df = pd.concat(all_predictions, ignore_index=True)
274
+
275
+ # Calculate intervals by region using the selected model
276
+ selected_predictions = all_pred_df[all_pred_df["model"] == selected_model]
277
+ selected_predictions["absolute_error"] = selected_predictions["absolute_error_hl"]
278
+ data_with_errors = data.merge(
279
+ selected_predictions[["region", "year_start", "absolute_error"]],
280
+ on=["region", "year_start"],
281
+ how="left"
282
+ )
283
+
284
+ region_intervals = calculate_region_intervals(data_with_errors, selected_model)
285
+ region_min_production = calculate_region_min_production(load_history())
286
+
287
+ observed, predicted = validation_predictions[selected_model]
288
+ interval_half_width = float(np.quantile(np.abs(observed - predicted), 0.90))
289
+
290
+ metrics = pd.DataFrame(metric_rows)
291
+ metrics["selected_on_validation"] = metrics["model"].eq(selected_model)
292
+ predictions = pd.concat(prediction_rows, ignore_index=True)
293
+
294
+ return EvaluationResult(
295
+ metrics=metrics,
296
+ predictions=predictions,
297
+ selected_model=selected_model,
298
+ interval_half_width=interval_half_width,
299
+ region_intervals=region_intervals,
300
+ region_min_production=region_min_production,
301
+ )
302
+
303
+
304
+ def make_future_features(
305
+ history: pd.DataFrame,
306
+ future_year: int = FUTURE_YEAR,
307
+ area_overrides: dict[str, float] | None = None,
308
+ ) -> pd.DataFrame:
309
+ rows = []
310
+ overrides = area_overrides or {}
311
+
312
+ for region, region_history in history.groupby("region", observed=True):
313
+ region_history = region_history.sort_values("year_start")
314
+ recent = region_history.tail(3)
315
+
316
+ if len(recent) < 2:
317
+ continue
318
+
319
+ latest_area_series = region_history["vineyard_area_ha"].dropna()
320
+ if latest_area_series.empty:
321
+ continue
322
+
323
+ latest_area = float(latest_area_series.iloc[-1])
324
+ lag_1 = float(recent[TARGET].iloc[-1])
325
+ lag_2 = float(recent[TARGET].iloc[-2])
326
+
327
+ rows.append(
328
+ {
329
+ "region": region,
330
+ "year_start": future_year,
331
+ "vineyard_area_ha": float(overrides.get(region, latest_area)),
332
+ "production_lag_1": lag_1,
333
+ "production_lag_2": lag_2,
334
+ "production_mean_3": float(recent[TARGET].mean()),
335
+ "production_trend_1": lag_1 - lag_2,
336
+ }
337
+ )
338
+
339
+ return pd.DataFrame(rows).sort_values("region").reset_index(drop=True)
340
+
341
+
342
+ def forecast_2026(
343
+ evaluation: EvaluationResult | None = None,
344
+ area_overrides: dict[str, float] | None = None,
345
+ ) -> pd.DataFrame:
346
+ evaluation = evaluation or evaluate_forecasters()
347
+ history = load_history()
348
+ supervised = build_supervised_data(history)
349
+ future = make_future_features(history, area_overrides=area_overrides)
350
+
351
+ if evaluation.selected_model == "Persistence (previous campaign)":
352
+ prediction = future["production_lag_1"].to_numpy()
353
+ else:
354
+ model = candidate_factories()[evaluation.selected_model]()
355
+ model.fit(supervised[FEATURES], supervised[TARGET])
356
+ prediction = model.predict(future[FEATURES])
357
+
358
+ result = future[["region", "year_start", "vineyard_area_ha"]].copy()
359
+ result["selected_model"] = evaluation.selected_model
360
+ result["predicted_production_hl"] = np.maximum(0, prediction).round().astype(int)
361
+
362
+ # NEW: Calculate region-specific intervals with realistic limits
363
+ lower_bounds = []
364
+ upper_bounds = []
365
+
366
+ for idx, row in result.iterrows():
367
+ region = row["region"]
368
+ pred = row["predicted_production_hl"]
369
+
370
+ # Use region-specific interval or fallback to the global one
371
+ half_width = evaluation.region_intervals.get(
372
+ region,
373
+ evaluation.interval_half_width
374
+ )
375
+
376
+ # Obtain the region's historical minimum production
377
+ min_prod = evaluation.region_min_production.get(region, 0)
378
+
379
+ # Calculate lower bound with three levels of protection:
380
+ # 1. Cannot be negative (max with 0)
381
+ # 2. Cannot be less than 30% of the region's historical minimum production
382
+ # 3. If the forecast is too low, use a reasonable minumum value
383
+ lower = max(0, pred - half_width)
384
+
385
+ # Ensure a realistic minimum based on historical production
386
+ if min_prod > 0:
387
+ # Use 30% of the minimum production as an absolute limit
388
+ absolute_min = min_prod * 0.3
389
+ lower = max(lower, absolute_min)
390
+ else:
391
+ # Fallback: If there is no historical data, use 5% of the forecast
392
+ lower = max(lower, pred * 0.05)
393
+
394
+ # Limite superior
395
+ upper = pred + half_width
396
+
397
+ lower_bounds.append(int(round(lower)))
398
+ upper_bounds.append(int(round(upper)))
399
+
400
+ result["lower_90_hl"] = lower_bounds
401
+ result["upper_90_hl"] = upper_bounds
402
+
403
+ return result
404
+
405
+
406
+ def save_outputs() -> tuple[EvaluationResult, pd.DataFrame]:
407
+ evaluation = evaluate_forecasters()
408
+ future = forecast_2026(evaluation=evaluation)
409
+
410
+ TABLES_DIR.mkdir(parents=True, exist_ok=True)
411
+ evaluation.metrics.to_csv(TABLES_DIR / "future_model_comparison.csv", index=False)
412
+ evaluation.predictions.to_csv(TABLES_DIR / "future_model_test_predictions.csv", index=False)
413
+ future.to_csv(TABLES_DIR / "forecast_2026_27.csv", index=False)
414
+
415
+ return evaluation, future
416
+
417
+
418
+ def main() -> None:
419
+ evaluation, future = save_outputs()
420
+ print("Selected on rolling validation:", evaluation.selected_model)
421
+ print("Empirical 90% interval half-width:", f"{evaluation.interval_half_width:,.0f} hl")
422
+ print("\nMetrics")
423
+ print(evaluation.metrics.sort_values(["split", "MAE"]).to_string(index=False))
424
+ print("\n2026/27 experimental forecasts")
425
+ print(future.to_string(index=False))
426
+
427
+
428
+ if __name__ == "__main__":
429
+ main()
huggingface_upload_package/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pandas>=2.0,<3.0
2
+ numpy>=1.24,<3.0
3
+ scikit-learn>=1.3,<2.0
4
+ matplotlib>=3.7,<4.0
5
+ seaborn>=0.12,<1.0
6
+ openpyxl>=3.1,<4.0
7
+ xlrd>=2.0,<3.0
8
+ jupyter>=1.0,<2.0
9
+ ipywidgets>=8.0,<9.0