Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes on generic_metric and mode_specific_metrics in relation to Mo… #91

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
34eae86
Changes on generic_metric and mode_specific_metrics in relation to Mo…
iantei Sep 7, 2023
176655a
Address Review comments.
iantei Sep 11, 2023
f04e596
Update generate_plots.py & scaffolding.py
iantei Sep 12, 2023
3182a0b
Fix merge conflict.
iantei Sep 12, 2023
43d974b
Fix scaffolding, updated mode_specific_metrics.ipynb.
iantei Sep 12, 2023
7343606
Revert version changes to 3.7.12.
iantei Sep 12, 2023
080f4f4
Update initialization of dynamic_labels from { } to json object refer…
iantei Sep 12, 2023
7d8b2d6
Default initialize dynamic_labels to { }.
iantei Sep 14, 2023
1b037c2
Merge with main. Resolve merge conflict.
iantei Sep 14, 2023
fea6365
Add an environment variable in Docker Compose to pass dynamic config.
iantei Sep 17, 2023
b04096b
Chang in docker-compose for STUDY_CONFIG to dev-emulator-study. Rever…
iantei Sep 18, 2023
5a70ecb
Change back docker-compose.dev.yml: STUDY_CONFIG to stage-program.
iantei Sep 19, 2023
6e80c7f
Replace Mode_confirm with Replaced_mode for barplot_mode() in mode_sp…
iantei Sep 22, 2023
30c1dd4
1. Remove extraneous whitespace from generate_plots.py. 2. Revert ref…
iantei Sep 25, 2023
86f8133
Remove extraneous whitespace from line 96 in generate_plots.py
iantei Sep 25, 2023
845dd47
Introduce defaultdic for dic_translations with Other in analogy to di…
iantei Sep 26, 2023
40519ec
Merge branch 'main' into ananta_support_customLabel_from_dynamic_config
iantei Sep 27, 2023
af9d3fc
Handle initialization of mode_count_interest. Introduce try-except bl…
iantei Sep 28, 2023
a868e4c
Move quality_text code into the if block in the above cell.
iantei Sep 28, 2023
54e213b
Update log messages for dynamic_labels_url and label_options unavaila…
iantei Sep 29, 2023
81407fc
Update scaffolding to introduce compute_CO2_impact_kg() computation w…
iantei Oct 5, 2023
d4fb9bc
1. Change the plots.py X-axis to showcase CO2 Impact in kg. 2. In sca…
iantei Oct 5, 2023
42990a2
Move the compute_CO2_impact_kg() call to scaffolding, such that energ…
iantei Oct 5, 2023
2dd360f
Changes to understand difference between default mapping and dynamic …
iantei Oct 6, 2023
0aeb70c
Update scaffolding to create different dictionary mappings for MODE, …
iantei Oct 7, 2023
aae0d2a
Update Trip_purpose to To Work instead of Work whenever dynamic label…
iantei Oct 7, 2023
f2f0a45
Update scaffolding.py CO2_footprint_lb() to utilize the distance whil…
iantei Oct 9, 2023
fecec39
Update changes for generic_timeseries. 1. Inside scaffolding.py intro…
iantei Oct 10, 2023
5cf84bc
Create new metrics_study and metrics_program options html files witho…
iantei Oct 12, 2023
5a8c9d6
Update index.html to use different metrics_ options html when dynamic…
iantei Oct 12, 2023
8fefdea
Remove redundant check for dynamic_labels_urls. Update the message to…
iantei Oct 12, 2023
a2c1910
Remove print statements used to evaluate the difference in energy cal…
iantei Oct 12, 2023
a42b308
Update the mode mapping in accordance to MODE for Daily Mode Share in…
iantei Oct 13, 2023
6f13c03
Refactor the code to load the config and corresponding metrics.html p…
iantei Oct 19, 2023
32864c6
Reinstate the comment for energy_calculations.ipynb. Removed extranne…
iantei Oct 19, 2023
b3a92a1
Update data.label_options to dynamic_labels to make it coherent acros…
iantei Oct 19, 2023
1628f5a
Created a new function inside scaffolding.py, mapping_labels(dynamic_…
iantei Oct 19, 2023
f3edc61
Moving the mapping_labels() call inside the conditional check for eac…
iantei Oct 19, 2023
e7c17a1
Update the purpose mapping for Work to select from scaffolding.mappin…
iantei Oct 19, 2023
c114d38
Update the Timeseries of emissions per miles TO Timeseries of emissio…
iantei Oct 24, 2023
b26207d
Update plots.py CO2_impact to take x and y Labels from the notebook. …
iantei Oct 27, 2023
14a3666
Update generic_timeseries to show the CO2 emissions in Imperial syste…
iantei Oct 27, 2023
4c177d7
Added print statements to understand the difference in CO2 emissions …
iantei Oct 27, 2023
a8f3697
Renamed 1. compute_CO2_impact_kg to compute_CO2_impact_dynamic 2. com…
iantei Oct 27, 2023
e7f804e
Removed the unnecessary file unde frontend/Dockerfile.dev.
iantei Oct 27, 2023
23e5773
Showing Timeseries of emissions per mile for default mapping.
iantei Oct 27, 2023
6c469a5
Remove extranneous whitespaces from energy_calculations and generic_t…
iantei Oct 27, 2023
a18c549
Remove whitespace from generic_timeseries.ipynb
iantei Oct 27, 2023
88b899b
Fixing the scaffolding calculation for computation of conversion to k…
iantei Oct 30, 2023
9134465
Add new function in scaffolding.py to print the computation of CO2 em…
iantei Oct 30, 2023
5229d7e
Added is_debug_mode flag, which by default is set to False. When it i…
iantei Oct 30, 2023
efbd31f
Removed energy_impact computation for Dynamic config case.
iantei Oct 31, 2023
3c8823e
Update distace_miles column in the selected_columns in scaffolding.py…
iantei Oct 31, 2023
adb5258
Setting the default is_debug_mode flag to False. This will disable ca…
iantei Oct 31, 2023
b858b53
Removed redundant if/else case for different label_type inside mappin…
iantei Nov 2, 2023
3ee1bbb
Energy_calculations.ipynb added justification for computation of tota…
iantei Nov 2, 2023
5cbce25
Refactor both energy_calculations and generic_timeseries notebook to …
iantei Nov 7, 2023
dd64513
Stored the returned expanded_ct from compute_CO2_footprint_dynamic().
iantei Nov 7, 2023
a72ac99
Fixed try-catch block to handle case where emissions is not defined. …
iantei Nov 7, 2023
ae3117a
Fixed issue with default mapping - calling the right function. Update…
iantei Nov 7, 2023
8832e79
Remove conversion_kilometer_to_mile and vice versa in scaffolding.py …
iantei Nov 13, 2023
78e4777
Removed f{'distance_unit'} with distance_unit for compute_daily_metri…
iantei Nov 13, 2023
932af13
Update sense keyword in the phrase for dropdown menu for Trip miles b…
iantei Nov 21, 2023
a23ad9f
Updated the comment to explain this is specically used to test with e…
iantei Nov 21, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions viz_scripts/bin/generate_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,29 @@
dynamic_config = json.loads(r.text)
print(f"Successfully downloaded config with version {dynamic_config['version']} "\
f"for {dynamic_config['intro']['translated_text']['en']['deployment_name']} "\
f"and data collection URL {dynamic_config['server']['connectUrl']}")
f"and data collection URL {dynamic_config['server']['connectUrl'] if 'server' in dynamic_config else 'default'}")

