bw2data.backends.proxies#

Attributes#

Classes#

Activity

A MutableMapping is a generic container for associating

Exchange

A MutableMapping is a generic container for associating

Exchanges

Iterator for exchanges with some additional methods.

Module Contents#

class bw2data.backends.proxies.Activity(document=None, **kwargs)[source]#

Bases: bw2data.proxies.ActivityProxyBase

A MutableMapping is a generic container for associating key/value pairs.

This class provides concrete generic implementations of all methods except for __getitem__, __setitem__, __delitem__, __iter__, and __len__.

Create an Activity proxy object.

If this is a new activity, can pass kwargs.

If the activity exists in the database, document should be an ActivityDataset.

_change_code(new_code: str, signal: bool = True)[source]#
_change_database(new_database: str, signal: bool = True)[source]#
_create_activity_copy(**kwargs) typing_extensions.Self[source]#
biosphere(exchanges_class=Exchanges)[source]#
consumers(kinds=labels.technosphere_negative_edge_types)[source]#
copy(code: str | None = None, signal: bool = True, **kwargs)[source]#

Copy the activity. Returns a new Activity.

code is the new activity code; if not given, a UUID is used.

kwargs are additional new fields and field values, e.g. name=’foo’

create_aggregated_process(database: str | None = None, signal: bool = True, **kwargs) tuple[typing_extensions.Self, typing_extensions.Self][source]#

Create a new aggregated process representing the life cycle inventory of this process.

This method performs a life cycle inventory (LCI) calculation for the reference product of this process and creates a new aggregated process node with all biosphere exchanges from the upstream supply chain. The aggregated process represents the cumulative environmental impacts of producing the reference product.

The method: 1. Performs an LCA calculation for the reference product 2. Creates a copy of this process (and optionally the product node if different) 3. Creates a production exchange linking the new process to the new product 4. Creates biosphere exchanges for all non-zero inventory flows

Parameters:
  • database – Name of the target database where the new process will be created. If None, uses the current process’s database. The database must already exist. Defaults to None.

  • signal – Whether to emit database signals during save operations. Defaults to True.

  • **kwargs – Additional keyword arguments passed to _create_activity_copy() to customize the new process attributes (e.g., name, location, etc.).

Returns:

A tuple containing:
  • The new aggregated process node

  • The new product node (or the same as the process if the process produces itself)

Return type:

tuple[Activity, Activity]

Raises:
  • ValueError – If database is provided and doesn’t exist, or if this activity is not a process node type (must be “process” or “processwithreferenceproduct”).

  • ImportError – If bw2calc is not installed (required for LCA calculations).

Examples

Create an aggregated process in the same database:

>>> process = Database("my_db").get("process_code")
>>> new_process, new_product = process.create_aggregated_process()

Create an aggregated process in a different database with custom attributes:

>>> new_process, new_product = process.create_aggregated_process(
...     database="aggregated_db",
...     name="Aggregated Steel Production",
...     location="GLO"
... )

The new process will contain all biosphere exchanges from the upstream supply chain:

>>> for exc in new_process.exchanges():
...     if exc["type"] == "biosphere":
...         print(f"{exc['input'][1]}: {exc['amount']}")
delete(signal: bool = True)[source]#
edges()[source]#
exchanges(exchanges_class=Exchanges)[source]#
new_edge(**kwargs)[source]#

Create a new exchange linked to this activity

new_exchange(**kwargs)[source]#
producers()[source]#
production(include_substitution=False, exchanges_class=Exchanges)[source]#
rp_exchange()[source]#

Return an Exchange object corresponding to the reference production. Uses the following in order:

  • The production exchange, if only one is present

  • The production exchange with the same name as the activity reference product.

Raises ValueError if no suitable exchange is found.

save(signal: bool = True, data_already_set: bool = False, force_insert: bool = False)[source]#

Saves the current activity to the database after performing various checks. This method validates the activity, updates the database status, and handles geographical and indexing updates. It raises an error if the activity is not valid and updates relevant data in the database.

Raises:

ValidityError – If the activity is not valid, an error is raised detailing the reasons.

Notes

