swolfpy

Project

class swolfpy.Project.Project(project_name, CommonData, Treatment_processes, Distance, Collection_processes=None, Technosphere_obj=None)[source]

Project class creates a new project in Brightway2.

Parameters:
  • project_name (str) – Name for the project

  • CommonData (class: swolfpy_inputdata.CommonData) – CommonData object

  • Treatment_processes (dict) – Dictionary for treatment processes include their input type and model.

  • Distance (class: swolfpy.Distance.Distance) – Distance object.

  • Collection_processes (dict, optional) – Dictionary for collection processes include their input type and model. Input type for the collection process is empty list [] as they don’t accept waste from other processes.

Note

Treatment processes and distance between them are required for creating a project. Collection processes are not required unless they are included in the system boundary.

Create sample project:

Step 1: Create CommonData and Treatment_processes dict with LF and WTE:

>>> from swolfpy_inputdata import CommonData
>>> from swolfpy_processmodels import LF
>>> from swolfpy_processmodels import WTE
>>> common_data = CommonData()
>>> Treatment_processes = {}
>>> Treatment_processes['LF']={'input_type':['RWC','Bottom_Ash','Fly_Ash','Other_Residual'],'model': LF()}
>>> Treatment_processes['WTE']={'input_type':['RWC','Other_Residual'],'model': WTE()}

Step 2: Create Distance object:

>>> from swolfpy_processmodels import Distance
>>> import pandas as pd
>>> Processes = ['LF','WTE','SF_COl']
>>> data = Distance.create_distance_table(Processes, ['Heavy Duty Truck'], default_dist=20)
>>> distance = Distance(data)

Step 3: Create Collection_processes dict with one single family sector which only has residual waste collection:

>>> from swolfpy_processmodels import SF_Col
>>> Collection_processes = {}
>>> Collection_scheme_SF_COL={'RWC':{'Contribution':1,'separate_col':{'SSR':0,'DSR':0,'MSR':0,'MSRDO':0,'SSYW':0,'SSYWDO':0}},
>>> 'SSO_DryRes':{'Contribution':0,'separate_col':{'SSR':0,'DSR':0,'MSR':0,'MSRDO':0,'SSYW':0,'SSYWDO':0}},
>>> 'REC_WetRes':{'Contribution':0,'separate_col':{'SSR':0,'DSR':0,'MSR':0,'MSRDO':0,'SSYW':0,'SSYWDO':0}},
>>> 'MRDO':{'Contribution':0,'separate_col':{'SSR':0,'DSR':0,'MSR':0,'MSRDO':0,'SSYW':0,'SSYWDO':0}}}
>>> Collection_processes['SF_COl']={'input_type':[],'model': SF_Col('SF_COl',Collection_scheme_SF_COL,
>>>                                 Treatment_processes=Treatment_processes,Distance=distance)}

Step 4: Create project:

>>> from swolfpy import Project
>>> demo = Project('demo',common_data,Treatment_processes,distance,Collection_processes)
>>> demo.init_project()
>>> demo.write_project()
>>> demo.group_exchanges()
>>> demo.parameters.default_parameters_list()
[{‘name’: ‘frac_of_Bottom_Ash_from_WTE_to_LF’, ‘amount’: 1.0},

{‘name’: ‘frac_of_Fly_Ash_from_WTE_to_LF’, ‘amount’: 1.0}, {‘name’: ‘frac_of_RWC_from_SF_COl_to_LF’, ‘amount’: 0.5}, {‘name’: ‘frac_of_RWC_from_SF_COl_to_WTE’, ‘amount’: 0.5}]

>>> demo.update_parameters(demo.parameters.default_parameters_list())
_find_destination(product)[source]

Find the processes that can treat the product. This function check the input_type in the Treatment_processes dictionary.

Parameters:

product (str) – Waste product e.g., RWC, Fly_Ash, Separated_Organics, Other_Residual

Returns:

A list of the discovered processes in the Treatment_processes dictionary that can treat the product

Return type:

list

init_project(signal=None)[source]

Calls the Create_Technosphere method to initialize a project.

This function create an empty database for each process as a placeholder, so swolfpy can browse these databases in the next step (writing project) and create exchanges between them.

write_project(signal=None)[source]

Call the import_database for all the process models.

_import_database(name)[source]

Instantiate the ProcessDB class for the process model and gets the LCI report from it; then translates the report for Brightway2 and populates the databases by Write_DB method.

Returns:

Returns a tuple (parameters,act_in_group)

Return type:

tuple

report_parameters()[source]

Reports the parameters in dictionary format.

Returns:

dictionary include the processes as key and parameters in each process as values.

