def _multiLCA(activities, methods): """Simple wrapper around brightway API""" bw2.calculation_setups['process'] = {'inv': activities, 'ia': methods} lca = bw2.MultiLCA('process') cols = [ act for act_amount in activities for act, amount in act_amount.items() ] return pd.DataFrame(lca.results.T, index=[method for method in methods], columns=cols)
def get_CFs(self, indicators=(), activities=(), show=False, path=''): ''' Get impact characterization factors. Parameters ---------- indicators : iterable Keys of the indicators in the `indicators` property. Will be defaulted to all loaded indicators if not provided. activities : iterable Keys of the activities in the `activities` property. Will be defaulted to all loaded indicators if not provided. show : bool Whether to print all characterization factors in the console. path : str If provided, the :class:`pandas.DataFrame` will be saved to the given file path. Returns ------- df: :class:`pandas.DataFrame` Characterization factors. Tip --- [1] Use `show_activity` to see the functional unit of the activity. The quantity will be 1. [2] If you run into an "FileNotFoundError", most likely there are some indicators that do not acutally have corresponding impact assessment methods, try to load indicators one at a time to look for the culprit. ''' if not self.indicators: raise ValueError('No loaded indicators.') elif not self.activities: raise ValueError('No loaded activities.') if not set(indicators).issubset(self.indicators): raise ValueError('Provided indicator(s) not all loaded.') inds = indicators if indicators else self.indicators ind_units = [bw2.methods.get(i)['unit'] for i in inds] + ['-', '-'] acts = [self.activities[k] for k in activities] if activities \ else [v for v in self.activities.values()] bw2.calculation_setups['multiLCA'] = { 'inv': [{ a: 1 } for a in acts], 'ia': inds } # This is to prevent bw2 from printing in the console stdout = sys.stdout sys.stdout = open(os.devnull, 'w') mlca = bw2.MultiLCA('multiLCA') sys.stdout = stdout # pd_indices = [a['name'] for a in acts] pd_cols = pd.MultiIndex.from_tuples(inds, names=('method', 'category', 'indicator')) cf_df = pd.DataFrame(data=mlca.results, columns=pd_cols) unit_df = pd.DataFrame( data={k: v for k, v in zip(cf_df.columns, ind_units)}, index=[ -1, ], dtype='object') # cf_df = pd.DataFrame(data=mlca.results, index=pd_indices, columns=pd_cols) cf_df[('-', '-', 'activity name')] = [a['name'] for a in acts] cf_df[('-', '-', 'functional unit')] = [a['unit'] for a in acts] df = pd.concat((unit_df, cf_df)) df.sort_index(axis=1, inplace=True) df.reset_index(drop=True, inplace=True) if show: print(df) export_df(df, path, show) self._CFs = df return df
'alumina_production_recipe', 'alumina_consumption_recipe', 'aluminium_ingot_production_recipe' ] #Output lca_df = pd.DataFrame() for year in year_list: utils_update.dbUpdate_ElecAluLiq(bw_db_name=bw_db_name, year=year) utils_update.dbUpdate_EnerAlumina(bw_db_name=bw_db_name, year=year) utils_update.dbUpdate_cons_mix(bw_db_name=bw_db_name, year=year, mineral='bauxite') utils_update.dbUpdate_cons_mix(bw_db_name=bw_db_name, year=year, mineral='alumina') for calculation_setup_name in multilca_list: MultiLCA = bw.MultiLCA(calculation_setup_name) temp_dt = utils_bw.get_multilca_to_dataframe(MultiLCA) temp_dt['Year'] = year lca_df = lca_df.append(temp_dt, ignore_index=True) for country in country_list: alu_cons_act = bw_db.get('market for consumption of aluminium') alu_cons_act['location'] = country alu_cons_act.save() utils_update.dbUpdate_cons_mix(bw_db_name=bw_db_name, year=year, mineral='aluminium') bw.calculation_setups['aluminium_consumption_recipe']['inv'] = [{ alu_cons_act: 1 }] MultiLCA = bw.MultiLCA('aluminium_consumption_recipe')
mc_sto.switch_method(method) CF_matr[method] = mc_sto.characterization_matrix.copy() mc_sto_results[method] = [] from time import time start = time() #Calculate results for each method and n_iter iterations for _ in range(n_iter): for method in CF_matr: mc_sto_results[method].append( (CF_matr[method] * mc_sto.inventory).sum()) next(mc_sto) print("Time elapsed: ", time() - start) ##### OTHER ##### #Montecarlo with static presample (it uses uncertainty in activities and in ecoinvent database) mc_sta = bw.MonteCarloLCA({electricity_prod: 1}, IPCC, presamples=[static_filepath]) n_iter = 1000 # Number of iterations mc_sta_results = np.array([next(mc_sta) for _ in range(n_iter)]) sb.distplot(mc_sta_results) ############ TESTING ######### #MultiLCA and my_calculatio_setup for multi-method LCA functional_unit = [{electricity_prod: 1}] my_calculation_setup = {"inv": functional_unit, "ia": ILCD} bw.calculation_setups["ILCD"] = my_calculation_setup mlca = bw.MultiLCA("ILCD") mlca.results
elec_act_exc_list = [exc for exc in act.technosphere() if 'electricity production' in exc.input['name']] for exc in elec_act_exc_list: exc.input.delete() exc.delete() [exc for exc in act.technosphere()] ''' #Check the LCA score are equivalent for all locations act_name = "market for electricity, high voltage, aluminium industry" act_list = [act for act in bw_db if act_name in act['name']] fu_list = [{act: 1} for act in act_list] method = ('IPCC 2013', 'climate change', 'GWP 100a') bw.calculation_setups['aluminium_elec_high_ipcc'] = { 'inv': fu_list, 'ia': [method] } MultiLCA = bw.MultiLCA('aluminium_elec_high_ipcc') pd.DataFrame(index=[list(fu.keys())[0]['location'] for fu in fu_list], columns=[method], data=MultiLCA.results) #2) Create 'electricity medium voltage' for GLO without any exchange. act_name = "market for electricity, medium voltage, aluminium industry" act_list = [act for act in bw_db if act_name in act['name']] #Check all locations exist diff_set = set(iai_reg_l).difference(set([act['location'] for act in act_list])) #If GLO does not exist. Create the activity WITHOUT EXCHANGES if 'GLO' in diff_set: new_act = bw_db.new_activity(act_name) new_act['name'] = act_name