The method performs the following operations: - Checks if the activity is valid. - Marks the database as ‘dirty’, indicating changes. - Checks for type and key validity of the activity. - Updates the activity’s associated document in the database. - Updates the geographical mapping if needed. - Updates the index if the database is searchable.

Examples

>>> activity.save()

Saves the activity if it’s valid, otherwise raises ValidityError.

substitution(exchanges_class=Exchanges)[source]#
technosphere(exchanges_class=Exchanges)[source]#
upstream(kinds=labels.technosphere_negative_edge_types, exchanges_class=Exchanges)[source]#
ORMDataset: typing_extensions.TypeAlias[source]#
property id[source]#
property key[source]#
class bw2data.backends.proxies.Exchange(document=None, **kwargs)[source]#

Bases: bw2data.proxies.ExchangeProxyBase

A MutableMapping is a generic container for associating key/value pairs.

This class provides concrete generic implementations of all methods except for __getitem__, __setitem__, __delitem__, __iter__, and __len__.

Create an Exchange proxy object.

If this is a new exchange, can pass kwargs.

If the exchange exists in the database, document should be an ExchangeDataset.

_process_temporal_distributions(data)[source]#

Process temporal_distribution attributes by converting TemporalDistribution instances to JSON.

This method creates a copy of the data and converts any TemporalDistribution instances found in ‘temporal_distribution’ keys to their JSON representation using the to_json method. The original data is not modified.

Parameters:

data – The exchange data dictionary

Returns:

A copy of the data with TemporalDistribution instances converted to JSON

_restore_temporal_distributions(data)[source]#

Restore temporal_distribution attributes by converting JSON back to TemporalDistribution instances.

This method creates a copy of the data and converts any JSON representations of TemporalDistribution instances back to TemporalDistribution objects. The original data is not modified.

Parameters:

data – The exchange data dictionary

Returns:

A copy of the data with JSON temporal_distribution converted back to TemporalDistribution instances

delete(signal: bool = True)[source]#
save(signal: bool = True, data_already_set: bool = False, force_insert: bool = False)[source]#
ORMDataset: typing_extensions.TypeAlias[source]#
property id[source]#
class bw2data.backends.proxies.Exchanges(key, kinds=None, reverse=False)[source]#

Bases: collections.abc.Iterable

Iterator for exchanges with some additional methods.

This is not a generator; next() is not supported. Everything time you start to iterate over the object you get a new list starting from the beginning. However, to get a single item you can do next(iter(foo)).

Ordering is by database row id.

Supports the following:

exchanges = activity.exchanges()

# Iterate
for exc in exchanges:
    pass

# Length
len(exchanges)

# Delete all
exchanges.delete()
_get_queryset()[source]#
delete(allow_in_sourced_project: bool = False)[source]#
filter(expr)[source]#
to_dataframe(categorical: bool = True, formatters: List[Callable] | None = None) pandas.DataFrame[source]#

Return a pandas DataFrame with all node exchanges. Standard DataFrame columns are:

target_id: int, target_database: str, target_code: str, target_name: Optional[str], target_reference_product: Optional[str], target_location: Optional[str], target_unit: Optional[str], target_type: Optional[str] source_id: int, source_database: str, source_code: str, source_name: Optional[str], source_product: Optional[str], # Note different label source_location: Optional[str], source_unit: Optional[str], source_categories: Optional[str] # Tuple concatenated with “::” as in bw2io edge_amount: float, edge_type: str,

Target is the node consuming the edge, source is the node or flow being consumed. The terms target and source were chosen because they also work well for biosphere edges.

Args:

categorical will turn each string column in a pandas Categorical Series. This takes 1-2 extra seconds, but saves around 50% of the memory consumption.

formatters is a list of callables that modify each row. These functions must take the following keyword arguments, and use the Wurst internal data format:

  • node: The target node, as a dict

  • edge: The edge, including attributes of the source node

  • row: The current row dict being modified.

The functions in formatters don’t need to return anything, they modify row in place.

Returns a pandas DataFrame.

_key[source]#
bw2data.backends.proxies.TemporalDistribution = None[source]#