import scipy.stats
import numpy as np
import matplotlib.pyplot as plt
import math
import pandas as pd
x = np.linspace(0,75, 1001)
general_median = 30
general_sd = 20
# Weibull distribution
scale = 34.736
shape = 2.5
# Gamma distribution
gamma_loc = 3.5
gamma_scale = 12.5
gamma_alpha = 2.45
# Gompertz distribution
gompertz_scale = 16.2
gompertz_loc = -58.2
gompertz_shape = 0.003
# Lognormal distribution
logn_scale = 29
logn_loc = 1
logn_shape = 0.5495
plt.rcParams["figure.figsize"] = [9, 4.8]
plt.subplot(1, 2, 1)
plt1, = plt.plot(x,
scipy.stats.norm.sf(x=x, loc = general_median, scale = general_sd),
color = '#1f77b4')
plt2, = plt.plot(x,
scipy.stats.weibull_min.sf(x=x, c=shape, loc=0, scale=scale),
linestyle='--', color = '#ff7f0e')
plt3, = plt.plot(x,
scipy.stats.gamma.sf(x, gamma_alpha, gamma_loc, gamma_scale),
linestyle=':', color = '#2ca02c')
plt4, = plt.plot(x,
scipy.stats.gompertz.sf(x, gompertz_shape, gompertz_loc, gompertz_scale),
linestyle='--', color = u'#e377c2')
plt5, = plt.plot(x,
scipy.stats.lognorm.sf(x, logn_shape, logn_loc, logn_scale),
linestyle = 'dashdot', color = u'#d62728')
plt.text(-10.8, 1.09, 'A', size=20, weight='bold')
plt.xlabel('Year')
plt.ylabel('Reliability')
plt.subplot(1, 2, 2)
plt1, = plt.plot(x,
[a / b for a, b in zip(scipy.stats.norm.pdf(x=x, loc = general_median, scale = general_sd), scipy.stats.norm.sf(x=x, loc = general_median, scale = general_sd))],
color = '#1f77b4')
plt2, = plt.plot(x,
[a / b for a, b in zip(scipy.stats.weibull_min.pdf(x=x, c=shape, loc=0, scale=scale), scipy.stats.weibull_min.sf(x=x, c=shape, loc=0, scale=scale))],
linestyle='--', color = '#ff7f0e')
plt3, = plt.plot(x,
[a / b for a, b in zip(scipy.stats.gamma.pdf(x, gamma_alpha, gamma_loc, gamma_scale), scipy.stats.gamma.sf(x, gamma_alpha, gamma_loc, gamma_scale))],
linestyle=':', color = '#2ca02c')
plt4, = plt.plot(x,
[a / b for a, b in zip(scipy.stats.gompertz.pdf(x, gompertz_shape, gompertz_loc, gompertz_scale), scipy.stats.gompertz.sf(x, gompertz_shape, gompertz_loc, gompertz_scale))],
linestyle='--', color = u'#e377c2')
plt5, = plt.plot(x,
[a / b for a, b in zip(scipy.stats.lognorm.pdf(x, logn_shape, logn_loc, logn_scale), scipy.stats.lognorm.sf(x, logn_shape, logn_loc, logn_scale))],
linestyle = 'dashdot', color = u'#d62728')
plt.text(-12, 0.26, 'B', size=20, weight='bold')
plt.ylim(0, 0.25)
plt.xlabel('Year')
plt.ylabel('Hazard rate')
plt.legend([plt1,plt2,plt3, plt4, plt5], ['Normal', 'Weibull', 'Gamma', 'Gompertz', 'Log-normal'], loc = 'upper left')
plt.tight_layout()
plt.show()
plt.clf() # Clear figure
<Figure size 648x345.6 with 0 Axes>
x = np.linspace(0, 7, 1001)
plt.rcParams["figure.figsize"] = [9, 4.8]
# plot 1
plt.subplot(1, 2, 1)
plt1, = plt.plot(x, scipy.stats.weibull_min.sf(x=x, c=0.6, loc=0, scale=2.5)*100)
plt2, = plt.plot(x, scipy.stats.weibull_min.sf(x=x, c=1, loc=0, scale=2.5)*100)
plt3, = plt.plot(x, scipy.stats.weibull_min.sf(x=x, c=1.7, loc=0, scale=2.5)*100)
plt.text(-1.1, 110, 'A', size=20, weight='bold')
plt.xlabel('Year')
plt.ylabel('Proportion surviving in %')
plt.subplot(1, 2, 2)
plt1, = plt.plot(x, scipy.stats.weibull_min.pdf(x=x, c=0.6, loc=0, scale=2.5))
plt2, = plt.plot(x, scipy.stats.weibull_min.pdf(x=x, c=1, loc=0, scale=2.5))
plt3, = plt.plot(x, scipy.stats.weibull_min.pdf(x=x, c=1.7, loc=0, scale=2.5))
plt.text(-1.1, 2.7, 'B', size=20, weight='bold')
plt.xlabel('Year')
plt.ylabel('Failure rate in %')
plt.legend([plt3,plt2,plt1], [r'$\beta = 1.7$', r'$\beta = 1$', r'$\beta = 0.6$'], loc = 'upper right')
plt.tight_layout()
plt.show()
plt.clf() # Clear figure
c:\Users\rapha\.conda\envs\master_thesis\lib\site-packages\scipy\stats\_continuous_distns.py:2108: RuntimeWarning: divide by zero encountered in power return c*pow(x, c-1)*np.exp(-pow(x, c))
<Figure size 648x345.6 with 0 Axes>
from functions import triang_dist_inputs_survival_case_3, triang_dist_inputs_survival_case_4
plt.rcParams["figure.figsize"] = [9.5, 4.8]
general_mean = 1
x_values = np.linspace(0.4, 1.6, 1201)
monte_carlo_input_distributions_pd = pd.DataFrame({'x' : x_values})
monte_carlo_input_distributions_pd['1: Normal distribution'] = scipy.stats.skewnorm.pdf(x_values, a = 0, loc = general_mean, scale = 0.05)
monte_carlo_input_distributions_pd['2: Normal distribution'] = scipy.stats.skewnorm.pdf(x_values, a = 0, loc = general_mean, scale = 0.1)
loc, scale, c = triang_dist_inputs_survival_case_3(general_mean, lower_bound= 0.6)
monte_carlo_input_distributions_pd['3: Triangular distribution'] = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
loc, scale, c = triang_dist_inputs_survival_case_4(general_mean, lower_bound = 0.5)
monte_carlo_input_distributions_pd['4: Triangular distribution'] = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
monte_carlo_input_distributions_pd['5: Uniform distribution'] = scipy.stats.uniform.pdf(x_values, loc = 0.5, scale = 1)
plt.subplot(1, 2, 1)
plt1, = plt.plot(monte_carlo_input_distributions_pd['x'], monte_carlo_input_distributions_pd['1: Normal distribution'], color = u'#ff7f0e')
plt2, = plt.plot(monte_carlo_input_distributions_pd['x'], monte_carlo_input_distributions_pd['2: Normal distribution'], color = u'#2ca02c')
plt3, = plt.plot(monte_carlo_input_distributions_pd['x'], monte_carlo_input_distributions_pd['3: Triangular distribution'], color = u'#d62728')
plt4, = plt.plot(monte_carlo_input_distributions_pd['x'], monte_carlo_input_distributions_pd['4: Triangular distribution'], color = u'#9467bd')
plt5, = plt.plot(monte_carlo_input_distributions_pd['x'], monte_carlo_input_distributions_pd['5: Uniform distribution'], color = u'#8c564b')
plt.text(0.26, 8.5, 'A', size=20, weight='bold')
plt.xlabel('Multiplier survival curves')
plt.ylabel('Probability by density in %')
# Second plot
x_values = np.linspace(0.6, 1.6, 1201)
monte_carlo_input_distributions_pd = pd.DataFrame({'x' : x_values})
monte_carlo_input_distributions_pd['1: Normal distribution'] = scipy.stats.skewnorm.pdf(x_values, a = 0, loc = general_mean, scale = 0.05)
monte_carlo_input_distributions_pd['2: Normal distribution'] = scipy.stats.skewnorm.pdf(x_values, a = 0, loc = general_mean, scale = 0.1)
loc, scale, c = triang_dist_inputs_survival_case_3(general_mean, lower_bound= 0.7)
monte_carlo_input_distributions_pd['3: Triangular distribution'] = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
loc, scale, c = triang_dist_inputs_survival_case_4(general_mean, lower_bound = 0.7)
monte_carlo_input_distributions_pd['4: Triangular distribution'] = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
monte_carlo_input_distributions_pd['5: Uniform distribution'] = scipy.stats.uniform.pdf(x_values, loc = 0.7, scale = 0.8)
plt.subplot(1, 2, 2)
plt1, = plt.plot(monte_carlo_input_distributions_pd['x'], monte_carlo_input_distributions_pd['1: Normal distribution'], color = u'#ff7f0e')
plt2, = plt.plot(monte_carlo_input_distributions_pd['x'], monte_carlo_input_distributions_pd['2: Normal distribution'], color = u'#2ca02c')
plt3, = plt.plot(monte_carlo_input_distributions_pd['x'], monte_carlo_input_distributions_pd['3: Triangular distribution'], color = u'#d62728')
plt4, = plt.plot(monte_carlo_input_distributions_pd['x'], monte_carlo_input_distributions_pd['4: Triangular distribution'], color = u'#9467bd')
plt5, = plt.plot(monte_carlo_input_distributions_pd['x'], monte_carlo_input_distributions_pd['5: Uniform distribution'], color = u'#8c564b')
plt.text(0.48, 8.5, 'B', size=20, weight='bold')
plt.xlabel('Multiplier survival curves')
plt.ylabel('Probability by density in %')
plt.legend([plt1,plt2,plt3,plt4, plt5], ['1: Normal distribution', '2: Normal distribution', '3: Triangular distribution', '4: Triangular distribution', '5: Uniform distribution'], loc = 'upper right')
plt.tight_layout()
plt.show()
plt.clf() # Clear figure
<Figure size 684x345.6 with 0 Axes>
from functions import skew_factor_loc_and_scale_by_mean_sd, triang_dist_inputs_case_3, triang_dist_inputs_case_4, shape_folded_case_2
graph_name = 'distribution_not_survival_curves'
x_values = np.linspace(-0.1, 1.1, 1001)
monte_carlo_input_distributions_loc_01_pd = pd.DataFrame({'x': x_values})
# data
mean_center = 0.5
# skewed Normal distribution with sd = 0.05
a, loc, scale = skew_factor_loc_and_scale_by_mean_sd(mean_center, 0.05)
if loc > 0.05 and loc < 0.95:
monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'] = scipy.stats.skewnorm.pdf(x_values, a = a, loc = loc, scale = scale)
else:
if loc < 0.5:
c = shape_folded_case_1(mean_center)
monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'] = scipy.stats.foldnorm.pdf(x_values, c = c, loc = 0.0, scale = 0.05)
else:
c = shape_folded_case_1(1-mean_center)
new_x = x_values.tolist()
new_x.reverse()
monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'] = scipy.stats.foldnorm.pdf(new_x, c = c, loc = 0.0, scale = 0.05)
# skewed normal distribution with sd = 0.1
a, loc, scale = skew_factor_loc_and_scale_by_mean_sd(mean_center, 0.1)
if loc > 0.1 and loc < 0.9:
monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'] = scipy.stats.skewnorm.pdf(x_values, a = a, loc = loc, scale = scale)
else:
if loc < 0.5:
c = shape_folded_case_2(mean_center)
monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'] = scipy.stats.foldnorm.pdf(x_values, c = c, loc = 0.0, scale = 0.1)
else:
c = shape_folded_case_2(1-mean_center)
new_x = x_values.tolist()
new_x.reverse()
monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'] = scipy.stats.foldnorm.pdf(new_x, c = c, loc = 0.0, scale = 0.1)
# Triangular distributions
# Case 3
loc, scale, c = triang_dist_inputs_case_3(mean_center)
monte_carlo_input_distributions_loc_01_pd['3: Triangular distribution'] = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
# Case 4
loc, scale, c = triang_dist_inputs_case_4(mean_center)
monte_carlo_input_distributions_loc_01_pd['4: Triangular distribution'] = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
# Uniform distribution
monte_carlo_input_distributions_loc_01_pd['5: Uniform distribution'] = scipy.stats.uniform.pdf(x_values, loc = 0, scale = 1)
plt.rcParams["figure.figsize"] = [9, 4.8]
plt.subplot(1, 2, 1)
plt1, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'], color = u'#ff7f0e')
plt2, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'], color = u'#2ca02c')
plt3, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['3: Triangular distribution'], color = u'#d62728')
plt4, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['4: Triangular distribution'], color = u'#9467bd')
plt5, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['5: Uniform distribution'], color = u'#8c564b')
plt.text(-0.25, 8.5, 'A', size=20, weight='bold')
plt.xlabel('Generated input value')
plt.ylabel('Probability by density in %')
###################### Plot 2
# data
mean_center = 0.2
# skewed Normal distribution with sd = 0.05
a, loc, scale = skew_factor_loc_and_scale_by_mean_sd(mean_center, 0.05)
if loc > 0.05 and loc < 0.95:
monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'] = scipy.stats.skewnorm.pdf(x_values, a = a, loc = loc, scale = scale)
else:
if loc < 0.5:
c = shape_folded_case_1(mean_center)
monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'] = scipy.stats.foldnorm.pdf(x_values, c = c, loc = 0.0, scale = 0.05)
else:
c = shape_folded_case_1(1-mean_center)
new_x = x_values.tolist()
new_x.reverse()
monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'] = scipy.stats.foldnorm.pdf(new_x, c = c, loc = 0.0, scale = 0.05)
# skewed normal distribution with sd = 0.1
a, loc, scale = skew_factor_loc_and_scale_by_mean_sd(mean_center, 0.1)
if loc > 0.1 and loc < 0.9:
monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'] = scipy.stats.skewnorm.pdf(x_values, a = a, loc = loc, scale = scale)
else:
if loc < 0.5:
c = shape_folded_case_2(mean_center)
monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'] = scipy.stats.foldnorm.pdf(x_values, c = c, loc = 0.0, scale = 0.1)
else:
c = shape_folded_case_2(1-mean_center)
new_x = x_values.tolist()
new_x.reverse()
monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'] = scipy.stats.foldnorm.pdf(new_x, c = c, loc = 0.0, scale = 0.1)
# Triangular distributions
# Case 3
loc, scale, c = triang_dist_inputs_case_3(mean_center)
monte_carlo_input_distributions_loc_01_pd['3: Triangular distribution'] = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
# Case 4
loc, scale, c = triang_dist_inputs_case_4(mean_center)
monte_carlo_input_distributions_loc_01_pd['4: Triangular distribution'] = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
# Uniform distribution
monte_carlo_input_distributions_loc_01_pd['5: Uniform distribution'] = scipy.stats.uniform.pdf(x_values, loc = 0, scale = 1)
plt.subplot(1, 2, 2)
plt1, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'], color = u'#ff7f0e')
plt2, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'], color = u'#2ca02c')
plt3, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['3: Triangular distribution'], color = u'#d62728')
plt4, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['4: Triangular distribution'], color = u'#9467bd')
plt5, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['5: Uniform distribution'], color = u'#8c564b')
plt.text(-0.25, 9.65, 'B', size=20, weight='bold')
plt.xlabel('Generated input value')
plt.ylabel('Probability by density in %')
plt.legend([plt1,plt2,plt3,plt4, plt5], ['1: Normal distribution', '2: Normal distribution', '3: Triangular distribution', '4: Triangular distribution', '5: Uniform distribution'], loc = 'upper right')
plt.tight_layout()
plt.show()
plt.clf() # Clear figure
<Figure size 648x345.6 with 0 Axes>
x_values = np.linspace(-0.1, 1.1, 1001)
monte_carlo_input_distributions_loc_01_pd = pd.DataFrame({'x': x_values})
# data
mean_center = 0.4
# skewed Normal distribution with sd = 0.05
a, loc, scale = skew_factor_loc_and_scale_by_mean_sd(mean_center, 0.05)
if loc > 0.05 and loc < 0.95:
monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'] = scipy.stats.skewnorm.pdf(x_values, a = a, loc = loc, scale = scale)
else:
if loc < 0.5:
c = shape_folded_case_1(mean_center)
monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'] = scipy.stats.foldnorm.pdf(x_values, c = c, loc = 0.0, scale = 0.05)
else:
c = shape_folded_case_1(1-mean_center)
new_x = x_values.tolist()
new_x.reverse()
monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'] = scipy.stats.foldnorm.pdf(new_x, c = c, loc = 0.0, scale = 0.05)
# skewed normal distribution with sd = 0.1
a, loc, scale = skew_factor_loc_and_scale_by_mean_sd(mean_center, 0.1)
if loc > 0.1 and loc < 0.9:
monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'] = scipy.stats.skewnorm.pdf(x_values, a = a, loc = loc, scale = scale)
else:
if loc < 0.5:
c = shape_folded_case_2(mean_center)
monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'] = scipy.stats.foldnorm.pdf(x_values, c = c, loc = 0.0, scale = 0.1)
else:
c = shape_folded_case_2(1-mean_center)
new_x = x_values.tolist()
new_x.reverse()
monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'] = scipy.stats.foldnorm.pdf(new_x, c = c, loc = 0.0, scale = 0.1)
# Triangular distributions
# Case 3
loc, scale, c = triang_dist_inputs_case_3(mean_center)
monte_carlo_input_distributions_loc_01_pd['3: Triangular distribution'] = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
# Case 4
loc, scale, c = triang_dist_inputs_case_4(mean_center)
monte_carlo_input_distributions_loc_01_pd['4: Triangular distribution'] = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
# Uniform distribution
monte_carlo_input_distributions_loc_01_pd['5: Uniform distribution'] = scipy.stats.uniform.pdf(x_values, loc = 0, scale = 1)
plt.rcParams["figure.figsize"] = [6.4, 4.8]
plt.subplot(1, 1, 1)
plt1, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['1: Normal distribution'], color = u'#ff7f0e')
plt2, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['2: Normal distribution'], color = u'#2ca02c')
plt3, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['3: Triangular distribution'], color = u'#d62728')
plt4, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['4: Triangular distribution'], color = u'#9467bd')
plt5, = plt.plot(monte_carlo_input_distributions_loc_01_pd['x'], monte_carlo_input_distributions_loc_01_pd['5: Uniform distribution'], color = u'#8c564b')
plt.xlabel('Generated input value')
plt.ylabel('Probability by density in %')
plt.legend([plt1,plt2,plt3,plt4, plt5], ['1: Normal distribution', '2: Normal distribution', '3: Triangular distribution', '4: Triangular distribution', '5: Uniform distribution'], loc = 'upper right')
plt.tight_layout()
plt.show()
plt.clf() # Clear figure
<Figure size 460.8x345.6 with 0 Axes>
from combined_reuse_matrace_model import evaluate_cohort_combined_model
# Execute model
## import data
file_path = 'data_cobalt_case_study/data_input_cobalt_extended_data_set.xlsx'
defined_distributions_pd = pd.read_excel('data_cobalt_case_study/defined_distributions.xlsx')
data_sheets = pd.ExcelFile(file_path).sheet_names
data_dic = {}
for data_sheet in data_sheets:
try:
data_dic[data_sheet] = pd.read_excel(file_path,
sheet_name=data_sheet).set_index('Product categories')
except:
data_dic[data_sheet] = pd.read_excel(file_path,
sheet_name=data_sheet).set_index('Products')
n_years = 36
extended_data_dic, extended_reuse_data_dic, extended_graph_data_pd = evaluate_cohort_combined_model(data_dic=data_dic,
n_years=n_years, start_year=2015,
defined_distributions_pd= defined_distributions_pd,
print_state=False, separate_reuse_graph=True, considered_use_cycles=3)
extended_graph_data_pd = extended_graph_data_pd * 100
extended_graph_data_pd['Losses:'] = [0 for i in range(n_years)]
# Combine catalysts into one category
column_catalists = extended_graph_data_pd.columns[4:8]
extended_graph_data_pd['Catalysts'] = extended_graph_data_pd.loc[:,column_catalists].sum(axis = 1)
extended_graph_data_pd = extended_graph_data_pd.drop(columns= column_catalists)
# Reorder data frame
new_column_order = extended_graph_data_pd.columns[:4].to_list() + ['Catalysts']
new_column_order = new_column_order + extended_graph_data_pd.columns[4:-1].to_list()
extended_graph_data_pd = extended_graph_data_pd[new_column_order]
# set hatch color
plt.rcParams['hatch.color'] = 'white'
# Set graph name
graph_name = 'extended_combined_model_v2'
# set size parameter
plt.rcParams["figure.figsize"] = [8, 4.8]
# Set colors
color_map = [u'#1f77b4' for i in range(3)] + [u'#ff7f0e', u'#2ca02c', 'goldenrod', u'#9467bd', u'#8c564b', u'#e377c2', u'#7f7f7f', 'peru', 'peru'] + ['firebrick' for i in range(5)]
# Set hatches for portable batteries
hatches = ['', '\\\\', '||']
# Set alpha portable batteries
alpha = [1, 0.8, 0.6] + [1 for i in range(7)] + [1, 0.7] + [1, 0.8, 0.6, 0.4, 0.2, 0]
hatches_losses = ['//', '\\\\', '//','\\\\','//', '\\\\']
alpha_losses = 1
fig, ax = plt.subplots()
stacks = ax.stackplot(extended_graph_data_pd.index, extended_graph_data_pd.transpose().to_numpy(), colors=color_map)
for element_index, stack, product in zip(range(len(extended_graph_data_pd.columns)), stacks, extended_graph_data_pd.columns):
stack.set_alpha(alpha[element_index])
# Set hatch for first three elements
if element_index <= 2:
stack.set_hatch(hatches[element_index])
if element_index >= 12:
stack.set_hatch(hatches_losses.pop())
stack.set_label(product)
plt4, = plt.plot(extended_graph_data_pd.index, extended_graph_data_pd.iloc[:, 0:10].sum(axis='columns'),
color = 'black', linestyle = '--')
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
plt.legend([plt4] + [i for i in reversed(plt.legend().legendHandles)] , ['In-use stock'] + [i for i in reversed(extended_graph_data_pd.columns)], loc ='center left', bbox_to_anchor=(1, 0.5))
plt.ylabel('Stock distribution by product categories and outflows in %')
plt.xlabel('Year AD')
plt.tight_layout()
plt.show()
use_stocks = ['use_stock_1', 'use_stock_2', 'use_stock_3']
phases = ['first use', 'second_use', 'third_use']
products = extended_reuse_data_dic['1']['use_stock_1'].keys()
# Create data frame with years as index
use_stocks_pd = pd.DataFrame({})
use_stocks_pd['year'] = [i + 2015 for i in range(n_years)]
use_stocks_pd = use_stocks_pd.set_index('year')
# Adding empty rows to data frame for labels later
for phase in phases:
use_stocks_pd[phase] = [0 for i in range(n_years)]
for product in products:
for phase, stock in zip(phases, use_stocks):
# Empty lis to collect values
collector_list = []
for year in range(n_years):
# pupulate list with values:
collector_list.append(extended_reuse_data_dic[str(year)][stock][product])
# Add to dataframe
use_stocks_pd["{} {}".format(product, phase)] = collector_list
use_stocks_pd = use_stocks_pd * 100
plt.rcParams["figure.figsize"] = [6.4, 4.8]
# Set order
order = [0,1,2]
rest_elements = [i for i in range(3,10)]
rest_elements.reverse()
order = order + rest_elements
# Setting the lables for the legend
products_lable = products.copy()
products_lable = products_lable.to_list()
products_lable.reverse()
# Add lables for use phases
products_lable = products_lable + ['3rd use', '2nd use', '1st use']
# Setting colors
colors = [u'#1f77b4', u'#ff7f0e', u'#2ca02c', u'#d62728', u'#9467bd', u'#8c564b', u'#e377c2']
color_map = ['k','k','k']
# Set hatches for portable batteries
hatches = ['', '\\\\', '||']
# Set alpha portable batteries
alpha = [1, 0.8, 0.6]
for color in colors:
for i in range(3):
color_map.append(color)
fig, ax = plt.subplots()
stacks = ax.stackplot(use_stocks_pd.index, use_stocks_pd.transpose().to_numpy(), colors=color_map)
# Iteration to set hatches
counter = 0
full_counter = 0
for stack in stacks:
stack.set_hatch(hatches[counter])
stack.set_alpha(alpha[counter])
if full_counter <= 2:
stack.set_label(products_lable.pop())
if counter == 0 and full_counter > 2:
stack.set_label(products_lable.pop())
#Increase counter
counter += 1
full_counter += 1
if counter == 3:
counter = 0
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
secax.set_ticks([i for i in range(0, 21, 2)])
plt.xlabel('Year AD')
plt.ylabel('In-use stock distribution in %')
plt.xlim(2015, 2035)
plt.xticks([i for i in range(2015, 2036, 2)])
# Take care of legend
handles, labels = plt.gca().get_legend_handles_labels()
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.show()
plt.close()
extended_reuse_data_dic['1']['use_stock_1']
Products smartphones 0.061623 mobile phones 0.005398 tablets 0.066902 laptops 0.138546 e-bikes 0.025635 power tools 0.016535 others 0.064644 Name: use_stock_1, dtype: float64
from base_matrace_model import evaluate_cohort
# Load data and define settings to execute model for extended data set and only matrace model
start_year = 2015
file_path = 'data_cobalt_case_study/data_input_cobalt_combined_data_set.xlsx'
data_sheets = pd.ExcelFile(file_path).sheet_names
data_dic = {}
for data_sheet in data_sheets:
try:
data_dic[data_sheet] = pd.read_excel(file_path,
sheet_name=data_sheet).set_index('Product categories')
except:
data_dic[data_sheet] = pd.read_excel(file_path,
sheet_name=data_sheet).set_index('Products')
# get data matrace model
matrace_data_dic, matrace_graph_data_pd = evaluate_cohort(data_dic['MaTrace_initial_inflow'], data_dic['MaTrace_in_use_stock'], data_dic['MaTrace_hibernating_stock'],
data_dic['MaTrace_end_of_life'], data_dic['MaTrace_B_recycling'], data_dic['MaTrace_D_secondary_material'], data_dic['MaTrace_production'], n_years, start_year,
defined_distributions_pd = defined_distributions_pd, print_state = False)
# get data Reuse-Matrace model with Combined Data Set
combined_data_dic, combined_reuse_data_dic, combined_graph_data_pd = evaluate_cohort_combined_model(data_dic, n_years, start_year,
defined_distributions_pd = defined_distributions_pd, print_state = False)
absolute_stock_comparison_portable_batteries_pd = pd.DataFrame({}, index=extended_graph_data_pd.index)
absolute_stock_comparison_portable_batteries_pd['MaTrace model by Godoy León et al. (2020)'] = matrace_graph_data_pd.iloc[:,0] * 100
absolute_stock_comparison_portable_batteries_pd['Reuse-MaTrace model - Data set I'] = combined_graph_data_pd.iloc[:,:2].sum(axis=1) * 100
absolute_stock_comparison_portable_batteries_pd['Reuse-MaTrace model - Data set II'] = extended_graph_data_pd.iloc[:,:2].sum(axis=1)
absolute_stock_comparison_pd = pd.DataFrame({}, index=extended_graph_data_pd.index)
absolute_stock_comparison_pd['MaTrace model by Godoy León et al. (2020)'] = matrace_graph_data_pd.iloc[:,:8].sum(axis=1) * 100
absolute_stock_comparison_pd['Reuse-MaTrace model - Data set I'] = combined_graph_data_pd.iloc[:,:13].sum(axis=1) * 100
absolute_stock_comparison_pd['Reuse-MaTrace model - Data set II'] = extended_graph_data_pd.iloc[:,:10].sum(axis=1)
# Define function returning crossing between two lines
def return_time_of_corssing(target, df, column):
last_above = np.where(df[column] > target)
last_above = df.index[last_above[0][-1]]
first_below = last_above +1
slope = df[column].loc[first_below] - df[column].loc[last_above]
# location see notices ipad
location = last_above + (target - df[column].loc[last_above]) / slope
return location
from cProfile import label
import functools
# create graph
plt.rcParams["figure.figsize"] = [9, 4.8]
fig = plt.figure()
ax = fig.add_subplot(1, 2, 1)
plt1, = plt.plot(absolute_stock_comparison_pd.index, absolute_stock_comparison_pd['MaTrace model by Godoy León et al. (2020)'], color = u'#ff7f0e')
plt2, = plt.plot(absolute_stock_comparison_pd.index, absolute_stock_comparison_pd['Reuse-MaTrace model - Data set I'], color = u'#2ca02c')
plt3, = plt.plot(absolute_stock_comparison_pd.index, absolute_stock_comparison_pd['Reuse-MaTrace model - Data set II'], color = u'#d62728')
# Vertical lines
plt.axvline(x = return_time_of_corssing(50, absolute_stock_comparison_pd, 'MaTrace model by Godoy León et al. (2020)'), ymin = 0.0, ymax = 0.485, color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(50, absolute_stock_comparison_pd, 'Reuse-MaTrace model - Data set I'), ymin = 0.0, ymax = 0.485, color = u'#2ca02c', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(50, absolute_stock_comparison_pd, 'Reuse-MaTrace model - Data set II'), ymin = 0.0, ymax = 0.485, color = u'#d62728', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(25, absolute_stock_comparison_pd, 'MaTrace model by Godoy León et al. (2020)'), ymin = 0.0, ymax = 0.25, color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(25, absolute_stock_comparison_pd, 'Reuse-MaTrace model - Data set I'), ymin = 0.0, ymax = 0.25, color = u'#2ca02c', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(25, absolute_stock_comparison_pd, 'Reuse-MaTrace model - Data set II'), ymin = 0.0, ymax = 0.25, color = u'#d62728', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(75, absolute_stock_comparison_pd, 'MaTrace model by Godoy León et al. (2020)'), ymin = 0.0, ymax = 0.725, color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(75, absolute_stock_comparison_pd, 'Reuse-MaTrace model - Data set I'), ymin = 0.0, ymax = 0.725, color = u'#2ca02c', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(75, absolute_stock_comparison_pd, 'Reuse-MaTrace model - Data set II'), ymin = 0.0, ymax = 0.725, color = u'#d62728', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.yticks([0, 25, 50, 75, 100])
plt.grid(axis = 'y')
plt.text(2010, 115, 'A', size=20, weight='bold')
plt.ylabel('Total in-use stock in %')
ax.set_xlabel('Year AD')
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
ax = fig.add_subplot(1, 2, 2)
plt1, = plt.plot(absolute_stock_comparison_portable_batteries_pd.index, absolute_stock_comparison_portable_batteries_pd['MaTrace model by Godoy León et al. (2020)'], color = u'#ff7f0e')
plt2, = plt.plot(absolute_stock_comparison_portable_batteries_pd.index, absolute_stock_comparison_portable_batteries_pd['Reuse-MaTrace model - Data set I'], color = u'#2ca02c')
plt3, = plt.plot(absolute_stock_comparison_portable_batteries_pd.index, absolute_stock_comparison_portable_batteries_pd['Reuse-MaTrace model - Data set II'], color = u'#d62728')
start_value = absolute_stock_comparison_portable_batteries_pd.iloc[0,0]
# Vertical lines
plt.axvline(x = return_time_of_corssing(start_value * 0.5, absolute_stock_comparison_portable_batteries_pd, 'MaTrace model by Godoy León et al. (2020)'), ymin = 0.0, ymax = 0.5, color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.5, absolute_stock_comparison_portable_batteries_pd, 'Reuse-MaTrace model - Data set I'), ymin = 0.0, ymax = 0.5, color = u'#2ca02c', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.5, absolute_stock_comparison_portable_batteries_pd, 'Reuse-MaTrace model - Data set II'), ymin = 0.0, ymax = 0.5, color = u'#d62728', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.25, absolute_stock_comparison_portable_batteries_pd, 'MaTrace model by Godoy León et al. (2020)'), ymin = 0.0, ymax = 0.275, color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.25, absolute_stock_comparison_portable_batteries_pd, 'Reuse-MaTrace model - Data set I'), ymin = 0.0, ymax = 0.275, color = u'#2ca02c', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.25, absolute_stock_comparison_portable_batteries_pd, 'Reuse-MaTrace model - Data set II'), ymin = 0.0, ymax = 0.275, color = u'#d62728', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.75, absolute_stock_comparison_portable_batteries_pd, 'MaTrace model by Godoy León et al. (2020)'), ymin = 0.0, ymax = 0.725, color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.75, absolute_stock_comparison_portable_batteries_pd, 'Reuse-MaTrace model - Data set I'), ymin = 0.0, ymax = 0.725, color = u'#2ca02c', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.75, absolute_stock_comparison_portable_batteries_pd, 'Reuse-MaTrace model - Data set II'), ymin = 0.0, ymax = 0.725, color = u'#d62728', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.yticks([i * 0.01 * start_value for i in [0, 25, 50, 75, 100]])
plt.grid(axis = 'y')
plt.xlim([2014, 2031])
plt.xticks([i for i in range(2015, 2031, 3)])
plt.ylabel('Total in-use stock of portable batteries in %')
plt.xlabel('Year AD')
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
secax.set_ticks([i for i in range(0,16,3)])
plt.text(2012.5, 47.38, 'B', size=20, weight='bold')
plt.legend([plt1,plt2,plt3], ['MaTrace model by \nGodoy León et al. (2020)', 'Reuse-MaTrace model \n(Combined Data Set)', 'Reuse-MaTrace model \n(Extended Data Set)'], loc = 'upper right')
plt.tight_layout()
plt.show()
plt.clf()
<Figure size 648x345.6 with 0 Axes>
relative_stock_comparison_portable_batteries_pd = pd.DataFrame({}, index = absolute_stock_comparison_portable_batteries_pd.index)
relative_stock_comparison_portable_batteries_pd['Reuse-MaTrace model - Data set I'] = (absolute_stock_comparison_portable_batteries_pd['Reuse-MaTrace model - Data set I'] / absolute_stock_comparison_portable_batteries_pd['MaTrace model by Godoy León et al. (2020)']) - 1
relative_stock_comparison_portable_batteries_pd['Reuse-MaTrace model - Data set II'] = (absolute_stock_comparison_portable_batteries_pd['Reuse-MaTrace model - Data set II'] / absolute_stock_comparison_portable_batteries_pd['MaTrace model by Godoy León et al. (2020)']) - 1
relative_stock_comparison_portable_batteries_pd = relative_stock_comparison_portable_batteries_pd * 100
relative_stock_comparison_pd = pd.DataFrame({}, index = absolute_stock_comparison_pd.index)
relative_stock_comparison_pd['Reuse-MaTrace model - Data set I'] = (absolute_stock_comparison_pd['Reuse-MaTrace model - Data set I'] / absolute_stock_comparison_pd['MaTrace model by Godoy León et al. (2020)']) - 1
relative_stock_comparison_pd['Reuse-MaTrace model - Data set II'] = (absolute_stock_comparison_pd['Reuse-MaTrace model - Data set II'] / absolute_stock_comparison_pd['MaTrace model by Godoy León et al. (2020)']) - 1
relative_stock_comparison_pd = relative_stock_comparison_pd * 100
plt.rcParams["figure.figsize"] = [9, 4.8]
fig = plt.figure()
ax = fig.add_subplot(1, 2, 1)
plt1, = plt.plot(relative_stock_comparison_pd.index, [0 for i in relative_stock_comparison_pd['Reuse-MaTrace model - Data set I']], color = u'#ff7f0e')
plt2, = plt.plot(relative_stock_comparison_pd.index, relative_stock_comparison_pd['Reuse-MaTrace model - Data set I'], color = u'#2ca02c')
plt3, = plt.plot(relative_stock_comparison_pd.index, relative_stock_comparison_pd['Reuse-MaTrace model - Data set II'], color = u'#d62728')
# Vertical lines
plt.axvline(x = return_time_of_corssing(50, absolute_stock_comparison_pd, 'MaTrace model by Godoy León et al. (2020)'), color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(25, absolute_stock_comparison_pd, 'MaTrace model by Godoy León et al. (2020)'), color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(75, absolute_stock_comparison_pd, 'MaTrace model by Godoy León et al. (2020)'), color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.ylabel('Relative deviation of total in-use stock in %')
plt.xlabel('Year AD')
plt.text(2009.5, 16.4, 'A', size=20, weight='bold')
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
ax = fig.add_subplot(1, 2, 2)
plt1, = plt.plot(relative_stock_comparison_pd.index, [0 for i in relative_stock_comparison_pd['Reuse-MaTrace model - Data set I']], color = u'#ff7f0e')
plt2, = plt.plot(relative_stock_comparison_portable_batteries_pd.index, relative_stock_comparison_portable_batteries_pd['Reuse-MaTrace model - Data set I'], color = u'#2ca02c')
plt3, = plt.plot(relative_stock_comparison_portable_batteries_pd.index, relative_stock_comparison_portable_batteries_pd['Reuse-MaTrace model - Data set II'], color = u'#d62728')
start_value = absolute_stock_comparison_portable_batteries_pd.iloc[0,0]
# Vertical lines
plt.axvline(x = return_time_of_corssing(start_value * 0.5, absolute_stock_comparison_portable_batteries_pd, 'MaTrace model by Godoy León et al. (2020)'), color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.25, absolute_stock_comparison_portable_batteries_pd, 'MaTrace model by Godoy León et al. (2020)'), color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.75, absolute_stock_comparison_portable_batteries_pd, 'MaTrace model by Godoy León et al. (2020)'), color = u'#ff7f0e', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.xlim([2014, 2026])
plt.xticks([i for i in range(2015, 2026, 2)])
plt.ylim([-20, 150])
plt.text(2012.9, 165, 'B', size=20, weight='bold')
plt.ylabel('Relative deviation of portable batteries in-use stock in %')
plt.xlabel('Year AD')
plt.legend([plt1,plt2,plt3], ['MaTrace model by \nGodoy León et al. (2020)', 'Reuse-MaTrace model \n(Combined Data Set)', 'Reuse-MaTrace model \n(Extended Data Set)'], loc = 'upper right')
plt.tight_layout()
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
plt.show()
plt.clf() # Clear figure
<Figure size 648x345.6 with 0 Axes>
# Create data:
file_path = 'data_cobalt_case_study/data_input_cobalt_extended_data_set.xlsx'
defined_distributions_pd = pd.read_excel('data_cobalt_case_study/defined_distributions.xlsx')
data_sheets = pd.ExcelFile(file_path).sheet_names
data_dic = {}
for data_sheet in data_sheets:
try:
data_dic[data_sheet] = pd.read_excel(file_path,
sheet_name=data_sheet).set_index('Product categories')
except:
data_dic[data_sheet] = pd.read_excel(file_path,
sheet_name=data_sheet).set_index('Products')
three_cycles_data_dic, three_cycles_reuse_data_dic, three_cycles_graph_data_pd = evaluate_cohort_combined_model(data_dic, n_years, start_year, defined_distributions_pd= defined_distributions_pd, print_state=False, separate_reuse_graph = False, considered_use_cycles = 3)
two_cycles_data_dic, two_cycles_reuse_data_dic, two_cycles_graph_data_pd = evaluate_cohort_combined_model(data_dic, n_years, start_year, defined_distributions_pd= defined_distributions_pd, print_state=False, separate_reuse_graph = False, considered_use_cycles = 2)
one_cycles_data_dic, one_cycles_reuse_data_dic, one_cycles_graph_data_pd = evaluate_cohort_combined_model(data_dic, n_years, start_year, defined_distributions_pd= defined_distributions_pd, print_state=False, separate_reuse_graph = False, considered_use_cycles = 1)
# Treat data
use_cycle_comparison_full_system = pd.DataFrame({}, index=one_cycles_graph_data_pd.index)
use_cycle_comparison_full_system['One use cycle'] = one_cycles_graph_data_pd.iloc[:,:11].sum(axis=1)
use_cycle_comparison_full_system['Two use cycles'] = two_cycles_graph_data_pd.iloc[:,:11].sum(axis=1)
use_cycle_comparison_full_system['Three use cycles'] = three_cycles_graph_data_pd.iloc[:,:11].sum(axis=1)
use_cycle_comparison_full_system = 100 * use_cycle_comparison_full_system
use_cycle_comparison_pd = pd.DataFrame({})
use_cycle_comparison_pd['year'] = [start_year + i for i in range(n_years)]
use_cycle_comparison_pd = use_cycle_comparison_pd.set_index('year')
use_cycle_comparison_pd['Three use cycles'] = [three_cycles_reuse_data_dic[key]['total_use_stock'].sum() for key in three_cycles_reuse_data_dic.keys()]
use_cycle_comparison_pd['Two use cycles'] = [two_cycles_reuse_data_dic[key]['total_use_stock'].sum() for key in three_cycles_reuse_data_dic.keys()]
use_cycle_comparison_pd['One use cycle'] = [one_cycles_reuse_data_dic[key]['total_use_stock'].sum() for key in three_cycles_reuse_data_dic.keys()]
use_cycle_comparison_pd = use_cycle_comparison_pd * 100
# Define functions for verticle line
def return_time_of_corssing(target, df, column):
last_above = np.where(df[column] > target)
last_above = df.index[last_above[0][-1]]
first_below = last_above +1
slope = df[column].loc[first_below] - df[column].loc[last_above]
# location see notices ipad
location = last_above + (target - df[column].loc[last_above]) / slope
return location
fig = plt.figure()
ax = fig.add_subplot(1, 2, 1)
plt1, = plt.plot(use_cycle_comparison_full_system.index, use_cycle_comparison_full_system['One use cycle'], color = 'royalblue')
plt2, = plt.plot(use_cycle_comparison_full_system.index, use_cycle_comparison_full_system['Two use cycles'], color = 'magenta')
plt3, = plt.plot(use_cycle_comparison_full_system.index, use_cycle_comparison_full_system['Three use cycles'], color = 'goldenrod')
# Vertical lines
plt.axvline(x = return_time_of_corssing(50, use_cycle_comparison_full_system, 'One use cycle'), ymin = 0.0, ymax = 0.485, color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(50, use_cycle_comparison_full_system, 'Two use cycles'), ymin = 0.0, ymax = 0.485, color = 'magenta', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(50, use_cycle_comparison_full_system, 'Three use cycles'), ymin = 0.0, ymax = 0.485, color = 'goldenrod', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(25, use_cycle_comparison_full_system, 'One use cycle'), ymin = 0.0, ymax = 0.25, color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(25, use_cycle_comparison_full_system, 'Two use cycles'), ymin = 0.0, ymax = 0.25, color = 'magenta', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(25, use_cycle_comparison_full_system, 'Three use cycles'), ymin = 0.0, ymax = 0.25, color = 'goldenrod', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(75, use_cycle_comparison_full_system, 'One use cycle'), ymin = 0.0, ymax = 0.725, color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(75, use_cycle_comparison_full_system, 'Two use cycles'), ymin = 0.0, ymax = 0.725, color = 'magenta', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(75, use_cycle_comparison_full_system, 'Three use cycles'), ymin = 0.0, ymax = 0.725, color = 'goldenrod', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.yticks([0, 25, 50, 75, 100])
plt.grid(axis = 'y')
plt.text(2010, 115, 'A', size=20, weight='bold')
plt.ylabel('Total in-use stock in %')
plt.xlabel('Year AD')
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
ax = fig.add_subplot(1, 2, 2)
plt1, = plt.plot(use_cycle_comparison_pd.index, use_cycle_comparison_pd['One use cycle'], color = 'royalblue')
plt2, = plt.plot(use_cycle_comparison_pd.index, use_cycle_comparison_pd['Two use cycles'], color = 'magenta')
plt3, = plt.plot(use_cycle_comparison_pd.index, use_cycle_comparison_pd['Three use cycles'], color = 'goldenrod')
start_value = use_cycle_comparison_pd.iloc[0,0]
# Vertical lines
plt.axvline(x = return_time_of_corssing(start_value * 0.5, use_cycle_comparison_pd, 'One use cycle'), ymin = 0.0, ymax = 0.5, color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.5, use_cycle_comparison_pd, 'Two use cycles'), ymin = 0.0, ymax = 0.5, color = 'magenta', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.5, use_cycle_comparison_pd, 'Three use cycles'), ymin = 0.0, ymax = 0.5, color = 'goldenrod', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.25, use_cycle_comparison_pd, 'One use cycle'), ymin = 0.0, ymax = 0.275, color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.25, use_cycle_comparison_pd, 'Two use cycles'), ymin = 0.0, ymax = 0.275, color = 'magenta', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.25, use_cycle_comparison_pd, 'Three use cycles'), ymin = 0.0, ymax = 0.275, color = 'goldenrod', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.75, use_cycle_comparison_pd, 'One use cycle'), ymin = 0.0, ymax = 0.725, color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.75, use_cycle_comparison_pd, 'Two use cycles'), ymin = 0.0, ymax = 0.725, color = 'magenta', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.75, use_cycle_comparison_pd, 'Three use cycles'), ymin = 0.0, ymax = 0.725, color = 'goldenrod', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.yticks([i * 0.01 * start_value for i in [0, 25, 50, 75, 100]])
plt.grid(axis = 'y')
plt.xlim([2014, 2031])
plt.xticks([i for i in range(2015, 2031, 3)])
plt.ylabel('Total in-use stock of portable batteries in %')
plt.xlabel('Year AD')
plt.text(2012.5, 47.38, 'B', size=20, weight='bold')
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
secax.set_ticks([i for i in range(0, 16, 3)])
plt.legend([plt1,plt2,plt3], ['One use cycle', 'Two use cycles', 'Three use cycles'], loc = 'upper right')
plt.tight_layout()
plt.show()
plt.clf() # Clear figure
<Figure size 648x345.6 with 0 Axes>
# Treat data
relative_stock_comparison_pd = pd.DataFrame({}, index = use_cycle_comparison_full_system.index)
relative_stock_comparison_pd['Two use cycles'] = (use_cycle_comparison_full_system['Two use cycles'] / use_cycle_comparison_full_system['One use cycle']) - 1
relative_stock_comparison_pd['Three use cycles'] = (use_cycle_comparison_full_system['Three use cycles'] / use_cycle_comparison_full_system['One use cycle']) - 1
relative_stock_comparison_pd = relative_stock_comparison_pd * 100
relative_stock_comparison_portable_batteries_pd = pd.DataFrame({}, index = use_cycle_comparison_pd.index)
relative_stock_comparison_portable_batteries_pd['Two use cycles'] = (use_cycle_comparison_pd['Two use cycles'] / use_cycle_comparison_pd['One use cycle']) - 1
relative_stock_comparison_portable_batteries_pd['Three use cycles'] = (use_cycle_comparison_pd['Three use cycles'] / use_cycle_comparison_pd['One use cycle']) - 1
relative_stock_comparison_portable_batteries_pd = relative_stock_comparison_portable_batteries_pd * 100
plt.rcParams["figure.figsize"] = [9, 4.8]
fig = plt.figure()
ax = fig.add_subplot(1, 2, 1)
plt1, = plt.plot(relative_stock_comparison_pd.index, [0 for i in relative_stock_comparison_pd['Two use cycles']], color = 'royalblue')
plt2, = plt.plot(relative_stock_comparison_pd.index, relative_stock_comparison_pd['Two use cycles'], color = 'magenta')
plt3, = plt.plot(relative_stock_comparison_pd.index, relative_stock_comparison_pd['Three use cycles'], color = 'goldenrod')
# Vertical lines
plt.axvline(x = return_time_of_corssing(50, use_cycle_comparison_full_system, 'One use cycle'), color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(25, use_cycle_comparison_full_system, 'One use cycle'), color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(75, use_cycle_comparison_full_system, 'One use cycle'), color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.ylabel('Relative deviation of total in-use stock in %')
plt.xlabel('Year AD')
plt.text(2010, 9.5, 'A', size=20, weight='bold')
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
ax = fig.add_subplot(1, 2, 2)
plt1, = plt.plot(relative_stock_comparison_pd.index, [0 for i in relative_stock_comparison_pd['Two use cycles']], color = 'royalblue')
plt2, = plt.plot(relative_stock_comparison_portable_batteries_pd.index, relative_stock_comparison_portable_batteries_pd['Two use cycles'], color = 'magenta')
plt3, = plt.plot(relative_stock_comparison_portable_batteries_pd.index, relative_stock_comparison_portable_batteries_pd['Three use cycles'], color = 'goldenrod')
start_value = use_cycle_comparison_pd.iloc[0,0]
# Vertical lines
plt.axvline(x = return_time_of_corssing(start_value * 0.5, use_cycle_comparison_pd, 'One use cycle'), color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.25, use_cycle_comparison_pd, 'One use cycle'), color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.axvline(x = return_time_of_corssing(start_value * 0.75, use_cycle_comparison_pd, 'One use cycle'), color = 'royalblue', alpha = 0.8, linestyle = '--', linewidth = 0.8)
plt.xlim([2014, 2026])
plt.xticks([i for i in range(2015, 2026, 2)])
plt.text(2012.9, 273, 'B', size=20, weight='bold')
plt.ylabel('Relative deviation of portable batteries in-use stock in %')
plt.xlabel('Year AD')
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
plt.legend([plt1, plt2,plt3], ['One use cycle', 'Two use cycles', 'Three use cycles'], loc = 'upper right')
plt.tight_layout()
plt.show()
plt.clf() # Clear figure
<Figure size 648x345.6 with 0 Axes>
The file necessary to create this graph needs to be created from the compact results generated by the file "monte_carlo_evaluation.py" (please see model_application_manual.ipynb). Those files are very large. Therefore, they are not provided. The following code cell contains commeted code which loads those files and creates a file "monte_carlo_quantiles.pkl". This file is provided and will be loaded.
# import pickle
# folder_path = 'data_cobalt_case_study/monte_carlo_results'
# single_pandas_list = []
# for i in range(10):
# start_run = i * 1000
# end_run = start_run + 999
# file_path = '{}/compact_results_run_{}_till_{}.pkl'.format(folder_path, start_run, end_run)
# with open(file_path, "rb") as f:
# single_pandas_list.append(pickle.load(f))
# # combine data frames
# compact_results_pd = pd.concat(single_pandas_list, axis='columns')
# monte_carlo_reuse_results_pd = compact_results_pd.astype(float)
# monte_carlo_reuse_results_grouped = monte_carlo_reuse_results_pd.groupby(
# level=[1, 2], axis=1
# )
# monte_carlo_reuse_statistics = monte_carlo_reuse_results_grouped.quantile(
# q=[0.01, 0.05, 0.10, 0.25, 0.50, 0.75, 0.90, 0.95, 0.99]
# )
# with open('{}/monte_carlo_quantiles.pkl'.format(folder_path), 'wb') as f:
# pickle.dump(monte_carlo_reuse_statistics,f)
# Load data
import pickle
folder_path = 'data_cobalt_case_study/monte_carlo_results'
with open('{}/monte_carlo_quantiles.pkl'.format(folder_path), 'rb') as f:
monte_carlo_reuse_statistics = pickle.load(f)
monte_carlo_reuse_statistics = monte_carlo_reuse_statistics * 100
# Graph
stock_flow = 'U.A use stock'
item = 'sum'
plt.rcParams["figure.figsize"] = [9, 4.8]
fig = plt.figure()
ax = fig.add_subplot(1, 2, 1)
combination = (stock_flow, item)
plt.fill_between(
x=monte_carlo_reuse_statistics.index,
y1=monte_carlo_reuse_statistics[combination + (0.01,)],
y2=monte_carlo_reuse_statistics[combination + (0.99,)],
alpha=0.2,
facecolor="#B321A0",
)
plt.fill_between(
x=monte_carlo_reuse_statistics.index,
y1=monte_carlo_reuse_statistics[combination + (0.05,)],
y2=monte_carlo_reuse_statistics[combination + (0.95,)],
alpha=0.3,
facecolor="#B321A0",
)
plt.fill_between(
x=monte_carlo_reuse_statistics.index,
y1=monte_carlo_reuse_statistics[combination + (0.1,)],
y2=monte_carlo_reuse_statistics[combination + (0.9,)],
alpha=0.5,
facecolor="#B321A0",
)
plt.fill_between(
x=monte_carlo_reuse_statistics.index,
y1=monte_carlo_reuse_statistics[combination + (0.25,)],
y2=monte_carlo_reuse_statistics[combination + (0.75,)],
alpha=0.7,
facecolor="#B321A0",
)
plt.plot(monte_carlo_reuse_statistics[combination + (0.5,)], color="k")
plt.xlabel("Year AD")
plt.ylabel("Total in-use stock in %")
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
plt.text(2010, 115, 'A', size=20, weight='bold')
# Second plot
ax = fig.add_subplot(1, 2, 2)
median_line = monte_carlo_reuse_statistics[combination + (0.5,)]
plt.fill_between(
x=monte_carlo_reuse_statistics.index,
y1=monte_carlo_reuse_statistics[combination + (0.01,)] - median_line,
y2=monte_carlo_reuse_statistics[combination + (0.99,)] - median_line,
alpha=0.2,
facecolor="#B321A0",
)
plt.fill_between(
x=monte_carlo_reuse_statistics.index,
y1=monte_carlo_reuse_statistics[combination + (0.05,)] - median_line,
y2=monte_carlo_reuse_statistics[combination + (0.95,)] - median_line,
alpha=0.3,
facecolor="#B321A0",
)
plt.fill_between(
x=monte_carlo_reuse_statistics.index,
y1=monte_carlo_reuse_statistics[combination + (0.1,)] - median_line,
y2=monte_carlo_reuse_statistics[combination + (0.9,)] - median_line,
alpha=0.5,
facecolor="#B321A0",
)
plt.fill_between(
x=monte_carlo_reuse_statistics.index,
y1=monte_carlo_reuse_statistics[combination + (0.25,)] - median_line,
y2=monte_carlo_reuse_statistics[combination + (0.75,)] - median_line,
alpha=0.7,
facecolor="#B321A0",
)
plt.plot(monte_carlo_reuse_statistics[combination + (0.5,)] - median_line, color="k")
plt.xlabel("Year AD")
plt.ylabel("Absolut deviation from in-use stock median in %")
# add second axis
def transforme_fuc(x):
return x - 2015
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year')
plt.text(2010, 16.5, 'B', size=20, weight='bold')
plt.legend(["1%-99% quantile", "5%-95% quantile", "10%-90% quantile",
"25%-75% quantile", "median"], loc="lower right")
plt.tight_layout()
plt.show()
plt.clf()
<Figure size 648x345.6 with 0 Axes>
# Load data
spearman_results_normalized = pd.read_pickle('{}/spearman_results_normalized.pkl'.format(folder_path))
spareman_results_normalized_summed_pd = spearman_results_normalized.groupby(level=[0,1,2], axis = 1).sum()
# Treat data
represent_years = [i +2000 for i in [16,18,20,22,24,27,30,33,36,39]]
dic_legend = {'n_initial_products_Share': r'$\eta$: Initial inflow distribution',
'n_use_1_in_use_Weibull scale': r'$S_{Uk}$: Weibull scale',
'n_use_1_in_use_Weibull shape': r'$S_{Uk}$: Weibull shape',
'reuse_split_split': r'$\delta$: Split portable batteries to products',
'Others' : 'Others'
}
band_width = monte_carlo_reuse_statistics[combination + (0.99,)] - monte_carlo_reuse_statistics[combination + (0.01,)]
def graph_dataframe(df, target_column):
transformed_df = df[target_column].copy()
transformed_df.columns = ['_'.join(col) for col in transformed_df.columns]
return transformed_df
total_use_stock_uncertainty_summed = graph_dataframe(spareman_results_normalized_summed_pd, 'U.A use stock')
total_use_stock_uncertainty_summed['Year'] = [start_year + i for i in total_use_stock_uncertainty_summed.index]
total_use_stock_uncertainty_summed = total_use_stock_uncertainty_summed.set_index('Year')
total_use_stock_unsertainty_summed_selected_years = total_use_stock_uncertainty_summed.filter(items=represent_years, axis = 0)
total_use_stock_unsertainty_summed_selected_years = total_use_stock_unsertainty_summed_selected_years[['n_initial_products_Share', 'n_use_1_in_use_Weibull scale', 'n_use_1_in_use_Weibull shape', 'reuse_split_split']]
total_use_stock_unsertainty_summed_selected_years['Others'] = 100- total_use_stock_unsertainty_summed_selected_years.sum('columns')
width = 1
fig, ax = plt.subplots()
# bottom list for stacks
bottom = [0 for i in range(len(represent_years))]
for input in ['n_initial_products_Share', 'n_use_1_in_use_Weibull scale', 'n_use_1_in_use_Weibull shape', 'reuse_split_split', 'Others']:
# add bar for sections which are supposed to be labeled
ax.bar(represent_years, total_use_stock_unsertainty_summed_selected_years[input].to_list(), width, bottom=bottom, label = dic_legend[input])
bottom = [old + new for old, new in zip(bottom, total_use_stock_unsertainty_summed_selected_years[input].to_list())]
handles, labels = ax.get_legend_handles_labels()
plt1, = plt.plot(extended_graph_data_pd.index, extended_graph_data_pd.iloc[:, 0:10].sum(axis='columns'),
color = 'red', linestyle = '--', label = 'Total in-use stock')
plt2, = plt.plot(extended_graph_data_pd.index, band_width,
color = "#B321A0")
ax.legend([i for i in reversed(handles)] + [plt1, plt2], [i for i in reversed(labels)] + ['Total in-use stock', "1%-99% quantile \nuncertainty bandwidth"],
loc = 'lower right')
plt.ylabel('Normalized square of Spearman\'s rank correlation in %')
plt.xlabel('Year AD ')
plt.xticks(represent_years)
plt.xlim([2015, 2040])
# add second axis
def transforme_fuc(x):
return x - 2015
# secax = ax.secondary_xaxis(-0.15, functions = (transforme_fuc, transforme_fuc))
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year ')
secax.set_ticks([i - 2015 for i in represent_years])
plt.show()
plt.clf()
<Figure size 648x345.6 with 0 Axes>
# Load data
spearman_results_abs= pd.read_pickle('{}/spearman_results_abs.pkl'.format(folder_path))
# Create data
initial_inflow_normalized = spearman_results_abs['U.A use stock', 'n_initial_products', 'Share']
# getting the squared normalized correlation.
initial_inflow_normalized = initial_inflow_normalized **2
sum_vec = initial_inflow_normalized.sum(axis=1)
# devied
initial_inflow_normalized=initial_inflow_normalized.div(sum_vec, axis='rows')
initial_inflow_normalized = initial_inflow_normalized * 100
# setting index
initial_inflow_normalized['Year'] = [start_year + i for i in initial_inflow_normalized.index]
initial_inflow_normalized = initial_inflow_normalized.set_index('Year')
initial_inflow_normalize_selected_years = initial_inflow_normalized.filter(items=represent_years, axis = 0)
width = 1
# Create graph
plt.rcParams["figure.figsize"] = [7, 5.5]
fig, ax = plt.subplots()
# bottom list for stacks
bottom = [0 for i in range(len(represent_years))]
for input in initial_inflow_normalize_selected_years.columns:
# add bar for sections which are supposed to be labeled
if input == 'superalloys':
ax.bar(represent_years, initial_inflow_normalize_selected_years[input].to_list(), width, bottom=bottom, label = input.capitalize(), color = 'tomato')
bottom = [old + new for old, new in zip(bottom, initial_inflow_normalize_selected_years[input].to_list())]
else:
ax.bar(represent_years, initial_inflow_normalize_selected_years[input].to_list(), width, bottom=bottom, label = input.capitalize())
bottom = [old + new for old, new in zip(bottom, initial_inflow_normalize_selected_years[input].to_list())]
handles, labels = ax.get_legend_handles_labels()
plt1, = plt.plot(extended_graph_data_pd.index, extended_graph_data_pd.iloc[:, 0:10].sum(axis='columns'),
color = 'red', linestyle = '--', label = 'Total in-use stock')
plt2, = plt.plot(extended_graph_data_pd.index, band_width,
color = "#B321A0")
ax.legend([i for i in reversed(handles)] + [plt1, plt2], [i for i in reversed(labels)] + ['Total in-use stock', "1%-99% quantile \nuncertainty bandwidth"],
loc ='upper left', bbox_to_anchor=(1,1))
fig.subplots_adjust(bottom=0.25)
plt.ylabel('Normalized square of Spearman\'s rank correlation in %')
plt.xlabel('Year AD ')
plt.xticks(represent_years)
plt.xlim([2015, 2040])
# add second axis
def transforme_fuc(x):
return x - 2015
# secax = ax.secondary_xaxis(-0.15, functions = (transforme_fuc, transforme_fuc))
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year ')
secax.set_ticks([i - 2015 for i in represent_years])
plt.show()
plt.clf()
C:\Users\rapha\AppData\Local\Temp/ipykernel_24400/3898441337.py:4: PerformanceWarning: indexing past lexsort depth may impact performance. initial_inflow_normalized = spearman_results_abs['U.A use stock', 'n_initial_products', 'Share']
<Figure size 504x396 with 0 Axes>
# Create data
considered_columns = list(spearman_results_abs['U.A use stock'].columns.levels[0])
considered_columns.remove('n_initial_products')
considered_columns.remove('n_use_1_in_use')
# Setting index
spearman_minor_contributer = spearman_results_abs['U.A use stock'][considered_columns]
spearman_minor_contributer['Year'] = [start_year + i for i in spearman_minor_contributer.index]
spearman_minor_contributer = spearman_minor_contributer.set_index('Year')
# Normalizing
spearman_minor_contributer = spearman_minor_contributer **2
sum_vec = spearman_minor_contributer.sum(axis=1)
# devied
spearman_minor_contributer=spearman_minor_contributer.div(sum_vec, axis='rows')
spearman_minor_contributer = spearman_minor_contributer * 100
spearman_minor_contributer = spearman_minor_contributer.groupby(level=[0,1], axis = 1).sum()
# merge columns
spearman_minor_contributer.columns = ['_'.join(col) for col in spearman_minor_contributer.columns]
# create graph
plt.rcParams["figure.figsize"] = [7, 5.5]
total_use_stock_unsertainty_summed_minor_contributers_selected_years = spearman_minor_contributer.filter(items=represent_years, axis = 0)
dic_legend = {'n_prod_1_D_Co metal or compound': r'$D$: Distribution of secondary material; Co metal or compound',
'n_prod_2_parameters_Domestic product inflow': r'$\psi_P$: Domstic product inflow',
'n_prod_2_parameters_Export of products': r'$\psi_P$: Fraction of exported final products',
'reuse_service_time_1_to_use': r'$\alpha_{i1}$: Transfer coefficient in-use stock to next in-use stock',
'reuse_service_time_1_weibull_scale': r'$S_{Ui1}$: Weibull scale of portable batteries in first use cycle',
'reuse_split_split': r'$\delta$: Split portable batteries to products'
}
width = 1
fig, ax = plt.subplots()
# bottom list for stacks
bottom = [0 for i in range(len(represent_years))]
list_not_considered = []
for input in total_use_stock_unsertainty_summed_minor_contributers_selected_years.columns:
if input in ['n_prod_1_D_Co metal or compound',
'n_prod_2_parameters_Domestic product inflow',
'n_prod_2_parameters_Export of products', 'reuse_service_time_1_to_use',
'reuse_service_time_1_weibull_scale', 'reuse_split_split']:
# add bar for sections which are supposed to be labeled
ax.bar(represent_years, total_use_stock_unsertainty_summed_minor_contributers_selected_years[input].to_list(), width, bottom=bottom, label = dic_legend[input])
bottom = [old + new for old, new in zip(bottom, total_use_stock_unsertainty_summed_minor_contributers_selected_years[input].to_list())]
else:
list_not_considered.append(total_use_stock_unsertainty_summed_minor_contributers_selected_years[input].to_list())
for vector in list_not_considered:
ax.bar(represent_years, vector, width, bottom=bottom, alpha = 0.3)
bottom = [old + new for old, new in zip(bottom, vector)]
handles, labels = ax.get_legend_handles_labels()
plt1, = plt.plot(extended_graph_data_pd.index, extended_graph_data_pd.iloc[:, 0:10].sum(axis='columns'),
color = 'red', linestyle = '--', label = 'Total in-use stock')
plt2, = plt.plot(extended_graph_data_pd.index, band_width,
color = "#B321A0")
ax.legend([i for i in reversed(handles)] + [plt1, plt2], [i for i in reversed(labels)] + ['Total in-use stock', "1%-99% quantile uncertainty bandwidth"],
loc ='upper left', bbox_to_anchor=(1,1))
fig.subplots_adjust(bottom=0.25)
plt.ylabel('Normalized square of Spearman\'s rank correlation in %')
plt.xlabel('Year AD ')
plt.xticks(represent_years)
plt.xlim([2015, 2040])
# add second axis
def transforme_fuc(x):
return x - 2015
# secax = ax.secondary_xaxis(-0.15, functions = (transforme_fuc, transforme_fuc))
secax = ax.secondary_xaxis('top', functions = (transforme_fuc, transforme_fuc))
secax.set_xlabel('Year ')
secax.set_ticks([i - 2015 for i in represent_years])
plt.show()
plt.clf()
<Figure size 504x396 with 0 Axes>
# Load data
with open('{}/inputs.pkl'.format(folder_path), 'rb') as f:
input_pd = pickle.load(f)
plt.rcParams["figure.figsize"] = [9, 4.8]
plt.subplot(1, 2, 1)
plt.hist(input_pd['reuse_service_time_1']['to_use']['e-bikes'], bins = 50)
plt.xlabel('Transfer coefficient to use')
plt.ylabel('Occurance')
plt.text(-0.11, 428, 'A', size=20, weight='bold')
###################### Plot 2
plt.subplot(1, 2, 2)
loc, scale, c = triang_dist_inputs_case_4(0.07)
x_values = np.linspace(-0.01, 1.1, 801)
y_values = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
plt2, = plt.plot(x_values, y_values, color = u'#9467bd')
plt.xlabel('Generated input value')
plt.ylabel('Probability by density in %')
plt.tight_layout()
plt.text(-0.18, 2.15, 'B', size=20, weight='bold')
plt.show()
plt.clf() # Clear figure
<Figure size 648x345.6 with 0 Axes>
selected_input = ('n_use_1_in_use', 'Weibull shape', 'hard metals')
plt.rcParams["figure.figsize"] = [6.4, 4.8]
plt.hist(input_pd[selected_input[0]][selected_input[1]][selected_input[2]], bins = 50)
plt.xlabel('Weibull shape')
plt.ylabel('Occurance')
Text(0, 0.5, 'Occurance')
plt.rcParams["figure.figsize"] = [9, 4.8]
plt.subplot(1, 2, 1)
plt.hist(input_pd['n_prod_2_parameters']['Processing yield']['dissipative uses'], bins = 50)
plt.xlabel('Transfer coefficient to use')
plt.ylabel('Occurance')
plt.text(0.09, 428, 'A', size=20, weight='bold')
###################### Plot 2
plt.subplot(1, 2, 2)
loc, scale, c = triang_dist_inputs_case_3(0.97)
x_values = np.linspace(-0.01, 1.1, 801)
y_values = scipy.stats.triang.pdf(x_values, c= c, loc = loc, scale = scale)
plt2, = plt.plot(x_values, y_values, color = u'#9467bd')
plt.text(-0.18, 2.7, 'B', size=20, weight='bold')
plt.xlabel('Generated input value')
plt.ylabel('Probability by density in %')
plt.tight_layout()
plt.show()
plt.clf() # Clear figure
<Figure size 648x345.6 with 0 Axes>