Skip to content

Commit

Permalink
Add support for BW25
Browse files Browse the repository at this point in the history
  • Loading branch information
romainsacchi committed Oct 15, 2023
1 parent f7d5de0 commit a94aa52
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 4 deletions.
90 changes: 90 additions & 0 deletions unfold/brightway25_export.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
from bw2data import databases, Database
from bw2io.importers.base_lci import LCIImporter
from copy import copy
import itertools

def write_brightway_database(data, name):
# Restore parameters to Brightway2 format
# which allows for uncertainty and comments
BW25UnfoldExporter(name, data).write_database()

class BW25UnfoldExporter(LCIImporter):
"""
Inherits from `LCIImporter` to
allow existing databases to be
written to disk.
"""

def __init__(self, db_name, data):
super().__init__(db_name)
self.db_name = db_name
self.data = data
for act in self.data:
act["database"] = self.db_name

# we override `write_database`
# to allow existing databases
# to be overwritten
def write_database(self):

def no_exchange_generator(data):
for ds in data:
cp = copy(ds)
cp["exchanges"] = []
yield cp

if self.db_name in databases:
print(
f"Database {self.db_name} " f"already exists: it will be overwritten."
)
super().write_database(
list(no_exchange_generator(self.data)), backend="iotable"
)

dependents = {exc["input"][0] for ds in self.data for exc in ds["exchanges"]}
lookup = {
obj.key: obj.id
for obj in itertools.chain(*[Database(label) for label in dependents])
}

def technosphere_generator(data, lookup):
for ds in data:
target = lookup[(ds["database"], ds["code"])]
for exc in ds["exchanges"]:
if exc["type"] in (
"substitution",
"production",
"generic production",
):
yield {
"row": lookup[exc["input"]],
"col": target,
"amount": exc["amount"],
"flip": False,
}
elif exc["type"] == "technosphere":
yield {
"row": lookup[exc["input"]],
"col": target,
"amount": exc["amount"],
"flip": True,
}

def biosphere_generator(data, lookup):
for ds in data:
target = lookup[(ds["database"], ds["code"])]
for exc in ds["exchanges"]:
if exc["type"] == "biosphere":
yield {
"row": lookup[exc["input"]],
"col": target,
"amount": exc["amount"],
"flip": False,
}

Database(self.db_name).write_exchanges(
technosphere_generator(self.data, lookup),
biosphere_generator(self.data, lookup),
list(dependents),
)
8 changes: 7 additions & 1 deletion unfold/export.py → unfold/brightway2_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@
from bw2io.importers.base_lci import LCIImporter


class UnfoldExporter(LCIImporter):
def write_brightway_database(data, name):
# Restore parameters to Brightway2 format
# which allows for uncertainty and comments
BW2UnfoldExporter(name, data).write_database()


class BW2UnfoldExporter(LCIImporter):
"""
Inherits from `LCIImporter` to
allow existing databases to be
Expand Down
13 changes: 10 additions & 3 deletions unfold/unfold.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,14 @@
remove_categories_for_technosphere_flows,
remove_missing_fields,
)
from .export import UnfoldExporter

try:
import bw_processing
from .brightway25_export import write_brightway_database

except ImportError:
from .brightway2_export import write_brightway_database

from .utils import HiddenPrints

DIR_CACHED_DB = Path(__file__).parent / "cached_databases"
Expand Down Expand Up @@ -1219,7 +1226,7 @@ def write(self, superstructure: bool = False, export_dir: str = None):
check_duplicate_codes(database)
correct_fields_format(database, scenario)
print(f"Writing database for scenario {scenario}...")
UnfoldExporter(scenario, database).write_database()
write_brightway_database(scenario, database).write_database()

else:
source_db = [db for db in self.dependencies if db.get("type") == "source"]
Expand Down Expand Up @@ -1258,6 +1265,6 @@ def write(self, superstructure: bool = False, export_dir: str = None):
correct_fields_format(
self.database, self.name or self.package.descriptor["name"]
)
UnfoldExporter(
BW2UnfoldExporter(
self.name or self.package.descriptor["name"], self.database
).write_database()

0 comments on commit a94aa52

Please sign in to comment.