### Compute the MFA system Source: https://flodym.readthedocs.io/en/latest/example1.html Runs the computation for the MFA example. This is the first step before plotting any flows. ```python mfa_example.compute() ``` -------------------------------- ### Import flodym and useful packages Source: https://flodym.readthedocs.io/en/latest/example2.html Loads the flodym library and its core components, along with os, copy, and numpy. This is the initial setup for using flodym in a notebook. ```python import os from copy import deepcopy import numpy as np from flodym import ( DimensionDefinition, FlowDefinition, MFADefinition, MFASystem, ParameterDefinition, SimpleFlowDrivenStock, StockDefinition, ) from flodym.export import PlotlyArrayPlotter, PlotlyProcessGraphPlotter ``` -------------------------------- ### Export MFA to pickle with export_mfa_to_pickle() Source: https://flodym.readthedocs.io/en/latest/howto8.html Saves an MFASystem to a pickle file using export_mfa_to_pickle(). The example enables logging to show the save confirmation. The pickle file requires flodym to read it back. ```python # turn on logging import logging logging.basicConfig(level=logging.INFO) from flodym.export import export_mfa_to_pickle export_path = "output_data/mfa.pickle" export_mfa_to_pickle(mfa=mfa, export_path=export_path) ``` ```text INFO:root:Data saved to output_data/mfa.pickle ``` -------------------------------- ### Create FlowDefinition instances Source: https://flodym.readthedocs.io/en/latest/api.definitions.html Example from the FlowDefinition documentation showing how to create two flow definitions with from_process_name, to_process_name, and dim_letters. These are used in MFADefinition to create a custom MFA system. ```python >>> from flodym import FlowDefinition >>> flow_one = FlowDefinition(from_process_name='fabrication', to_process_name='use', dim_letters=('r', 't')) >>> flow_two = FlowDefinition(from_process_name='use', to_process_name='end_of_life', dim_letters=('r', 't')) ``` -------------------------------- ### Initialize parameters dictionary with Parameter objects Source: https://flodym.readthedocs.io/en/latest/howto5.html Initializes parameters with data using numpy arrays. Parameters transfer values to flows, making data input easier when reading from files. This example uses a 3x1 array for extraction and 1D arrays for product shares and yields. ```python import numpy as np parameters = { "extraction": Parameter(name="extraction", dims=dims["r", "t"], values=3.0 * np.ones((3, 1))), "product_shares": Parameter( name="product_shares", dims=dims[("p",)], values=np.array([0.6, 0.4]) ), "process_a_yield": Parameter( name="process_a_yield", dims=dims[("p",)], values=np.array([0.8, 0.9]) ), } ``` -------------------------------- ### Import flodym and other packages Source: https://flodym.readthedocs.io/en/latest/example5.html Imports required packages including flodym core classes and NormalLifetime for the MFA example. ```python from os.path import join import numpy as np import pandas as pd import plotly.express as px from flodym import ( DimensionDefinition, Dimension, DimensionSet, ParameterDefinition, Parameter, FlowDefinition, StockDefinition, MFASystem, MFADefinition, DataReader, InflowDrivenDSM, ) from flodym.lifetime_models import NormalLifetime ``` -------------------------------- ### Render MFA structure with GraphvizProcessGraphPlotter Source: https://flodym.readthedocs.io/en/latest/api.export_and_plotting.html Constructs a `graphviz.Digraph` for the MFA system's structure and renders it to a PNG file. Requires the optional `graphviz` python package; rendering additionally needs Graphviz system binaries. The example uses `mfa` as an already defined MFASystem. ```python >>> from flodym.export import GraphvizProcessGraphPlotter >>> dot = GraphvizProcessGraphPlotter(mfa=mfa).plot() >>> dot.render("system_structure", format="png") ``` -------------------------------- ### Define a custom MFA System subclass Source: https://flodym.readthedocs.io/en/latest/api.mfa_system.html Example of defining a custom MFA system by subclassing MFASystem and implementing the compute method. The compute method should contain the computations on the system's stocks and flows. ```python >>> from flodym import MFASystem >>> class CustomMFA(MFASystem): >>> def compute(self): >>> # do some computations on the CustomMFA attributes: stocks and flows ``` -------------------------------- ### Define a custom MFASystem subclass with compute method Source: https://flodym.readthedocs.io/en/latest/howto5.html Shows how to subclass MFASystem and implement a compute method that performs array operations on flows and parameters. The example uses flows like 'sysenv => process_a' and parameters like 'extraction' and 'product_shares'. ```python from flodym import MFASystem class MyMFASystem(MFASystem): def compute(self): self.flows["sysenv => process_a"][...] = self.parameters["extraction"] product_flow = self.flows["sysenv => process_a"] * self.parameters["product_shares"] self.flows["process_a => process_b"][...] = ( product_flow * self.parameters["process_a_yield"] ) self.flows["process_a => sysenv"][...] = product_flow * ( 1.0 - self.parameters["process_a_yield"] ) self.flows["process_b => sysenv"][...] = self.flows["process_a => process_b"] ``` -------------------------------- ### Create and display a process graph figure with PlotlyProcessGraphPlotter Source: https://flodym.readthedocs.io/en/latest/api.export_and_plotting.html Initializes a PlotlyProcessGraphPlotter with an MFA system and produces a plotly figure via the plot() method, then shows it with fig.show(). This example uses the default configuration, where processes are layered based on their longest path from the system boundary and distributed horizontally. ```python >>> from flodym.export import PlotlyProcessGraphPlotter >>> fig = PlotlyProcessGraphPlotter(mfa=mfa).plot() >>> fig.show() ``` -------------------------------- ### Convert MFASystem to dictionary with convert_to_dict() Source: https://flodym.readthedocs.io/en/latest/howto8.html Converts an MFASystem to a nested dictionary using convert_to_dict() with type 'pandas' or 'numpy'. The example prints the keys and data types for both conversions. Parameters are not included in the dictionary. ```python from flodym.example_objects import get_example_mfa from flodym.export import convert_to_dict # printing function def print_types(dict_in): first_items = { k: next(iter(v.values())) if isinstance(v, dict) else v[0] for k, v in dict_in.items() } type_strings = [f" {k}: {type(v)}" for k, v in first_items.items()] print("Keys and data types:") print("\n".join(type_strings)) mfa = get_example_mfa() mfa.compute() print("Pandas:") df_dict = convert_to_dict(mfa, type="pandas") print_types(df_dict) print() print("Numpy:") np_dict = convert_to_dict(mfa, type="numpy") print_types(np_dict) ``` ```text Pandas: Keys and data types: dimension_names: dimension_items: processes: flows: flow_dimensions: flow_processes: stocks: stock_dimensions: stock_processes: Numpy: Keys and data types: dimension_names: dimension_items: processes: flows: flow_dimensions: flow_processes: stocks: stock_dimensions: stock_processes: ``` -------------------------------- ### Create FlodymArray from DataFrame using from_df() Source: https://flodym.readthedocs.io/en/latest/howto7.html This example shows how to create a FlodymArray from a pandas DataFrame using the from_df() method. It defines dimensions for Time and Material, creates a DataFrame with values, and then prints the shape and values of the resulting array. The output demonstrates that the data is reordered according to the order of items in the dimensions. ```python import pandas as pd from flodym import Dimension, DimensionSet, FlodymArray dims = DimensionSet( dim_list=[ Dimension(letter="t", name="Time", dtype=int, items=[2010, 2020]), Dimension(letter="e", name="Material", dtype=str, items=["Fe", "Cu", "Mn"]), ] ) df = pd.DataFrame( { "Time": [2020, 2020, 2020, 2010, 2010, 2010], "Material": ["Mn", "Cu", "Fe", "Fe", "Cu", "Mn"], "value": [6.0, 5.0, 4.0, 1.0, 2.0, 3.0], } ) my_array = FlodymArray.from_df(dims=dims, df=df) print("Shape:", my_array.shape) print("Values:", my_array.values.flatten()) ``` ```output Shape: (2, 3) Values: [1. 2. 3. 4. 5. 6.] ``` -------------------------------- ### Initialize an MFA System with a DimensionSet Source: https://flodym.readthedocs.io/en/latest/howto5.html Shows the most direct way to initialize an MFA system by creating a DimensionSet with dimensions for Region, Product, and Time. This is a prerequisite for passing attributes to the system. ```python from flodym import DimensionSet, Dimension, Flow, Parameter, Process dims = DimensionSet( dim_list=[ Dimension(name="Region", letter="r", items=["EU", "US", "MEX"]), Dimension(name="Product", letter="p", items=["A", "B"]), Dimension(name="Time", letter="t", items=[2020]), ] ) ``` -------------------------------- ### Convert FlodymArray to DataFrame with to_df() Source: https://flodym.readthedocs.io/en/latest/howto8.html Exports a FlodymArray to a pandas DataFrame using the to_df() method. The example creates an example array and displays the first rows. The method has options to customize the format, such as exporting only non-zero values. ```python from flodym.example_objects import get_example_array array = get_example_array() df = array.to_df() df.head() ``` -------------------------------- ### size(key) Source: https://flodym.readthedocs.io/en/latest/api.dimensions.html Gets the number of items in a dimension. ```APIDOC ## size(key) ### Description Get the number of items in a dimension. ### Parameters - **key** (_str_) - Required - the name or letter of the dimension to get the size of ``` -------------------------------- ### MFA System.get_new_array Source: https://flodym.readthedocs.io/en/latest/api.mfa_system.html Method to get a new FlodymArray object with specified dimensions. ```APIDOC ## MFA System.get_new_array ### Description Get a new FlodymArray object. ### Method method ### Endpoint MFA System.get_new_array ### Parameters - **dim_letters** (_tuple_ _|__None_) – Optional - tuple of dimension letters to include in the new FlodymArray. If None, all dimensions are included. - **kwargs** – Optional - keyword arguments to pass to the FlodymArray constructor. ### Return Type _FlodymArray_ ``` -------------------------------- ### Initialize MyMFASystem with dims, processes, flows, parameters Source: https://flodym.readthedocs.io/en/latest/howto5.html Creates the MFA system instance by passing the dimensions, processes, flows, and parameters dictionaries. This is the final step before computing the system. ```python my_mfa_system = MyMFASystem( dims=dims, processes=processes, flows=flows, parameters=parameters, ) ``` -------------------------------- ### Initialize ExcelParameterReader with file and sheet mappings Source: https://flodym.readthedocs.io/en/latest/howto7.html Creates dictionaries mapping parameter names to file paths and sheet names, then initializes the reader with them. ```python parameter_file = "../examples/input_data/example2_parameters.xlsx" parameter_files = {p.name: parameter_file for p in parameter_definitions} parameter_sheets = {p.name: p.name for p in parameter_definitions} reader = ExcelParameterReader( parameter_files=parameter_files, parameter_sheets=parameter_sheets, ) ``` -------------------------------- ### Visualize MFA system with PlotlyProcessGraphPlotter Source: https://flodym.readthedocs.io/en/latest/example1.html Creates a plotter for the MFA system and displays the graph in a notebook. Requires the mfa_example instance from the previous step. ```python graph_plotter = PlotlyProcessGraphPlotter(mfa=mfa_example) fig = graph_plotter.plot() fig.show(renderer="notebook") ``` -------------------------------- ### Get a slice from a FlodymArray Source: https://flodym.readthedocs.io/en/latest/howto4.html Shows how to retrieve a slice by indexing with an item name. The output shows the resulting array's dimensions, shape, and values. ```python # recall print("flow_a dimensions: ", flow_a.dims.letters) slice_a1 = flow_a["A"] print("slice_a1:") show_array(slice_a1) ``` ```text flow_a dimensions: ('t', 'p') slice_a1: dimensions: ('t',) shape: (1,) name: unnamed values mean: 0.090 values sum: 0.090 ``` -------------------------------- ### Initialize ExcelDimensionReader with file and sheet mappings Source: https://flodym.readthedocs.io/en/latest/howto7.html Creates dictionaries mapping dimension names to file paths and sheet names, then initializes the reader with them. ```python dimension_file = "../examples/input_data/example2_dimensions.xlsx" dimension_files = {d.name: dimension_file for d in dimension_definitions} dimension_sheets = {d.name: d.name for d in dimension_definitions} reader = ExcelDimensionReader( dimension_files=dimension_files, dimension_sheets=dimension_sheets, ) ``` -------------------------------- ### Create SimpleFlowDrivenStock and compute stock Source: https://flodym.readthedocs.io/en/latest/howto6.html Creates a SimpleFlowDrivenStock with time and product dimensions, sets inflow/outflow values, computes the stock as cumulative sum, and prints results. The output shows the stock array type, outflow shape, stock sum, and array names. ```python from flodym import SimpleFlowDrivenStock, Dimension, DimensionSet dims = DimensionSet( dim_list=[ Dimension(letter="t", name="Time", dtype=int, items=list(range(2000, 2011))), Dimension(letter="p", name="Product", dtype=str, items=["Vehicles", "Buildings", "Other"]), ] ) my_stock = SimpleFlowDrivenStock(dims=dims, name="in-use") # example output print("Inflow type:", type(my_stock.inflow)) print("Outflow shape:", my_stock.outflow.shape) print("Stock sum:", my_stock.stock.sum_values()) print(f"Array names: {my_stock.stock.name}, {my_stock.inflow.name}, {my_stock.outflow.name}") ``` ```text Inflow type: Outflow shape: (11, 3) Stock sum: 0.0 Array names: in-use_stock, in-use_inflow, in-use_outflow ``` -------------------------------- ### MFA System.from_excel Source: https://flodym.readthedocs.io/en/latest/api.mfa_system.html Class method to define and set up the MFA system by loading data from Excel files. Initializes stocks and flows with zero values. ```APIDOC ## MFA System.from_excel ### Description Define and set up the MFA system and load all required data from Excel files. Initialises stocks and flows with all zero values. Builds a CompoundDataReader from Excel readers, and calls the from_data_reader class method. ### Method _classmethod_ ### Endpoint MFA System.from_excel ### Parameters - **definition** (_MFADefinition_) – Required - The MFA definition object - **dimension_files** (_dict_) – Required - A dictionary mapping dimension names to Excel files - **parameter_files** (_dict_) – Required - A dictionary mapping parameter names to Excel files - **dimension_sheets** (_dict_ _|__None_) – Optional - A dictionary mapping dimension names to sheet names in the Excel files - **parameter_sheets** (_dict_ _|__None_) – Optional - A dictionary mapping parameter names to sheet names in the Excel files - **allow_missing_parameter_values** (_bool_) – Optional - Whether to allow missing values in the parameter data (missing rows or empty value cells) - **allow_extra_parameter_values** (_bool_) – Optional - Whether to allow extra values in the parameter data ### Notes See `flodym.ExcelDimensionReader`, `flodym.ExcelParameterReader`, and `flodym.FlodymArray.from_df()` for expected format. ``` -------------------------------- ### Create DimensionDefinition instances Source: https://flodym.readthedocs.io/en/latest/api.definitions.html Use this snippet to create DimensionDefinition objects for time and region dimensions. The example imports DimensionDefinition from flodym and instantiates two definitions with name, letter, and dtype parameters. ```python >>> from flodym import DimensionDefinition >>> time_definition = DimensionDefinition(name='Time', letter='t', dtype=int) >>> region_definition = DimensionDefinition(name='Region', letter='r', dtype=str) ``` -------------------------------- ### ExcelParameterReader(parameter_files, parameter_sheets=None, allow_missing_values=False, allow_extra_values=False, **read_excel_kwargs) Source: https://flodym.readthedocs.io/en/latest/api.data_readers.html Class to read an Excel file to a pandas DataFrame and call flodym.Parameter.from_df(). Expects contiguous data starting in the upper left cell A1. ```APIDOC ## ExcelParameterReader(parameter_files, parameter_sheets=None, allow_missing_values=False, allow_extra_values=False, **read_excel_kwargs) ### Description Reads an excel file to a pandas data frame and calls `flodym.Parameter.from_df()`. Expects contiguous data starting in the upper left cell A1. For further detail on expected format, see `flodym.FlodymArray.from_df()`. ### Parameters - **parameter_files** (dict) - Required - Mapping of parameter names to file paths. Can be the same file for multiple parameters if the sheets are different. Format: {parameter_name: file_path, ...} - **parameter_sheets** (dict) - Optional - Mapping of parameter names to sheet names in the excel file. If None, the first sheet is used. Format: {parameter_name: sheet_name, ...} Defaults to None. - **allow_missing_values** (bool, optional) - Optional - Whether to allow missing values in the DataFrame. This includes both missing rows, and NaN values in the value column. Defaults to False. - **allow_extra_values** (bool, optional) - Optional - Whether to allow extra rows in the DataFrame, i.e. tows with index items not present in the FlodymArray dimension items. Defaults to False. - **read_excel_kwargs** - Optional - Additional keyword arguments passed to pandas.read_excel. Not encouraged to use. ``` -------------------------------- ### MFASystem.from_csv() Source: https://flodym.readthedocs.io/en/latest/api.mfa_system.html Class method to define and set up the MFA system, loading all required data from CSV files. Initialises stocks and flows with zero values. ```APIDOC ## MFASystem.from_csv() ### Description Define and set up the MFA system and load all required data from CSV files. Initialises stocks and flows with all zero values. ### Method N/A (Python class method) ### Endpoint N/A (Python class method) ### Parameters - **definition** (MFADefinition) - Required - The MFA definition object - **dimension_files** (dict) - Required - A dictionary mapping dimension names to CSV files - **parameter_files** (dict) - Required - A dictionary mapping parameter names to CSV files - **allow_missing_parameter_values** (bool) - Optional - Whether to allow missing values in the parameter data (missing rows or empty value cells) - **allow_extra_parameter_values** (bool) - Optional - Whether to allow extra values in the parameter data ### Request Example N/A ### Response #### Success Response (200) Returns an instance of MFASystem. #### Response Example N/A ``` -------------------------------- ### Increase EoL buildings flow and compute scenario Source: https://flodym.readthedocs.io/en/latest/example2.html Creates a deep copy of the mfa_example, increases the 'eol buildings' parameter by 25%, recomputes the system, and calculates the shares of the remelting flow over the 'e' dimension. This represents scenario (b) for reducing copper concentration. ```python mfa_example_b = deepcopy(mfa_example) mfa_example_b.parameters["eol buildings"][...] *= 1.25 mfa_example_b.compute() shares_demolition = mfa_example_b.flows["remelting => sysenv"].get_shares_over(("e")) ``` -------------------------------- ### Initialize DSM with lifetime model class and set parameters later Source: https://flodym.readthedocs.io/en/latest/howto6.html Creates an InflowDrivenDSM by specifying the lifetime model class (NormalLifetime) at initialization, then sets the lifetime parameters (mean and std) and inflow values before computing. The stock values for vehicles are printed after computation. ```python import numpy as np from flodym import InflowDrivenDSM, NormalLifetime, Parameter my_dsm = InflowDrivenDSM( dims=dims, name="in-use-dsm", lifetime_model=NormalLifetime, ) lifetime_mean = Parameter(dims=dims[("p",)], values=np.array([10, 20, 5])) my_dsm.inflow.values[...] = 0.1 my_dsm.lifetime_model.set_prms(mean=lifetime_mean, std=0.3 * lifetime_mean) my_dsm.compute() print("Stock values for Vehicles:", my_dsm.stock["Vehicles"].values) ``` ```output Stock values for Vehicles: [0.0999229 0.19969257 0.29907161 0.39755859 0.49422094 0.58754022 0.67537297 0.75514013 0.82428638 0.88090476 0.92428638] ``` -------------------------------- ### Define flows dictionary with Flow objects Source: https://flodym.readthedocs.io/en/latest/howto5.html Manually initializes the flows dictionary. Flows are normally not initialized with values; values enter through parameters. This manual setup is verbose and repeats information, but there are helper functions to shorten it. ```python flows = { "sysenv => process_a": Flow( name="sysenv => process_a", dims=dims["r", "t"], from_process=processes["sysenv"], to_process=processes["process_a"], ), "process_a => process_b": Flow( name="process_a => process_b", dims=dims, from_process=processes["process_a"], to_process=processes["process_b"], ), "process_a => sysenv": Flow( name="process_a => sysenv", dims=dims, from_process=processes["process_a"], to_process=processes["sysenv"], ), "process_b => sysenv": Flow( name="process_b => sysenv", dims=dims["r", "t"], from_process=processes["process_b"], to_process=processes["sysenv"], ), } ``` -------------------------------- ### Export MFA flows to CSV with flodym Source: https://flodym.readthedocs.io/en/latest/howto8.html Exports MFA flows to CSV files in a specified directory. The flow names are modified to create valid file names. The example prints the list of files and the header of the first file. ```python import os from flodym.export import export_mfa_flows_to_csv, export_mfa_stocks_to_csv export_dir = "output_data/flows" export_mfa_flows_to_csv(mfa, export_directory=export_dir) # print files list print("\nFiles in folder:\n") print("\n".join(os.listdir(export_dir))) # print header of first file print("\nFirst file Header:\n") with open(os.path.join(export_dir, os.listdir(export_dir)[0])) as input_file: head = [next(input_file) for _ in range(5)] print("".join(head)) ``` ```text INFO:root:Data saved in directory output_data/flows ``` ```text Files in folder: demolition__landfills.csv demolition__remelting.csv remelting__slag_piles.csv remelting__sysenv.csv shredder__remelting.csv shredder__sysenv.csv sysenv__demolition.csv sysenv__shredder.csv First file Header: Time,Material,value 1980,Fe,5.700000000000005 1980,Cu,5.292 1980,Mn,0.030000000000000027 1981,Fe,6.080000000000005 ``` -------------------------------- ### Initialize DSM with lifetime model instance and inflow Source: https://flodym.readthedocs.io/en/latest/howto6.html Creates a NormalLifetime instance with parameters and an inflow StockArray, then passes them to the InflowDrivenDSM constructor. Computes the stock and prints the resulting values for vehicles. ```python from flodym import StockArray lifetime_model = NormalLifetime(dims=dims, mean=lifetime_mean, std=0.3 * lifetime_mean) inflow = StockArray(dims=dims, name="in-use-dsm_inflows", values=0.1 * np.ones(dims.shape)) my_dsm = InflowDrivenDSM( dims=dims, name="in-use-dsm", lifetime_model=lifetime_model, inflow=inflow, ) my_dsm.compute() print("Stock values for Vehicles:", my_dsm.stock["Vehicles"].values) ``` ```output Stock values for Vehicles: [0.0999229 0.19969257 0.29907161 0.39755859 0.49422094 0.58754022 0.67537297 0.75514013 0.82428638 0.88090476 0.92428638] ``` -------------------------------- ### MFASystem.from_data_reader() Source: https://flodym.readthedocs.io/en/latest/api.mfa_system.html Class method to define and set up the MFA system, loading all required data from a data reader. Initialises stocks and flows with zero values. ```APIDOC ## MFASystem.from_data_reader() ### Description Define and set up the MFA system and load all required data. Initialises stocks and flows with all zero values. ### Method N/A (Python class method) ### Endpoint N/A (Python class method) ### Parameters - **definition** (MFADefinition) - Required - The MFA definition object - **data_reader** (DataReader) - Required - The data reader object ### Request Example N/A ### Response #### Success Response (200) Returns an instance of MFASystem. #### Response Example N/A ``` -------------------------------- ### Export MFA stocks to CSV with flodym Source: https://flodym.readthedocs.io/en/latest/howto8.html Exports MFA stocks to CSV files, optionally including inflow and outflow data. When enabled, three files are created per stock: inflow, outflow, and stock. The example prints the list of generated files. ```python import os export_dir = "output_data/stocks" export_mfa_stocks_to_csv(mfa, export_directory=export_dir, with_in_and_out=True) # print files list print("\nFiles in folder:\n") print("\n".join(os.listdir(export_dir))) ``` ```text INFO:root:Data saved in directory output_data/stocks ``` ```text Files in folder: landfills_inflow.csv landfills_outflow.csv landfills_stock.csv slag_piles_inflow.csv slag_piles_outflow.csv slag_piles_stock.csv ``` -------------------------------- ### Set values, compute, and check stock balance Source: https://flodym.readthedocs.io/en/latest/howto6.html Sets inflow and outflow values, computes the stock, prints the stock values for Vehicles, and checks the stock balance. The output shows the computed stock values. ```python my_stock.inflow.values[...] = 0.1 my_stock.outflow.values[...] = 0.01 my_stock.compute() print("Stock values for Vehicles:", my_stock.stock["Vehicles"].values) my_stock.check_stock_balance() ``` ```text Stock values for Vehicles: [0.09 0.18 0.27 0.36 0.45 0.54 0.63 0.72 0.81 0.9 0.99] ``` -------------------------------- ### Base class shown_processes Source: https://flodym.readthedocs.io/en/latest/api.export_and_plotting.html Property that returns the shown processes. ```APIDOC ## shown_processes ### Description Property that returns the shown processes. ### Property shown_processes ``` -------------------------------- ### Define processes dictionary with Process objects Source: https://flodym.readthedocs.io/en/latest/howto5.html Defines the process nodes for the MFA system. The first process with ID 0 must be named "sysenv" and represents the system environment; other names cause an error when the MFASystem is created. Keys in the dictionary should match object names for clarity, though this is not required. ```python processes = { "sysenv": Process(name="sysenv", id=0), "process_a": Process(name="process_a", id=1), "process_b": Process(name="process_b", id=2), } ``` -------------------------------- ### Create empty flows and show default names Source: https://flodym.readthedocs.io/en/latest/howto5.html Creates empty flows from processes, flow definitions, and dimensions, then prints the generated flow names. The output shows the default naming convention using process names with an arrow. ```python from flodym import make_empty_flows flows = make_empty_flows(processes=processes, flow_definitions=flow_definitions, dims=dims) print("Flow names:\n ", "\n ".join(flows)) ``` ```text Flow names: sysenv => process_a process_a => process_b process_a => sysenv process_b => sysenv ``` -------------------------------- ### CustomDataReader class definition Source: https://flodym.readthedocs.io/en/latest/example5.html Defines a DataReader subclass that reads dimensions and parameter values from Excel files. The read_dimension method handles region, waste, material, and time dimensions, while read_parameter_values reads parameter data, fills missing values, and filters by dimensions. Used in the following step of the example. ```python class CustomDataReader(DataReader): """The methods `read_dimensions` and `read_parameters` are already defined in the parent DataReader class, and loop over the methods `read_dimension` and `read_parameter_values` that we specify for our usecase here. """ def __init__(self, data_directory, years): self.data_directory = data_directory self.years = years def read_dimension(self, dimension_definition: DimensionDefinition) -> Dimension: if (dim_name := dimension_definition.name) == "region": data = pd.read_excel( join(self.data_directory, "example5_vehicle_lifetime.xlsx"), "Data" ) other_data = pd.read_excel( join(self.data_directory, "example5_vehicle_stock.xlsx"), "Data" ) data = (set(data[dim_name].unique())).intersection(set(other_data[dim_name].unique())) data = list(data) data.sort() elif (dim_name := dimension_definition.name) in ["waste", "material"]: data = pd.read_excel( join(self.data_directory, "example5_eol_recovery_rate.xlsx"), "Data" ) data.columns = [x.lower() for x in data.columns] data = list(data[dim_name].unique()) data.sort() elif dimension_definition.name == "time": data = self.years return Dimension( name=dimension_definition.name, letter=dimension_definition.letter, dtype=dimension_definition.dtype, items=data, ) def read_parameter_values(self, parameter_name: str, dims: DimensionSet) -> Parameter: data = pd.read_excel( join(self.data_directory, f"example5_{parameter_name.replace(' ', '_')}.xlsx"), "Data" ) data = data.fillna(0) if "r" in dims: # remove unwanted regions data = data[data["region"].isin(dims["r"].items)] if parameter_name == "vehicle new registration": # add rows with missing years for year in self.years: if year not in data.columns: data[year] = 0 # remove unncessary columns data = data[["region"] + self.years] else: data.columns = [x.lower() for x in data.columns] # remove unncessary columns data = data[[dim.name for dim in dims] + ["value"]] if parameter_name == "eol recovery rate": # add rows with missing waste /material combinations waste_material_combinations = [ (waste, material) for waste in dims["w"].items for material in dims["m"].items ] data = data.set_index(["waste", "material"]) data = data.reindex(waste_material_combinations).reset_index() data = data.fillna(0) return Parameter.from_df(dims=dims, df=data) ``` -------------------------------- ### Instantiate SimpleMFA with input data Source: https://flodym.readthedocs.io/en/latest/example1.html Creates an instance of the SimpleMFA class using the previously defined dimensions, processes, parameters, flows, and an empty stocks dictionary. The system is defined but not yet computed. ```python mfa_example = SimpleMFA( dims=dimensions, processes=processes, parameters=parameters, flows=flows, stocks={} ) ``` -------------------------------- ### Load data and initialize SimpleMFA from Excel Source: https://flodym.readthedocs.io/en/latest/example2.html Loads dimension and parameter files from Excel and initializes the SimpleMFA system in one step. Requires the mfa_definition, dimension_definitions, and parameter_definitions variables to be defined beforehand. ```python dimension_file = os.path.join("input_data", "example2_dimensions.xlsx") parameter_file = os.path.join("input_data", "example2_parameters.xlsx") mfa_example = SimpleMFA.from_excel( definition=mfa_definition, dimension_files={d.name: dimension_file for d in dimension_definitions}, parameter_files={p.name: parameter_file for p in parameter_definitions}, dimension_sheets={d.name: d.name for d in dimension_definitions}, parameter_sheets={p.name: p.name for p in parameter_definitions}, ) ``` -------------------------------- ### Update shredder yield parameter and compute scenario Source: https://flodym.readthedocs.io/en/latest/example2.html Creates a deep copy of the mfa_example, updates the 'shredder yield' parameter to new values, recomputes the system, and calculates the shares of the remelting flow over the 'e' dimension. This represents scenario (a) for reducing copper concentration. ```python mfa_example_a = deepcopy(mfa_example) mfa_example_a.parameters["shredder yield"].set_values(np.array([0.92, 0.075, 0.92])) mfa_example_a.compute() shares_shredder = mfa_example_a.flows["remelting => sysenv"].get_shares_over(("e")) ``` -------------------------------- ### Create stock definitions and empty stocks Source: https://flodym.readthedocs.io/en/latest/howto6.html Defines stock definitions with a normal lifetime model and creates empty stocks. The stock values are initially zero until computed. ```python from flodym import StockDefinition, make_empty_stocks, make_processes stock_defs = [ StockDefinition( dim_letters=("t", "p"), name="in-use", subclass=InflowDrivenDSM, lifetime_model_class=NormalLifetime, process_name="use_phase", ) ] processes = make_processes(["sysenv", "use_phase"]) stocks = make_empty_stocks(stock_definitions=stock_defs, processes=processes, dims=dims) # still zero, as not yet computed print("Stock values for Vehicles:", stocks["in-use"].stock["Vehicles"].values) ``` -------------------------------- ### Initialize FlodymArray with DimensionSet Source: https://flodym.readthedocs.io/en/latest/howto4.html Creates a DimensionSet with Region, Product, and Time dimensions, then initializes three FlodymArray instances with specified values. The arrays are created with subsets of dimensions using the dims['t', 'p'] syntax. Values are provided as numpy arrays; if omitted, arrays would be zero-initialized. ```python import numpy as np from flodym import Dimension, DimensionSet, FlodymArray # Create a dimension set dims = DimensionSet( dim_list=[ Dimension(name="Region", letter="r", items=["EU", "US", "MEX"]), Dimension(name="Product", letter="p", items=["A", "B"]), Dimension(name="Time", letter="t", items=[2020]), ] ) flow_a = FlodymArray(dims=dims["t", "p"], values=0.2 * np.ones((1, 2))) flow_b = FlodymArray(dims=dims["r", "t"], values=0.1 * np.ones((3, 1))) parameter_a = FlodymArray(dims=dims["r", "p"], values=0.5 * np.ones((3, 2))) ``` -------------------------------- ### Import flodym and useful packages Source: https://flodym.readthedocs.io/en/latest/example3.html Imports standard data science libraries (os, numpy, pandas, plotly.express) and flodym classes (Dimension, DimensionSet, Parameter, StockArray, InflowDrivenDSM) along with NormalLifetime from flodym.lifetime_models. ```python import os import numpy as np import pandas as pd import plotly.express as px from flodym import ( Dimension, DimensionSet, Parameter, StockArray, InflowDrivenDSM, ) from flodym.lifetime_models import NormalLifetime ``` -------------------------------- ### Define dimensions, parameters, and processes Source: https://flodym.readthedocs.io/en/latest/example1.html Defines time and element dimensions, a DimensionSet, parameters D and alpha with linear increasing values, and three processes (sysenv, process 1, process 2). ```python time = Dimension(name="Time", letter="t", items=list(range(1980, 2011))) elements = Dimension( name="Elements", letter="e", items=["single material"], ) dimensions = DimensionSet(dim_list=[time, elements]) parameters = { "D": Parameter(name="inflow", dims=dimensions, values=np.arange(0, 31).reshape(31, 1)), "alpha": Parameter( name="recovery rate", dims=dimensions, values=np.arange(2, 33).reshape(31, 1) / 34, ), } processes = { "sysenv": Process(name="sysenv", id=0), "process 1": Process(name="process 1", id=1), "process 2": Process(name="process 2", id=2), } ``` -------------------------------- ### Define process names Source: https://flodym.readthedocs.io/en/latest/example2.html Lists the process names used in the MFA system. ```python process_names = [ "sysenv", "shredder", "demolition", "remelting", "landfills", "slag piles", ] ``` -------------------------------- ### Pydantic class method for custom initialization Source: https://flodym.readthedocs.io/en/latest/howto1.html Shows a pydantic class method that computes an attribute from input arguments, demonstrating how flodym offers alternative constructors. ```python class Person(BaseModel): initials: str @classmethod def from_name(cls, first_name: str, last_name: str): initials = f"{first_name[0]}.{last_name[0]}." return cls(initials=initials) person_a = Person.from_name(first_name="Adam", last_name="Smith") print(person_a.initials) ``` -------------------------------- ### FlodymArray methods: abs(), apply(), cast_to(), cast_values_to(), copy_dims, cumsum(), from_array(), from_df(), from_dims_superset(), full(), full_like(), get_shares_over(), items_where(), maximum(), minimum(), scalar(), set_values(), set_values_from_df(), sign(), split(), sum_over(), sum_to(), sum_values(), sum_values_over(), sum_values_to(), to_class(), to_df() Source: https://flodym.readthedocs.io/en/latest/api.dimensions.html Methods for creating, transforming, and aggregating FlodymArray objects. ```APIDOC ## FlodymArray methods ### Description Methods for array operations: absolute value, applying functions, casting, copying dimensions, cumulative sum, constructing from arrays/DataFrames, filling, computing shares, filtering, finding maximum/minimum, creating scalar arrays, setting values, sign, splitting, summing over/to dimensions, converting to class/DataFrame. ### Class FlodymArray ### Methods - `abs()`: Returns the absolute value of the array. - `apply()`: Applies a function to the array. - `cast_to()`: Casts the array to a target dimension set. - `cast_values_to()`: Casts the array values to a target dimension set. - `copy_dims`: Property that returns a copy of the dimensions. - `cumsum()`: Computes the cumulative sum along a dimension. - `from_array()`: Creates a FlodymArray from a NumPy array. - `from_df()`: Creates a FlodymArray from a DataFrame. - `from_dims_superset()`: Creates a FlodymArray from a superset of dimensions. - `full()`: Creates a fully populated array. - `full_like()`: Creates an array like another with a fill value. - `get_shares_over()`: Computes shares over a dimension. - `items_where()`: Returns items where a condition is true. - `maximum()`: Returns the element-wise maximum. - `minimum()`: Returns the element-wise minimum. - `scalar()`: Creates a scalar array. - `set_values()`: Sets values in the array. - `set_values_from_df()`: Sets values from a DataFrame. - `sign()`: Returns the sign of the array. - `split()`: Splits the array along a dimension. - `sum_over()`: Sums over a dimension and returns an array. - `sum_to()`: Sums to a target dimension set. - `sum_values()`: Sums all values. - `sum_values_over()`: Sums values over a dimension. - `sum_values_to()`: Sums values to a target dimension set. - `to_class()`: Converts to a specific class. - `to_df()`: Converts to a DataFrame. ``` -------------------------------- ### Import ExcelDimensionReader and define dimensions Source: https://flodym.readthedocs.io/en/latest/howto7.html Imports ExcelDimensionReader and DimensionDefinition, then creates a list of dimension definitions with name, letter, and dtype. ```python from flodym import ExcelDimensionReader, DimensionDefinition dimension_definitions = [ DimensionDefinition(name="Time", letter="t", dtype=int), DimensionDefinition(name="Material", letter="e", dtype=str), ] ``` -------------------------------- ### Normal Python class definition and initialization Source: https://flodym.readthedocs.io/en/latest/howto1.html Shows a standard Python class with an __init__ method and attribute assignment. Used as a baseline for comparing with pydantic. ```python class Person: def __init__(self, name): self.name = name person_a = Person("Adam") print(person_a.name) ``` -------------------------------- ### Compute MFA system and print flow outputs Source: https://flodym.readthedocs.io/en/latest/howto5.html Calls the compute function on the MFA system and prints the resulting flow values as DataFrames. The output shows the computed values for each flow, demonstrating the system's behavior. ```python my_mfa_system.compute() # print example output for f in my_mfa_system.flows.values(): print(f.name, "\n", f.to_df(), "\n") ``` ```text sysenv => process_a value Region Time EU 2020 3.0 US 2020 3.0 MEX 2020 3.0 process_a => process_b value Region Product Time EU A 2020 1.44 B 2020 1.08 US A 2020 1.44 B 2020 1.08 MEX A 2020 1.44 B 2020 1.08 process_a => sysenv value Region Product Time EU A 2020 0.36 B 2020 0.12 US A 2020 0.36 B 2020 0.12 MEX A 2020 0.36 B 2020 0.12 process_b => sysenv value Region Time EU 2020 2.52 US 2020 2.52 MEX 2020 2.52 ``` -------------------------------- ### flodym.make_empty_stocks Source: https://flodym.readthedocs.io/en/latest/api.mfa_system.html Function to initialize empty Stock objects for each of the stocks listed in stock definitions. ```APIDOC ## flodym.make_empty_stocks ### Description Initialise empty Stock objects for each of the stocks listed in stock definitions. ### Method function ### Endpoint flodym.make_empty_stocks ### Parameters - **stock_definitions** (_list_ _[__StockDefinition_ _]_) – Required - **processes** (_dict_ _[__str_ _,__Process_ _]_) – Required - **dims** (_DimensionSet_) – Required ### Return Type dict[str, _Stock_] ``` -------------------------------- ### make_processes Source: https://flodym.readthedocs.io/en/latest/_sources/api.mfa_system.rst.txt Creates a processes object for use in material flow analysis. ```APIDOC ## make_processes ### Description Creates a processes object for use in material flow analysis. ### Function - **Signature**: `flodym.make_processes()` ### Returns - A processes object. ``` -------------------------------- ### make_processes() Source: https://flodym.readthedocs.io/en/latest/api.definitions.html make_processes is a function to create processes. ```APIDOC ## make_processes() ### Description make_processes is a function to create processes. ``` -------------------------------- ### Define parameters for ExcelParameterReader Source: https://flodym.readthedocs.io/en/latest/howto7.html Imports ExcelParameterReader and ParameterDefinition, then creates a list of parameter definitions with names and dimension letters. ```python from flodym import ExcelParameterReader, ParameterDefinition parameter_definitions = [ ParameterDefinition(name="eol machines", dim_letters=("t",)), ParameterDefinition(name="eol buildings", dim_letters=("t",)), ParameterDefinition(name="composition eol machines", dim_letters=("e",)), ParameterDefinition(name="composition eol buildings", dim_letters=("e",)), ParameterDefinition(name="shredder yield", dim_letters=("e",)), ParameterDefinition(name="demolition yield", dim_letters=("e",)), ParameterDefinition(name="remelting yield", dim_letters=("e",)), ] ``` -------------------------------- ### SimpleFlowDrivenStock Source: https://flodym.readthedocs.io/en/latest/api.export_and_plotting.html A stock model driven by simple flows. ```APIDOC ## SimpleFlowDrivenStock ### Description A stock model driven by simple flows. ### Properties - `dims` - The dimensions of the stock. - `inflow` - The inflow array. - `name` - The name of the stock. - `outflow` - The outflow array. - `process` - The process associated with the stock. - `stock` - The stock array. - `time_letter` - The time dimension letter. - `process_id` - The process identifier. - `shape` - The shape of the stock. ### Methods - `check_stock_balance()` - Checks the stock balance. - `compute()` - Computes the stock. - `get_stock_balance()` - Gets the stock balance. - `init_t` - Initializes the time dimension. - `to_stock_type()` - Converts to a specific stock type. - `validate_stock_arrays` - Validates the stock arrays. - `validate_time_first_dim` - Validates that time is the first dimension. ``` -------------------------------- ### Create MFADefinition object Source: https://flodym.readthedocs.io/en/latest/example2.html Combines all definitions into an MFADefinition object. ```python mfa_definition = MFADefinition( dimensions=dimension_definitions, parameters=parameter_definitions, processes=process_names, flows=flow_definitions, stocks=stock_definitions, ) ```