-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
473 lines (410 loc) · 17.1 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
import numpy as np
import helper_data
import dash_daq as daq
default_country = 'Belgium'
default_age_group = 'Adults'
fruit_category = 'Fruit'
meat_category = 'Meat'
vegetable_category = 'Vegetable'
grain_category = 'Grain'
oil_category = 'Oil'
dairy_category = 'Dairy'
nut_seed_legume_category = 'Nut/Seed/Legume'
other_category = 'Other'
food_categories = helper_data.get_food_categories()
all_keys = helper_data.get_food_category_and_item_dictionary()
slider_keys = helper_data.get_slider_box_keys()
# Read the data.
df = pd.read_csv('df/CleanFoodData.csv')
co2fp_df = pd.read_csv('df/CO2Footprint.csv')
co2mean_df = pd.read_csv('df/CO2_per_country_ageGroup.csv')
knn_df =pd.read_csv('https://raw.githubusercontent.com/mcunha95/CarbonFoodPrint/knn/KNN/formated_normalized_food_per_country_ageGroup.csv')
################################################################################
# KNN
################################################################################
def knn_predict(data):
X = np.asarray(knn_df.iloc[:,2:])
y_country = np.asarray(knn_df.iloc[:,0])
y_age = np.asarray(knn_df.iloc[:,1])
neigh_country = KNeighborsClassifier(n_neighbors = 1, weights='uniform', algorithm='auto')
neigh_country.fit(X, y_country)
return neigh_country.predict([data])[0]
################################################################################
# MAP
################################################################################
def legend_map_func(filtered_df):
age_group = filtered_df.ageGroup.unique()[0]
countries_age_group = filtered_df.Country.unique()
categories = co2fp_df.Category.unique()
#INIZALIZATION DICTIONARY
legend_map = {}
for country in countries_age_group:
legend_map[country] = dict()
for category in categories:
legend_map[country][category]=0
legend_map[country]['Total']=0
#POPULATION
cond_age_group = df.Pop_Class==age_group
for country in countries_age_group:
cond_country = df.Country==country
for id in df[cond_country&cond_age_group].FoodId:
cond_ID = co2fp_df.ID==pd.to_numeric(id)
category = co2fp_df[cond_ID].Category
cond_dfID = df.FoodId==id
value=float(df[cond_country&cond_age_group&cond_dfID].Mean.values[0])
legend_map[country][category.values[0]]+=value
legend_map[country]['Total']+=value
#NORMALIZATION
for key, value in legend_map.items():
total = legend_map[key]['Total']
for key1, value1 in value.items():
legend_map[key][key1] = value1/total
return legend_map
def euro_map(filtered_df):
#scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'], [0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
legend_map = legend_map_func(filtered_df)
txt = []
for country in filtered_df['Country'].values:
txtbycountry = ""
for key1,value1 in legend_map[country].items():
if key1 != 'Total':
txtbycountry += " "+key1+": "+str(round(value1*100,2))+ '%<br>'
txt.append(txtbycountry)
filtered_df['text'] = txt#filtered_df['state'] + '<br>' +'Beef '+filtered_df['beef']+' Dairy '+filtered_df['dairy']+'<br>'+'Fruits '+filtered_df['total fruits']+' Veggies ' + filtered_df['total veggies']+'<br>'+'Wheat '+filtered_df['wheat']+' Corn '+filtered_df['corn']
colorscale="Cividis"#YlOrRd,Portland,Hot,Electric,Viridis,Cividis.
data = [ dict(
type='choropleth',
colorscale = colorscale,
autocolorscale = False,
locations = filtered_df['Country'],
z = filtered_df['Mean_CO2.g'].astype(float),
locationmode = 'country names',
text = filtered_df['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 1
) ),
colorbar = dict(
title = "grams of CO2/day")
) ]
layout = dict(
autosize=False,
width='auto',
height=500,
title = 'Avg Carbon Footprint Country Map',
geo = dict(
scope='europe',
projection=dict( type='Orthographic' ),
),
)
return {"data":data,"layout":layout}
################################################################################
################################################################################
################################################################################
# RUSHIL:
################################################################################
def generateDropDown(categoryName, food_items_only_per_category):
return dcc.Dropdown(
id='dropdown-' + categoryName,
options=[{'label': item, 'value': item} for item in food_items_only_per_category],
multi=True,
style={'marginLeft': 15, 'marginRight': 15, 'width': '600px'}
)
def generateSlider(itemName, categoryName):
return html.Div(
id='slider-container-' + categoryName + '-' + itemName,
children=[
html.H5(itemName),
html.P("(Servings per week)"),
html.H5(id='slider-value-box-' + categoryName + '-' + itemName),
dcc.Slider(
id='slider-' + categoryName + '-' + itemName,
min=0,
max=20,
step=1,
value=0,
)
]
)
def generateSliderArea(categoryName, food_items_only_per_category):
return html.Div(
children=[generateSlider(item, categoryName) for item in food_items_only_per_category],
style={'marginLeft': 30, 'marginRight': 30, 'width': '200px'})
def generateCategorySection(categoryName):
food_items_only_per_category = helper_data.get_food_items_only_per_category(categoryName)
return html.Div(
id='section-' + categoryName,
children=[
html.H3(categoryName),
generateDropDown(categoryName, food_items_only_per_category),
generateSliderArea(categoryName, food_items_only_per_category)
], style={'marginLeft': 30, 'marginRight': 30}
)
################################################################################
################################################################################
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server
# Bootstrap CSS
app.css.append_css({'external_url': 'https://codepen.io/amyoshino/pen/jzXypZ.css'})
app.layout = html.Div(children=[
#Row 1
html.Div([
html.Img(
src="http://www.greeneatz.com/wp-content/uploads/2013/01/foods-carbon-footprint.jpg",
width='auto',
height='auto',
className = "two columns"),
html.H1('My Carbon Food Print', style={'color': 'white', 'fontSize': 30}, className = "ten columns")
], className = "row", style={'backgroundColor':'#8EB640'}),
#Tabs
html.Div([
dcc.Tabs(id="tabs-example", value='tab-1-example', children=[
################################################################################
#Tab one
################################################################################
dcc.Tab(label='Calculate my CO2 footprint', children = [
html.Div(children=[
html.H3('What country do you want to check?',
style={'marginLeft': 30, 'marginRight': 30, 'marginTop': 10}),
dcc.Dropdown(
id='country',
options=helper_data.get_countries(),
value=default_country,
style={'marginLeft': 30, 'marginRight': 30, 'width': '200px'}
)
]),
html.Div(children=[
html.H3('What age group are you in?',
style={'marginLeft': 30, 'marginRight': 30}),
dcc.Dropdown(
id='age-group',
options=helper_data.get_age_groups(default_country),
value=default_age_group,
style={'marginLeft': 30, 'marginRight': 30, 'width': '200px'}
)
]),
html.Div(children=[
generateCategorySection(category)
for category in food_categories
]),
html.Div(id='my-carbon-food-print-div'),
html.Div(id='live-knn'),
html.Div(id='live-graph')
], className = "six columns"),
################################################################################
#Tab two
################################################################################
dcc.Tab(label='Explore Europe', children =[
# Row: Filter
html.Div(children=[
html.H4('What age group are you in?', style={'marginLeft': 30}),
dcc.Dropdown(
id='age-groups-map',
options=helper_data.get_all_age_groups(),
value='Adults',
style={'marginLeft': 30, 'marginRight': 0, 'width': '200px'}
)
]),
#Code in tab
html.Div([
# Column: Map
dcc.Graph(id="euro-map")
],
className="row"),
#Code in tab
], className = "six columns"),
#End tabs
]),
], className="row"),
])
@app.callback(
Output(component_id='live-graph',component_property='children'),
[
Input('country','value'),
Input('age-group','value')
]+
[
Input(sliderValueId, 'value') for sliderValueId in slider_keys
]
)
def generateGraph(country, ageGroup, *args):
newDict = {}
i = 0
for category in food_categories:
newDict[category] = {}
for item in all_keys[category]:
newDict[category][item]=args[i]
i+=1
# from here we need to take the new dict and generate the graphs
dataArrays=helper_data.generate_data_arrays(newDict)
myTotalWeeklyCO2 = sum(dataArrays['your_food_choices_emissions'])
countryArrays=helper_data.generate_data_arrays_country(country,ageGroup,myTotalWeeklyCO2)
return html.Div(children=[
dcc.Graph(
id='country-person-graph-agg',
figure={
'data': [
{'x': dataArrays['your_food_choices_all_categories'], 'y': dataArrays['your_food_choices_aggregated_emissions'], 'type': 'bar'},
],
'layout': {
'title': 'My CO2 production/food group',
'yaxis':{
'title':'CO2 footprint [grams]'
}
}
},
style={'marginLeft': 30, 'marginRight': 30, 'maxwidth': '600px'}
),
dcc.Graph(
id='country-person-graph',
figure={
'data': [
{'x': dataArrays['your_food_choices_item'], 'y': dataArrays['your_food_choices_emissions'], 'type': 'bar', 'width': [0.8] },
],
'layout': {
'title': 'My CO2 production/food',
'yaxis':{
'title':'CO2 footprint [grams]'
}
}
}
),
dcc.Graph(
id='countries-person-comparision',
figure={
'data': [
{'x': countryArrays['country'], 'y': countryArrays['country_emissions'], 'type': 'bar',
'marker':{'color':countryArrays['color']}},
],
'layout': {
'title': 'average Weekly CO2 emissions per person per country (in your population group)'
}
}
)
])
@app.callback(
Output('euro-map', 'figure'),
[Input('age-groups-map', 'value')]
)
def filter_euro_map(age_group):
cond_age_group = co2mean_df['ageGroup'] == age_group
cond_non_cero = co2mean_df['Mean_CO2.g'] != 0
return euro_map(co2mean_df[(cond_age_group & cond_non_cero)])
@app.callback(
Output(component_id='age-group', component_property='options'),
[Input(component_id='country', component_property='value')]
)
def update_age_groups(country):
return helper_data.get_age_groups(country)
for category in food_categories:
@app.callback(
Output('dropdown-' + category, 'options'),
[Input('age-group', 'value'),
Input('country', 'value')],
[State('dropdown-' + category, 'id')]
)
def resetOptionsAgeChange(ageGroup, country, categoryId):
categoryName = categoryId.split('-')[-1]
return helper_data.get_food_items(country, ageGroup, categoryName)
@app.callback(
Output('dropdown-' + category, 'value'),
[Input('dropdown-' + category, 'options')]
)
def clearSelections(CategoryOptions):
return []
for category in food_categories:
for item in helper_data.get_food_items_only_per_category(category):
@app.callback(
Output('slider-value-box-' + category + '-' + item, 'children'),
[Input('slider-' + category + '-' + item, 'value')]
)
def setValue(inputValue):
return inputValue
for category in food_categories:
for item in helper_data.get_food_items_only_per_category(category):
@app.callback(
Output('slider-container-' + category + '-' + item, 'style'),
[Input('dropdown-' + category, 'value')],
[State('slider-container-' + category + '-' + item, 'id')]
)
def hideSlider(optionsArray, itemID):
itemName = itemID.split('-')[-1]
if optionsArray is None:
return {'display': 'none'}
if itemName in optionsArray:
return {'display': 'block'}
return {'display': 'none'}
@app.callback(
Output(component_id='my-carbon-food-print-div', component_property='children'),
[Input(component_id='country', component_property='value'),
Input(component_id='age-group', component_property='value')]+
[Input(sliderValueId, 'value') for sliderValueId in slider_keys]
)
def get_my_carbon_food_print(country, age_group, *args):
newDict = {}
i = 0
for category in food_categories:
newDict[category] = {}
for item in all_keys[category]:
newDict[category][item] = args[i]
i += 1
my_carbon_food_print = helper_data.calculate_my_carbon_food_print(newDict)
country_food_print = helper_data.get_carbon_food_print_for_country(country, age_group)
return html.Div([
html.Div([
daq.Gauge(
id='my-gauge',
label='Your weekly CO2 food print',
max=100000,
value=my_carbon_food_print,
min=0)
], className="six columns"),
html.Div([
daq.Gauge(
id='country-gauge',
label=country + ' ' + age_group.lower() + ' weekly CO2 food print',
max=100000,
value=country_food_print,
min=0)
], className="six columns")
], className="row")
@app.callback(
Output(component_id='live-knn', component_property='children'),
[Input(component_id='country', component_property='value'),
Input(component_id='age-group', component_property='value')]+
[Input(sliderValueId, 'value') for sliderValueId in slider_keys]
)
def get_my_carbon_food_print(country, age_group, *args):
newDict = {}
newDictAvg = {}
total_grams = 0
i = 0
for category in food_categories:
newDict[category] = {}
for item in all_keys[category]:
newDict[category][item] = args[i]
total_grams += args[i]
i += 1
for key, values in newDict.items():
for key1, value1 in newDict[key].items():
if total_grams!=0:
newDictAvg[key1.lower()]=value1/total_grams
data_test = []
for col in list(knn_df.keys()[2:]):
if col == 'egg':
col='eggs'
data_test.append(newDictAvg[col])
knn_prediction = knn_predict(data_test)
return html.Div([
html.H3('According to your eating habits you eat similar to a person from '+knn_prediction)
], className="row")
if __name__ == '__main__':
app.run_server(debug=True)