if dynamic_config['intro']['program_or_study'] == 'program':
mode_studied = dynamic_config['intro']['mode_studied']
else:
mode_studied = None

# Check if the dynamic config contains dynamic labels 'label_options'
# Passing the boolean flag is not enough, bcos we need to trace through the dynamic_config - pass label_options URL.
if 'label_options' in dynamic_config:
dynamic_labels_url = dynamic_config['label_options']

# Parse through the dynamic_labels_url: Create a new function for this
if dynamic_labels_url:
req = requests.get(dynamic_labels_url)
if req.status_code != 200:
print("Unable to download dynamic_labels, status code: {r.status_code}")
iantei marked this conversation as resolved.
Show resolved Hide resolved
else:
print("Dynamic labels download was successful.")
dynamic_labels = json.loads(req.text)
else:
print("Dynamic labels URL is unavailable.")

if args.date is None:
start_date = arrow.get(int(dynamic_config['intro']['start_year']),
int(dynamic_config['intro']['start_month']), 1)
Expand Down Expand Up @@ -69,7 +85,8 @@ def compute_for_date(month, year):
program=args.program,
study_type=dynamic_config['intro']['program_or_study'],
mode_of_interest=mode_studied,
include_test_users=dynamic_config.get('metrics', {}).get('include_test_users', False))
include_test_users=dynamic_config.get('metrics', {}).get('include_test_users', False),
dynamic_labels = dynamic_labels)
iantei marked this conversation as resolved.
Show resolved Hide resolved

