brightway-lca / brightway2-io

Importing and exporting for the Brightway LCA framework
BSD 3-Clause "New" or "Revised" License
26 stars 40 forks source link

Export to excel/csv with "temporal distribution" (1/2 solved) #195

Open Stew-McD opened 1 year ago

Stew-McD commented 1 year ago

This issue came up last week in Barcelona at the spatio-temporal training, I've had a go at fixing it. I can import and export the TD objects now without a problem
The test file I used to work this out is here

Unfortunately, I have not yet been able to integrate my functions into the bw2io codebase.

Problem

When temporal distributions are added to exchanges, the database cannot be exported to excel/csv. This is because the temporal distributions are stored as numpy arrays.

Solution

function 1: TD_to_string()

Converts all temporal distributions in a database to a set of strings (using np.array2string)

def TD_to_string(db):
    for act in db:
        for exc in act.technosphere():
            if "TD" in exc:
                exc['TD_amount'] = np.array2string(exc['TD'].amount, 
                    separator=", ").replace('[', "").replace(']',"").replace("\n", "")
                exc['TD_time'] = np.array2string(exc['TD'].date, 
                    separator=", ").replace('[', "").replace(']',"").replace("\n", "")
                exc['TD_time_type'] = str(exc['TD'].base_time_type)
                exc.pop("TD")
                exc.save()

    return db

function 2: string_to_TD()

Converts the strings back into their original form as TD objects (using np.fromstring)
(after importing the database from excel)

def string_to_TD(db):


    for act in db:
        for exc in act.technosphere():
            try:
                td_amount = np.fromstring(exc['TD_amount'], sep=', ', dtype=float)
                td_date = np.fromstring(exc['TD_time'], sep=', ', dtype=exc['TD_time_type'])
                exc["TD"] = bwt.TemporalDistribution(td_date, td_amount)

                exc.pop("TD_amount")
                exc.pop("TD_time")
                exc.pop("TD_time_type")
                exc.save()
            except KeyError:
                pass

    return db

Possible implementation of the solution in to bw2io (optimal is a different story)