Return type:

dict

report_parameters_list()[source]

Reports the parameters in list format.

Returns:

List of parameters (waste fractions) in the project

Return type:

list

group_exchanges(signal=None)[source]

Create a group for the parameters in each database and add the exchanges that include these parameters to this group.

As a results, model know to update the values in those exchanges when the parameter is updated

update_parameters(new_param_data, signal=None)[source]

Updates the parameters and their related exchanges based on the new_param_data.

Parameters:

new_param_data (list) – List of parameters (waste fractions) in the project with new values

Note

parameters are waste fractions which show what fraction of waste from one source go to different destinations, so sum of parameters from each source should be 1. (0<= parameters <=1)

create_scenario(input_dict, scenario_name)[source]

Creates a new scenario (activity).

static setup_LCA(name, functional_units, impact_methods)[source]

Perform LCA by instantiating the bw2calc.multi_lca class from Brightway2.

bw2calc.multi_lca is a wrapper class for performing LCA calculations with many functional units and LCIA methods.

static contribution_analysis(functional_unit, impact_method, limit, limit_type='number', target='emissions', figsize=(6, 4), font_scale=1)[source]

Perform LCA by instantiating the bw2calc.lca.LCA class from Brightway2 and then perform contribution analysis by bw2analyzer.ContributionAnalysis class. Check the following functions in bw2analyzer for more info:

  • bw2analyzer.ContributionAnalysis.annotated_top_processes

  • bw2analyzer.ContributionAnalysis.annotated_top_emissions

save(filename)[source]

Dumps the Project class to pickle file. User can load the pickle and use it later.

Parameters:

filename (str) –

Technosphere

class swolfpy.Technosphere.Technosphere(project_name, LCI_path=None, LCI_Reference_path=None, Ecospold2_Path=None)[source]
Parameters:
  • project_name (str) – Name for the project

  • LCI_path (str) – Path to the technosphere LIC csv file

  • LCI_Reference_path (str) – Path to the csv file for the technosphere references

  • Ecospold2_Path (str) – Path to the user defined technosphere LCI with ecospold2 format.

Create_Technosphere()[source]

Initialize a project in Brightway2 by calling the bw2setup() function which creates the biosphere3 database and imports the impact assessment methods.

It also adds 7 new biosphere flows for cost calculations swolfpy.

New impact methods are imported by calling the import_methods() from swolfpy_method module.

Note: If the project already exists, it will delete all the databases except ‘biosphere3’. Technosphere database is written from the SWOLF_AccountMode_LCI DATA.csv in the Data folder unless user select new file with it’s path.

_Write_user_technosphere()[source]

Creates the user technosphere database from Ecospold2 files.

Interface with Brightway2: Calls the

bw2io.importers.SingleOutputEcospold2Importer function.

_write_technosphere()[source]

Creates the swolfpy technosphere database.

_check_nan(x)[source]

Check the x and return 0 if x is nan.

ProcessDB

class swolfpy.ProcessDB.ProcessDB(process_name, waste_treatment, CommonData, process_types, Distance=None)[source]
check_nan(x)[source]
static init_DB(DB_name, waste_flows)[source]
Write_DB(waste_flows, parameters, Process_Type)[source]
_add_transport_from_collection()[source]

Adding activity for transport between the collection and treatment processes.

_add_transport_between_processes()[source]

Adding activity for transport between the treatment processes.

_write_DB_from_dict()[source]
exchange(Input, Type, Unit, Amount, Formula=None, Act=None, product=None)[source]

Return exchange in a dictionary format.

static _helper_wasteflow_name(name: str) str[source]

Removes the collection index and returns the waste fraction index.

Parameters

class swolfpy.Parameters.Parameters(processes, CommonData)[source]
add_parameter(product, process_model_from, process_model_to, value, dynamic_param=True)[source]

Define new parameter.

Parameters:
  • product (str) – Name of stream

  • process_model_from (str) – Name of the process which is source of stream

  • process_model_to (str) – Name of the process which is destination of stream

  • value (float) – Value for the parameter

SWM_network(view=True, show_vals=True, all_flow=True, filename='SWM_network')[source]

To render the generated DOT source code, you also need to install Graphviz..

..note:: Make sure that the directory containing the dot executable is on your systems path.

add_edge(head, tail, name, value=None)[source]
default_parameters_list()[source]
parameters_list()[source]
update_values(param_name, val, simulation=False)[source]
check_sum()[source]

Check that sum of the waste fractions (parameters) for each stream from one source to all available destinations is 1.

add_uncertainty(param_name, **kwargs)[source]

