2

I would like to modify an activity's exchanges and save the activity back to the database.
It is possible to change other aspects of the activity, like its name:
some_act['name'] = "some new name"
and then save the activity with: some_act.save()
It is also possible to modify exchanges the same way:
some_exc['scale"] = 0.5
and then save the exchange with:
some_exc.save()

However, the only way I have found to add/delete exchanges from a specific activity is to go through the dictionary version of the activity:

some_act_dataset = some_act._data
some_act_dataset['exchanges'] = [{exchange1}, {exchange2}] # exc must be valid exchange dict

The problem is that I don't know how to save the new activity (as dict) back to the database.
some_act_dataset.save() doesn't work, since dictionaries don't have a save method. Database("my_database").write(some_act_dataset)overwrites all the other data in the database.

I could work in the loaded database:
loaded_db = Database("my_database").load()
and make the changes I need in the resulting dictionary, and then write the whole database, but when the databases are big, this seems like a costly operation.

So, the question is: is there a way to modify an activity's exchanges and save the activity back to the database without needing to overwrite the entire database?

MPa
  • 1,086
  • 1
  • 10
  • 25

1 Answers1

4

Actiities and exchanges are stored in separate tables in the SQLite database, and they each have their own object. In the journey to and from the database, several translation layers are used:

Brightway2 Activity object hierarchy

However, we almost always work with Activity or Exchange objects. The key point here is that because activities and exchanges are two separate tables, they have to be treated separately.

To create a new exchange, use Activity.new_exchange():

In [1] from brightway2 import *

In [2]: act = Database("something").random()

In [3]: exc = act.new_exchange()

In [4]: type(exc)
Out[4]: bw2data.backends.peewee.proxies.Exchange

You can also specify data attributes in the new_exchange method call:

In [5]: exc = act.new_exchange(amount=1)

In [6]: exc['amount']
Out[6]: 1

To delete an Exchange, call Exchange.delete(). If you are doing a lot of data manipulation, you can either execute SQL directly against the database, or write peewee queries with ActivityDataset or ExchangeDataset (see e.g. the queries built in the construction of an Exchanges object).

Chris Mutel
  • 2,549
  • 1
  • 14
  • 9