print(f"Running at {arrow.get()} with params {params}")

Expand Down
6 changes: 4 additions & 2 deletions viz_scripts/energy_calculations.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"program = \"default\"\n",
"study_type = \"program\"\n",
"mode_of_interest = \"e-bike\"\n",
"include_test_users = False"
"include_test_users = False\n",
"dynamic_labels = { }"
]
},
{
Expand Down Expand Up @@ -107,6 +108,7 @@
" month,\n",
" program,\n",
" study_type,\n",
" dynamic_labels,\n",
" dic_re,\n",
" dic_pur=dic_pur,\n",
" include_test_users=include_test_users)\n",
Expand Down Expand Up @@ -252,7 +254,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.12"
"version": "3.9.16"
iantei marked this conversation as resolved.
Show resolved Hide resolved
}
},
"nbformat": 4,
Expand Down
8 changes: 5 additions & 3 deletions viz_scripts/generic_metrics.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"program = \"default\"\n",
"study_type = \"study\"\n",
"mode_of_interest = None\n",
"include_test_users = False"
"include_test_users = False\n",
"dynamic_labels = { }"
]
},
{
Expand Down Expand Up @@ -88,6 +89,7 @@
" month,\n",
" program,\n",
" study_type,\n",
" dynamic_labels,\n",
" dic_re,\n",
" dic_pur=dic_pur,\n",
" include_test_users=include_test_users)"
Expand Down Expand Up @@ -295,7 +297,7 @@
" \n",
" plot_title= plot_title_no_quality+\"\\n\"+quality_text\n",
"\n",
" barplot_mode(data,x,y,plot_title,file_name)\n",
" barplot_mode(data,x,y,plot_title, expanded_ct['Mode_confirm'].dropna().unique().tolist(), file_name)\n",
" alt_text = store_alt_text_bar(pd.DataFrame(data['Average (miles)'].values, data['Mode_confirm']), file_name, plot_title)\n",
"except:\n",
" generate_missing_plot(plot_title_no_quality,debug_df,file_name)\n",
Expand Down Expand Up @@ -392,7 +394,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.12"
"version": "3.9.16"
}
},
"nbformat": 4,
Expand Down
6 changes: 4 additions & 2 deletions viz_scripts/generic_timeseries.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"program = \"default\"\n",
"study_type = \"study\"\n",
"mode_of_interest = None\n",
"include_test_users = False"
"include_test_users = False\n",
"dynamic_labels = {}"
]
},
{
Expand Down Expand Up @@ -85,6 +86,7 @@
" month,\n",
" program,\n",
" study_type,\n",
" dynamic_labels,\n",
" dic_re,\n",
" include_test_users=include_test_users)\n",
"expanded_ct = scaffolding.add_energy_labels(expanded_ct, df_ei, dic_fuel) if \"mode_confirm\" in expanded_ct.columns else expanded_ct"
Expand Down Expand Up @@ -364,7 +366,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.12"
"version": "3.9.6"
iantei marked this conversation as resolved.
Show resolved Hide resolved
}
},
"nbformat": 4,
Expand Down
8 changes: 5 additions & 3 deletions viz_scripts/mode_specific_metrics.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"program = \"default\"\n",
"study_type = \"program\"\n",
"mode_of_interest = \"e-bike\"\n",
"include_test_users = False"
"include_test_users = False\n",
"dynamic_labels_url = \"https://raw.githubusercontent.com/e-mission/nrel-openpath-deploy-configs/main/label_options/example-program-label-options.json\""
]
},
{
Expand Down Expand Up @@ -102,6 +103,7 @@
" month,\n",
" program,\n",
" study_type,\n",
" dynamic_labels_url,\n",
" dic_re,\n",
" dic_pur=dic_pur,\n",
" include_test_users=include_test_users)"
Expand Down Expand Up @@ -266,7 +268,7 @@
" y2 = \"Count\"\n",
"\n",
" plot_title= plot_title_no_quality+\"\\n\"+quality_text\n",
" barplot_mode(data,x,y,plot_title,file_name)\n",
" barplot_mode(data,x,y,plot_title, expanded_ct['Mode_confirm'].dropna().unique().tolist(), file_name)\n",
" alt_text = store_alt_text_bar(pd.DataFrame(data['Average (miles)'].values, data.Replaced_mode), file_name, plot_title)\n",
"except:\n",
" generate_missing_plot(plot_title_no_quality,debug_df,file_name)\n",
Expand Down Expand Up @@ -365,7 +367,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.12"
"version": "3.9.6"
iantei marked this conversation as resolved.
Show resolved Hide resolved
}
},
"nbformat": 4,
Expand Down
6 changes: 4 additions & 2 deletions viz_scripts/mode_specific_timeseries.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"program = \"default\"\n",
"study_type = \"program\"\n",
"mode_of_interest = \"e-bike\"\n",
"include_test_users = False"
"include_test_users = False\n",
"dynamic_labels = { }"
]
},
{
Expand Down Expand Up @@ -95,6 +96,7 @@
" month,\n",
" program,\n",
" study_type,\n",
" dynamic_labels,\n",
" dic_re,\n",
" dic_pur=dic_pur,\n",
" include_test_users=include_test_users)"
Expand Down Expand Up @@ -483,7 +485,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.12"
"version": "3.9.6"
iantei marked this conversation as resolved.
Show resolved Hide resolved
}
},
"nbformat": 4,
Expand Down
69 changes: 7 additions & 62 deletions viz_scripts/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,29 +51,8 @@ def merge_small_entries(labels, values):
return (v2l_df.index.to_list(),v2l_df.vals.to_list())