Add uncertainty to parameter.

Parameters:

param_name (str) – Name of the parameter (wastefraction) that has uncertainty

setup_MC(seed=None)[source]

Import uncertainty to stats_arrays package.

MC_calc()[source]

Generates new values for uncertain parameters.

normalize()[source]

Normalize the parameters after updating the valuse by monte carlo.

MC_get_param_val(param_name)[source]

Report the uncertain value created for parameter.

Parameters:

param_name (str) – Name of the parameter (wastefraction) that has uncertainty

Returns:

Value of the parameter

Return type:

float

Param_exchanges(new_vals)[source]

Returns the parameters exchanges with the new values.

swolfpy_method

swolfpy.swolfpy_method.import_methods(path_to_methods=None)[source]

Imports the user defined LCIA methods from the csv files in the path.

LCA Matrix

class swolfpy.LCA_matrix.LCA_matrix(functional_unit, method)[source]

Bases: LCA

This class translate the row and col of the tech_param and bio_param to the activity key in the Brightway2 database. Both the tech_param and bio_param has the dtype=[('input', '<u4'), ('output', '<u4'), ('row', '<u4'), ('col', '<u4'), ('type', 'u1'), ('uncertainty_type', 'u1'), ('amount', '<f4'), ('loc', '<f4'), ('scale', '<f4'), ('shape', '<f4'), ('minimum', '<f4'), ('maximum', '<f4'), ('negative', '?')]) data type.

self.tech_matrix is a dictionary that includes all the technosphere and waste exchanges as tuple (product,Feed) key and amount as value: {(('LF', 'Aerobic_Residual'), ('SF1_product', 'Aerobic_Residual_MRDO')):0.828}

self.bio_matrix is a dictionary that includes all the biosphere exchanges as tuple (product,Feed) key and amount as value {(('biosphere3', '0015ec22-72cb-4af1-8c7b-0ba0d041553c'), ('Technosphere', 'Boiler_Diesel')):6.12e-15}

So we can update the tech_params and bio_params by tuple keys that are consistent with the keys in the ProcessModel.report(). Check Process models class for more info.

static update_techmatrix(process_name, report_dict, tech_matrix)[source]

Updates the tech_matrix according to the report_dict. tech_matrix is an instance of LCA_matrix.tech_matrix. Useful for Monte Carlo simulation, and optimization.

Parameters:
  • process_name (str) – Name of the life-cycle process model.

  • report_dict (dict) – LCI report of the life-cycle process model (swolfpy_processmodels.ProcessModel.report()).

  • tech_matrix (LCA_matrix.tech_matrix) –

static update_biomatrix(process_name, report_dict, bio_matrix)[source]

Updates the bio_matrix according to the report_dict. bio_matrix is an instance of LCA_matrix.bio_matrix. Useful for Monte Carlo simulation, and optimization.

Parameters:
  • process_name (str) – Name of the life-cycle process model.

  • report_dict (dict) – LCI report of the life-cycle process model (swolfpy_processmodels.ProcessModel.report()).

  • bio_matrix (LCA_matrix.bio_matrix) –

static get_mass_flow(LCA, process)[source]

Calculates the total mass of flows to process based on the supply_array in bw2calc.lca.LCA.

Parameters:
  • LCA (bw2calc.lca.LCA or swolfpy.LCA_matrix.LCA_matrix) – LCA object.

  • process (str) – Name of the process databases.

Returns:

Total mass of flows to process

Return type:

float

static get_mass_flow_comp(LCA, process, index)[source]

Calculates the mass of flows to process based on the index and supply_array in bw2calc.lca.LCA.

Parameters:
  • LCA (bw2calc.lca.LCA or swolfpy.LCA_matrix.LCA_matrix) – LCA object.

  • process (str) – Name of the process databases.

  • index (str) – Name of the process databases.

Returns:

Pandas series with mass flows as values and index as rows.

Return type:

pandas.core.series.Series

Monte Carlo

class swolfpy.Monte_Carlo.Monte_Carlo(functional_unit, method, project, process_models=None, process_model_names=None, common_data=None, parameters=None, seed=None)[source]

Bases: LCA_matrix

Setups the Monte Carlo simulation. This class is inherited from swolfpy.LCA_matrix. The Monte Carlo simulation will be only done for the process models, common data or parameters than the class gets by arguments.

Parameters:
  • functional_unit (dict) – {flow:amount}

  • method (list) – List of methods for MC.

  • project (str) – Name of the project.

  • process_models (list, optional) – list of the process models.

  • process_model_names (list, optional) – list of process models’ names.

  • common_data (swolfpy_inputdata.CommonData.CommonData , optional) – CommonData object.

  • parameters (swolfpy_inputdata.Parameters.Parameters,optional) – Parameters object

  • seed (int, optional) – seed for stats_arrays.RandomNumberGenerator

