def test_add_impact_scores_to_act_existing_db(data_for_testing): """Test adding agg dataset to existing database""" Database('agg').register() assert 'agg' in databases assert len(Database('agg')) == 0 add_impact_scores_to_act(act_code='A', agg_db='agg', up_db='techno_UP', selected_methods=[ data_for_testing['m1_name'], data_for_testing['m2_name'] ], biosphere='biosphere', overwrite=False, create_ef_on_the_fly=True, create_agg_database_on_fly=False) assert 'agg' in databases assert len(Database('agg')) == 1 assert ('agg', 'A') in Database('agg') act = get_activity(('agg', 'A')) act_bio_exc = {exc.input.key: exc['amount'] for exc in act.biosphere()} assert len(act_bio_exc) == 2 lca = LCA({('techno_UP', 'A'): 1}, method=data_for_testing['m1_name']) lca.lci() lca.lcia() assert lca.score == act_bio_exc[( 'biosphere', Method(data_for_testing['m1_name']).get_abbreviation())] lca.switch_method(method=data_for_testing['m2_name']) lca.lcia() assert lca.score == act_bio_exc[( 'biosphere', Method(data_for_testing['m2_name']).get_abbreviation())]
class LCIA: def __init__(self, biosphere="biosphere3"): self.db = Database(biosphere) self.method = Method(self.name) @property def metadata(self): obj = { "unit": self.unit, "description": self.description, "url": self.url, "geocollections": [], } if self.geocollection: obj["geocollections"] = [self.geocollection] return obj @regionalized_setup def import_regional_method(self): self.method.register(**self.metadata) self.setup_geocollections() self.method.write(list(self.regional_cfs())) def __repr__(self): return str(self.name)
def test_aggregated_LCIA_multiple_methods_already_augmented(data_for_testing): projects.set_current(data_for_testing['project']) assert "techno_UP" in databases assert "biosphere" in databases assert "techno_agg_LCIA" not in databases assert data_for_testing['m1_name'] in methods assert data_for_testing['m2_name'] in methods assert len(methods) == 2 add_all_unit_score_exchanges_and_cfs(biosphere='biosphere') agg_db = DatabaseAggregator( up_db_name="techno_UP", agg_db_name="techno_agg_LCIA", database_type='LCIA', method_list=[data_for_testing['m1_name'], data_for_testing['m2_name']], biosphere='biosphere', overwrite=False).generate() assert "techno_agg_LCIA" in databases assert len(Database("techno_agg_LCIA")) == len(Database("techno_UP")) lca_unit_process = LCA({("techno_UP", "A"): 1}, method=data_for_testing['m1_name']) lca_unit_process.lci() lca_unit_process.lcia() lca_LCIA = LCA({("techno_agg_LCIA", "A"): 1}, method=data_for_testing['m1_name']) lca_LCIA.lci() lca_LCIA.lcia() assert lca_unit_process.score == lca_LCIA.score score_in_B = lca_LCIA.biosphere_matrix[lca_LCIA.biosphere_dict[( 'biosphere', Method(data_for_testing['m1_name']).get_abbreviation())], lca_LCIA.activity_dict[( "techno_agg_LCIA", "A")]] assert score_in_B == lca_LCIA.score lca_unit_process = LCA({("techno_UP", "A"): 1}, method=data_for_testing['m2_name']) lca_unit_process.lci() lca_unit_process.lcia() lca_LCIA = LCA({("techno_agg_LCIA", "A"): 1}, method=data_for_testing['m2_name']) lca_LCIA.lci() lca_LCIA.lcia() assert lca_unit_process.score == lca_LCIA.score score_in_B = lca_LCIA.biosphere_matrix[lca_LCIA.biosphere_dict[( 'biosphere', Method(data_for_testing['m2_name']).get_abbreviation())], lca_LCIA.activity_dict[( "techno_agg_LCIA", "A")]] assert score_in_B == lca_LCIA.score
def import_example_data(): db = Database("temp-example-db") if db.name not in databases: db.register() db.write(db_data) db.process() method = Method(("static GWP", )) if method.name not in methods: method.register() method.write(static_cfs) method.process() dynamic_method = DynamicIAMethod("static GWP") if dynamic_method.name not in dynamic_methods: dynamic_method.register() dynamic_method.write({x[0]: x[1] for x in static_cfs}) dynamic_method.to_worst_case_method(("static GWP", "worst case")) dynamic_method = DynamicIAMethod("dynamic GWP") if dynamic_method.name not in dynamic_methods: dynamic_method.register() dynamic_method.write(dynamic_cfs) dynamic_method.to_worst_case_method(("dynamic GWP", "worst case")) dynamic_method = DynamicIAMethod("discounted dynamic GWP") if dynamic_method.name not in dynamic_methods: dynamic_method.register() dynamic_method.write(dynamic_discounted_cfs) dynamic_method.to_worst_case_method( ("discounted dynamic GWP", "worst case"))
class LCIA: def __init__(self, biosphere='biosphere3'): self.db = Database(biosphere) self.method = Method(self.name) @property def metadata(self): obj = { 'unit': self.unit, 'description': self.description, 'url': self.url, 'geocollections': [] } if self.geocollection: obj['geocollections'] = [self.geocollection] return obj def import_global_method(self): self.method.register(**self.metadata) self.method.write(list(self.global_cfs())) @regionalized @regionalized_setup def import_regional_method(self): self.method.register(**self.metadata) self.setup_geocollections() self.method.write(list(self.regional_cfs())) def __repr__(self): return str(self.name)
def test_add_unit_score_exchange_and_cf(data_for_testing): """ Augment methods and biosphere database for unit scores""" # Make sure project received with expected initial data (possibly delete # since this does not test the function, but rather the testing itself) projects.set_current(data_for_testing['project']) assert "biosphere" in databases method_name = data_for_testing['m1_name'] assert method_name in methods assert len(Database('biosphere')) == 2 loaded_biosphere_before = Database('biosphere').load() method = Method(method_name) loaded_method_before = method.load() assert len(loaded_method_before) == 2 ef_code = method.get_abbreviation() assert ('biosphere', ef_code) not in loaded_biosphere_before # Augment method and biosphere database add_unit_score_exchange_and_cf(method=method_name, biosphere='biosphere') assert len(Database('biosphere')) == 3 loaded_biosphere_after = Database('biosphere').load() assert ('biosphere', ef_code) in loaded_biosphere_after new_ef = get_activity(('biosphere', ef_code)) assert new_ef['name'] == 'Unit impact for {}'.format(method_name) method = Method(method_name) loaded_method_after = method.load() assert len(loaded_method_after) == 3 assert (('biosphere', ef_code), 1) in loaded_method_after
def test_add_unit_score_exchange_and_cf_act_exists(data_for_testing): projects.set_current(data_for_testing['project']) method_name = data_for_testing['m1_name'] assert len(Database('biosphere')) == 2 loaded_biosphere_before = Database('biosphere').load() method1_name = data_for_testing['m1_name'] method1 = Method(method1_name) loaded_method1_before = method1.load() assert len(loaded_method1_before) == 2 ef1_code = method1.get_abbreviation() assert ('biosphere', ef1_code) not in loaded_biosphere_before # Manually add ef to biosphere biosphere_data = Database('biosphere').load() biosphere_data[("biosphere", Method(method_name).get_abbreviation())] = { 'name': 'Unit impact for {}'.format(method_name), 'type': 'unit exchange', 'unit': Method(method_name).metadata['unit'] } Database('biosphere').write(biosphere_data) assert len(Database('biosphere')) == 3 # run function, should not change the length of biosphere, but should add # cf to method add_unit_score_exchange_and_cf(method_name, biosphere='biosphere') loaded_method1_after = method1.load() assert len(loaded_method1_after) == 3 assert len(Database('biosphere')) == 3
def whole_method_LCIA_calculator(method_list, results_folder, ref_bio_dict): LCI_arrays_dir = os.path.join(results_folder, 'Inventory') assert os.path.isdir(LCI_arrays_dir), "No LCI results to process" LCI_arrays = os.listdir(LCI_arrays_dir) for method in method_list: method_abbreviation = Method(method).get_abbreviation() LCIA_folder = os.path.join(results_folder, 'LCIA', method_abbreviation) if not os.path.isdir(LCIA_folder): os.makedirs(LCIA_folder) loaded_method = Method(method).load() method_ordered_exchanges = [exc[0] for exc in loaded_method] # Collectors for the LCI array indices and characterization factors that are relevant # for the impact assessment (i.e. those that have characterization factors for the given method) lca_specific_biosphere_indices = [] cfs = [] for exc in method_ordered_exchanges: # For every exchange that has a characterization factor try: lca_specific_biosphere_indices.append(ref_bio_dict[exc]) # Check to see if it is in the bio_dict # If it is, it is in the inventory # And its index is bio_dict[exc] cfs.append(dict(loaded_method)[exc]) # If it is in bio_dict, we need its # characterization factor except: pass for act in LCI_arrays: if act in os.listdir(LCIA_folder): pass else: calculate_score_array_from_LCI_array( results_folder, lca_specific_biosphere_indices, cfs, act, LCIA_folder) return None
def concat_lcia_samples_arrays_from_method_tuple( result_dir, method, sb_id_list=None, totals_or_per_exchanges="totals", project_name=None, sim_name=None, dest=None, fail_if_samples_batches_different=False, ignore_missing=True): """ Concatenate and save LCIA sample arrays in result dir Parameters ------------ result_type : str Path to the directory where data used or generated by bw2preagg is saved. method : tuple LCIA method identification in brightway2 (tuple) sb_id_list : list List of samples_batch ids. If None, all samples_batch are processed. totals_or_per_exchanges : str, default="totals" Deal with totals or results per elementary flows project_name : str Name of the brightway2 project where the database is imported sim_name : str, default=None Name to give the directory in which results will be saved. If None, a default name is generated from sb_id_list dest : str Path to location where concatenated array directory will be saved fail_if_samples_batches_different : bool, default=False If False, will raise ValueError if arrays available in samples_batch folders are not the same If True, will concatenate only those arrays that are available in all samples_batch folders ignore_missing : bool, default=True If False, will concatenate arrays in LCI folder only if all expected LCI arrays are present """ if project_name: projects.set_current(_check_project(project_name)) method = _check_method(method) abbr = Method(method).get_abbreviation() concat_samples_arrays_in_result_type_dir( result_dir=result_dir, sb_id_list=sb_id_list, result_type_dirname=abbr, totals_or_per_exchanges=totals_or_per_exchanges, sim_name=sim_name, dest=dest, fail_if_samples_batches_different=fail_if_samples_batches_different, ignore_missing=ignore_missing)
def negtive_cf(method_name=None): """find the negative values of Chracterization Fators of ia method, which implied that they are good for the environment **kwargs **method_name** : [str] name of the method tool, for exmaple-- ('ReCiPe Midpoint (I) V1.13') **return A dictionary of negtive CFs of selected method. For exmaple-- ('ReCiPe Midpoint (I) V1.13','photochemical oxidant formation','POFP'):\ [('Benzaldehyde' (kilogram, None, ('air',)),-0.155), ('Benzaldehyde' (kilogram, None, ('air', 'urban air close to ground')), -0.155)] """ negtive_cf_dict = {} if method_name is not None: method_lst = list(filter(lambda x: x[0] == method_name, methods)) else: method_lst = methods for method in method_lst: CFs = {} for key, cfs in Method(method).load(): if cfs < 0: CFs[((Database('biosphere3').get(key[1])))] = cfs if CFs: negtive_cf_dict[method] = CFs # workbook = openpyxl.Workbook() # sheet = workbook.active # row = 1 # for key,values in negtive_cf_dict.items(): # sheet.cell(row=row, column=1, value=str(key)) # column = 2 # for element in values: # sheet.cell(row=row, column=column, value=str(element)) # column += 1 # row += 1 # workbook.save(filename="ncf2.xlsx") return negtive_cf_dict
def data_for_testing(): # Make sure we are starting off with an empty project assert not len(Database('techno_UP')) assert not len(Database('techno_LCI')) assert not len(Database('techno_LCIA')) assert not len(Database('biosphere')) assert not len(methods) biosphere = Database("biosphere") biosphere.register() biosphere.write({ ("biosphere", "1"): { 'categories': ['things'], 'exchanges': [], 'name': 'an emission', 'type': 'emission', 'unit': 'kg' }, ("biosphere", "2"): { 'categories': ['other things'], 'exchanges': [], 'name': 'another emission', 'type': 'emission', 'unit': 'kg' }, }) assert len(Database('biosphere')) == 2 techno_UP = Database("techno_UP") techno_UP.register() techno_UP.write({ ("techno_UP", "A"): { 'exchanges': [ { 'amount': 1.0, 'input': ('techno_UP', 'A'), 'type': 'production' }, { 'amount': 10, 'input': ('techno_UP', 'B'), 'type': 'technosphere' }, { 'amount': 100, 'input': ('biosphere', '1'), 'type': 'biosphere' }, { 'amount': 1000, 'input': ('biosphere', '2'), 'type': 'biosphere' }, ], 'name': 'activity A', 'unit': 'kg', 'location': 'GLO', 'reference product': 'A', 'production amount': 1 }, ("techno_UP", "B"): { 'exchanges': [ { 'amount': 1.0, 'input': ('techno_UP', 'B'), 'type': 'production' }, { 'amount': 25, 'input': ('biosphere', '1'), 'type': 'biosphere' }, { 'amount': 50, 'input': ('biosphere', '2'), 'type': 'biosphere' }, ], 'name': 'activity B', 'unit': 'kg', 'location': 'GLO', 'reference product': 'B', 'production amount': 1 }, }) m1_name = ('some', 'LCIA', 'method') m1 = Method(m1_name) m1.register() m1.metadata['unit'] = "Some impact unit" m1.write([ (("biosphere", "1"), 1), (("biosphere", "2"), 10), ]) m2_name = ('some other', 'LCIA', 'method') m2 = Method(m2_name) m2.register() m2.metadata['unit'] = "Some other impact unit" m2.write([ (("biosphere", "1"), 100), (("biosphere", "2"), 42), ]) print(projects.dir) yield {'project': projects.current, 'm1_name': m1_name, 'm2_name': m2_name} rmtree(projects.dir, ignore_errors=True)
def __init__(self, biosphere='biosphere3'): self.db = Database(biosphere) self.method = Method(self.name)