def pie_chart_mode(plot_title,labels,values,file_name):
all_labels= ['Gas Car, drove alone',
'Bus',
'Train',
'Free Shuttle',
'Taxi/Uber/Lyft',
'Gas Car, with others',
'Bikeshare',
'Scooter share',
'E-bike',
'Walk',
'Skate board',
'Regular Bike',
'Not a Trip',
'No Travel',
'Same Mode',
'E-car, drove alone',
'E-car, with others',
'Air',
'Other']

val2labeldf = pd.DataFrame({"labels": labels, "values": values})

colours = dict(zip(all_labels, plt.cm.tab20.colors[:len(all_labels)]))
colors = dict(zip(labels, plt.cm.tab20.colors[:len(labels)]))
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(aspect="equal"))

m_labels, m_values = merge_small_entries(labels, values)
Expand All @@ -85,7 +64,7 @@ def func(pct, values):

wedges, texts, autotexts = ax.pie(m_values,
labels = m_labels,
colors=[colours[key] for key in labels],
colors=[colors[key] for key in labels],
shankari marked this conversation as resolved.
Show resolved Hide resolved
pctdistance=0.75,
autopct= lambda pct: func(pct, values),
textprops={'size': 23})
Expand All @@ -97,22 +76,8 @@ def func(pct, values):
plt.show()

def pie_chart_purpose(plot_title,labels,values,file_name):
labels_trip= ['Work',
'Home',
'Meal',
'Shopping',
'Personal/Medical',
'Recreation/Exercise',
'Transit transfer',
'Pick-up/Drop off',
'Entertainment/Social',
'Other',
'School',
'Religious',
'No travel',
'not_a_trip']

iantei marked this conversation as resolved.
Show resolved Hide resolved
colours = dict(zip(labels_trip, plt.cm.tab20.colors[:len(labels_trip)]))
colors = dict(zip(labels, plt.cm.tab20.colors[:len(labels)]))
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(aspect="equal"))

m_labels, m_values = merge_small_entries(labels, values)
Expand All @@ -124,7 +89,7 @@ def func(pct, values):

wedges, texts, autotexts = ax.pie(m_values,
labels = m_labels,
colors=[colours[key] for key in labels],
colors=[colors[key] for key in labels],
shankari marked this conversation as resolved.
Show resolved Hide resolved
pctdistance=0.85,
autopct=lambda pct: func(pct, values),
textprops={'size': 23})
Expand Down Expand Up @@ -181,32 +146,12 @@ def energy_impact(x,y,color,plot_title,file_name):
plt.legend(labels=objects, handles=patches, loc='upper right', borderaxespad=0, fontsize=15, frameon=True)
plt.savefig(SAVE_DIR+file_name+".png", bbox_inches='tight')

def barplot_mode(data,x,y,plot_title,file_name):
all_labels= ['Gas Car, drove alone',
'Bus',
'Train',
'Free Shuttle',
'Taxi/Uber/Lyft',
'Gas Car, with others',
'Bikeshare',
'Scooter share',
'E-bike',
'Walk',
'Skate board',
'Regular Bike',
'Not a Trip',
'No Travel',
'Same Mode',
'E-car, drove alone',
'E-car, with others',
'Air',
'Other']