run(nproc, n)[source]

Runs the Monte Carlo n times with nproc processors. Calls and map the Monte_Carlo.worker() to the processors.

Parameters:
  • nproc (int) – Number of processors allocated to MC

  • n (int) – Number of iterations in MC

static worker(args)[source]

Setups the Monte Carlo for process models and input data and then creates the LCA object and Calls the Monte_Carlo.parallel_mc() for n times.

static parallel_mc(lca, method, tech_matrix, bio_matrix, process_models=None, process_model_names=None, parameters=None, common_data=None, index=None)[source]

Calls the InputData.gen_MC() , ProcessModel.MC_calc() and parameters.MC_calc() and then gets the new LCI and updates the tech_matrix and bio_matrix.

Creates new bio_param and tech_param and then recalculate the LCA.

result_to_DF()[source]

Returns the results from the Monte Carlo in a pandas.DataFrame format.

Returns:

Monte Carlo results

Return type:

pandas.DataFrame

save_results(name)[source]

Save the results from the Monte Carlo to pickle file.

Optimization

class swolfpy.Optimization.Optimization(functional_unit, method, project)[source]

Bases: LCA_matrix

Parameters:
  • functional_unit (dict) –

  • method (list) –

  • project (swolfpy.Project.Project) –

static get_config(project)[source]
set_config(config)[source]
update_col_scheme(x)[source]
_objective_function(x)[source]

Use the new parameters (Waste fractions) to update the tech_matrix (tech_param) and recalculate the LCA score.

get_mass_flow_from_supply_array(key, KeyType, x)[source]

Calculate the mass to the process from the supply_array matrix.

get_emission_amount(emission, x)[source]

Calculate the mass of the emission to biosphere from the inventory.

get_impact_amount(impact, x)[source]

Calculates impacts other than objective.

_create_equality(N_param_Ingroup)[source]

Check that the sum of parameters in each group should be one.

_create_inequality(key, limit, KeyType, ConstType)[source]
Parameters:
  • key (str or tuple) – process name, key for activity in process or key for activity in biosphere

  • limit (float) –

  • KeyType (str) – "Process", "WasteToProcess", "Emission"

  • ConstType (str) – "<=" , ">="

_create_collection_constraints(cons)[source]
_col_const_helper(const_dict, k, cons)[source]
_create_constraints()[source]
static multi_start_optimization(optObject, constraints=None, collection=False, n_iter=30, nproc=None, timeout=None, initialize_guess='random')[source]

Call the scipy.optimize.minimize() to minimize the LCA score.

Notes

  • constraints is python dictionary.

  • Constraint type can be '<=' or '>='.

  • Three kind of constraints are defined as below:

  • Process: Constraint on the total mass to the process. The 'KeyType' should be 'Process' (e.g., The capacity of the WTE). Example:

>>> constraints = {}
>>> # Use name the the process as key in dict
>>> constraints['WTE'] = {'limit':100, 'KeyType':'Process','ConstType':"<="}
  • WasteToProcess: Constraint on the total mass of waste fraction to the process. The 'KeyType' should be 'WasteToProcess' (e.g., Ban food waste from landfill). Example:

>>> constraints = {}
>>> # Use database key as key in dict
>>> constraints[('LF','Food_Waste_Vegetable')] = {'limit':0, 'KeyType':'WasteToProcess','ConstType':"<="}
  • Emission: Constraint on the emissions. The 'KeyType' should be 'Emission' (e.g., CO2 emissions Cap). Example:

>>> constraints = {}
>>> # Use database key as key in dict
>>> constraints[('biosphere3', 'eba59fd6-f37e-41dc-9ca3-c7ea22d602c7')] = {'limit':100,'KeyType':'Emission','ConstType':"<="}
static abortable_worker(func, *args, **kwargs)[source]
static worker(optObject, bnds, x0, iteration)[source]
set_optimized_parameters_to_project()[source]
plot_sankey(optimized_flow=True, show=True, fileName=None, params=None)[source]

Plots a sankey diagram for the waste mass flows. Calls the plotly.graph_objs.Sankey to plot sankey. Calculates the mass flows by calling self.get_mass_flow_from_supply_array().

Parameters:
  • optimized_flow (bool) – If True, it plots the sankey based on the optimized waste fractions. If False, it plots the sankey based on the current waste fractions by calling self.project.parameters_list.

  • show (bool) – If True, it will show the figure