colours = dict(zip(all_labels, plt.cm.tab20.colors[:len(all_labels)]))
def barplot_mode(data,x,y,plot_title, labels, file_name):
colors = dict(zip(labels, plt.cm.tab20.colors[:len(labels)]))
sns.set(font_scale=1.5)
f = plt.subplots(figsize=(15, 6))
sns.set(style='whitegrid')
ax = sns.barplot(x=x, y=y, palette=colours,data=data, ci=None)
ax = sns.barplot(x=x, y=y, palette=colors,data=data, ci=None)
shankari marked this conversation as resolved.
Show resolved Hide resolved
plt.xlabel(x, fontsize=23)
plt.ylabel(y, fontsize=23)
plt.title(plot_title, fontsize=25)
Expand Down
30 changes: 24 additions & 6 deletions viz_scripts/scaffolding.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import pandas as pd
import numpy as np
import sys
import requests
import json

import emission.storage.timeseries.abstract_timeseries as esta
import emission.storage.timeseries.tcquery as esttc
Expand Down Expand Up @@ -106,7 +108,12 @@ def expand_userinputs(labeled_ct):
unique_users = lambda df: len(df.user_id.unique()) if "user_id" in df.columns else 0
trip_label_count = lambda s, df: len(df[s].dropna()) if s in df.columns else 0

def load_viz_notebook_data(year, month, program, study_type, dic_re, dic_pur=None, include_test_users=False):
# Function to map: Selected an "old_mode" col from expanded_ct and
# map to the value of dic_translations into "new mode" col of expanded_ct
def update_expanded_ct(expanded_ct, new_mode, old_mode, dic_mapping):
expanded_ct[new_mode] = expanded_ct[old_mode].map(dic_mapping)

iantei marked this conversation as resolved.
Show resolved Hide resolved
def load_viz_notebook_data(year, month, program, study_type, dynamic_labels, dic_re, dic_pur=None, include_test_users=False):
shankari marked this conversation as resolved.
Show resolved Hide resolved
""" Inputs:
year/month/program/study_type = parameters from the visualization notebook
dic_* = label mappings; if dic_pur is included it will be used to recode trip purpose
Expand All @@ -124,15 +131,26 @@ def load_viz_notebook_data(year, month, program, study_type, dic_re, dic_pur=Non
# CASE 2 of https://github.com/e-mission/em-public-dashboard/issues/69#issuecomment-1256835867
if "distance" in expanded_ct.columns:
unit_conversions(expanded_ct)

# Mapping new mode labels with dictionaries

# Extract translations key
dic_translations = dict()
if "translations" in dynamic_labels and "en" in dynamic_labels["translations"]:
dic_translations = dynamic_labels["translations"]["en"]

# Select the mapping based on availability of dynamic_labels
if dic_translations:
dic_mapping = dic_translations
else:
dic_mapping = dic_re

# Map new mode labels with translations dictionary from dynamic_labels
# CASE 2 of https://github.com/e-mission/em-public-dashboard/issues/69#issuecomment-1256835867
if "mode_confirm" in expanded_ct.columns:
expanded_ct['Mode_confirm']= expanded_ct['mode_confirm'].map(dic_re)
update_expanded_ct(expanded_ct, "Mode_confirm", "mode_confirm", dic_mapping)
if study_type == 'program':
# CASE 2 of https://github.com/e-mission/em-public-dashboard/issues/69#issuecomment-1256835867
if 'replaced_mode' in expanded_ct.columns:
expanded_ct['Replaced_mode']= expanded_ct['replaced_mode'].map(dic_re)
update_expanded_ct(expanded_ct, "Replaced_mode", "replaced_mode", dic_mapping)
else:
print("This is a program, but no replaced modes found. Likely cold start case. Ignoring replaced mode mapping")
else:
Expand All @@ -141,7 +159,7 @@ def load_viz_notebook_data(year, month, program, study_type, dic_re, dic_pur=Non
# Trip purpose mapping
# CASE 2 of https://github.com/e-mission/em-public-dashboard/issues/69#issuecomment-1256835867
if dic_pur is not None and "purpose_confirm" in expanded_ct.columns:
expanded_ct['Trip_purpose']= expanded_ct['purpose_confirm'].map(dic_pur)
update_expanded_ct(expanded_ct, "Trip_purpose", "purpose_confirm", dic_pur)

# Document data quality
file_suffix = get_file_suffix(year, month, program)
Expand Down