Download this example as a Jupyter notebook or a Python script.


Perform a BoM sustainability summary query#

The following supporting files are required for this example:

Run a BoM sustainability summary query#

First, connect to Granta MI.

[1]:
from ansys.grantami.bomanalytics import Connection
[2]:
server_url = "http://my_grantami_server/mi_servicelayer"
cxn = Connection(server_url).with_credentials("user_name", "password").connect()

Next, create a sustainability summary query. The query accepts a single BoM as argument and an optional configuration for units. If a unit is not specified, the default unit is used. Default units for the analysis are MJ for energy, kg for mass, and km for distance.

[3]:
xml_file_path = "supporting-files/bom-2301-assembly.xml"
with open(xml_file_path) as f:
    bom = f.read()

from ansys.grantami.bomanalytics import queries

MASS_UNIT = "kg"
ENERGY_UNIT = "MJ"
DISTANCE_UNIT = "km"

sustainability_summary_query = (
    queries.BomSustainabilitySummaryQuery()
    .with_bom(bom)
    .with_units(mass=MASS_UNIT, energy=ENERGY_UNIT, distance=DISTANCE_UNIT)
)
[4]:
sustainability_summary = cxn.run(sustainability_summary_query)
sustainability_summary
[4]:
<BomSustainabilitySummaryQueryResult>

The BomSustainabilitySummaryQueryResult object that is returned implements a messages property and properties showing the environmental impact of the items included in the BoM. Log messages are sorted by decreasing severity. The same messages are available in the MI Service Layer log file and are logged using the standard logging module. The next sections show examples of visualizations for the results of the sustainability summary query.

Summary per phase#

The sustainability summary result object contains a phases_summary property. This property summarizes the environmental impact contributions by lifecycle phase: materials, processes, and transport phases. The results for each phase include their absolute and relative contributions to the product as a whole.

[5]:
sustainability_summary.phases_summary
[5]:
[<SustainabilityPhaseSummaryResult('Material', EE%=57.701602167379974, CC%=64.89069113210087)>,
 <SustainabilityPhaseSummaryResult('Processes', EE%=28.998376390298482, CC%=24.13108080560933)>,
 <SustainabilityPhaseSummaryResult('Transport', EE%=13.300021442321539, CC%=10.978228062289809)>]

Use the pandas and plotly libraries to visualize the results. First, the data is translated from the BoM Analytics BomSustainabilitySummaryQueryResult to a pandas Dataframe object.

[6]:
import pandas as pd

EE_HEADER = f"EE [{ENERGY_UNIT}]"
CC_HEADER = f"CC [{MASS_UNIT}]"

phases_df = pd.DataFrame.from_records(
    [
        {
            "Name": item.name,
            "EE%": item.embodied_energy_percentage,
            EE_HEADER: item.embodied_energy.value,
            "CC%": item.climate_change_percentage,
            CC_HEADER: item.climate_change.value,
        }
        for item in sustainability_summary.phases_summary
    ]
)
phases_df
[6]:
Name EE% EE [MJ] CC% CC [kg]
0 Material 57.701602 333.680522 64.890691 32.013029
1 Processes 28.998376 167.693669 24.131081 11.904774
2 Transport 13.300021 76.912216 10.978228 5.415975
[7]:
import plotly.graph_objects as go
from plotly.subplots import make_subplots


def plot_impact(df, title, textinfo="percent+label", hoverinfo="value+name"):
    fig = make_subplots(
        rows=1,
        cols=2,
        specs=[[{"type": "domain"}, {"type": "domain"}]],
        subplot_titles=["Embodied Energy", "Climate Change"],
    )
    fig.add_trace(go.Pie(labels=df["Name"], values=df[EE_HEADER], name=ENERGY_UNIT), 1, 1)
    fig.add_trace(go.Pie(labels=df["Name"], values=df[CC_HEADER], name=MASS_UNIT), 1, 2)
    fig.update_layout(title_text=title, legend=dict(orientation="h"))
    fig.update_traces(textposition="inside", textinfo=textinfo, hoverinfo=hoverinfo)
    fig.show()


plot_impact(phases_df, "BoM sustainability summary - By phase")

Transport phase#

The environmental contribution from the transport phase is summarized in the transport_details property. Results include the individual environmental impact for each transport stage included in the input BoM.

[8]:
sustainability_summary.transport_details
[8]:
[<TransportSummaryResult('Port to airport by truck', EE%=6.849370743919566, CC%=6.4903370873409205)>,
 <TransportSummaryResult('Country 1 to country 2 by air', EE%=90.70442541896631, CC%=91.19168538146589)>,
 <TransportSummaryResult('Airport to distributor by truck', EE%=2.4462038371141306, CC%=2.317977531193186)>]
[9]:
DISTANCE_HEADER = f"Distance [{DISTANCE_UNIT}]"

transport_df = pd.DataFrame.from_records(
    [
        {
            "Name": item.name,
            DISTANCE_HEADER: item.distance.value,
            "EE%": item.embodied_energy_percentage,
            EE_HEADER: item.embodied_energy.value,
            "CC%": item.climate_change_percentage,
            CC_HEADER: item.climate_change.value,
        }
        for item in sustainability_summary.transport_details
    ]
)
transport_df
[9]:
Name Distance [km] EE% EE [MJ] CC% CC [kg]
0 Port to airport by truck 350.0 6.849371 5.268003 6.490337 0.351515
1 Country 1 to country 2 by air 1500.0 90.704425 69.762784 91.191685 4.938918
2 Airport to distributor by truck 125.0 2.446204 1.881430 2.317978 0.125541
[10]:
plot_impact(transport_df, "Transport stages - environmental impact")

In some situations, it might be useful to calculate the environmental impact per distance travelled and add the results as new columns in the dataframe.

[11]:
EE_PER_DISTANCE = f"EE [{ENERGY_UNIT}/{DISTANCE_UNIT}]"
CC_PER_DISTANCE = f"CC [{MASS_UNIT}/{DISTANCE_UNIT}]"
transport_df[EE_PER_DISTANCE] = transport_df.apply(lambda row: row[EE_HEADER] / row[DISTANCE_HEADER], axis=1)
transport_df[CC_PER_DISTANCE] = transport_df.apply(lambda row: row[CC_HEADER] / row[DISTANCE_HEADER], axis=1)
transport_df
[11]:
Name Distance [km] EE% EE [MJ] CC% CC [kg] EE [MJ/km] CC [kg/km]
0 Port to airport by truck 350.0 6.849371 5.268003 6.490337 0.351515 0.015051 0.001004
1 Country 1 to country 2 by air 1500.0 90.704425 69.762784 91.191685 4.938918 0.046509 0.003293
2 Airport to distributor by truck 125.0 2.446204 1.881430 2.317978 0.125541 0.015051 0.001004
[12]:
fig = make_subplots(
    rows=1, cols=2, specs=[[{"type": "domain"}, {"type": "domain"}]], subplot_titles=[EE_PER_DISTANCE, CC_PER_DISTANCE]
)
fig.add_trace(
    go.Pie(labels=transport_df["Name"], values=transport_df[EE_PER_DISTANCE], name=f"{ENERGY_UNIT}/{DISTANCE_UNIT}"),
    1,
    1,
)
fig.add_trace(
    go.Pie(labels=transport_df["Name"], values=transport_df[CC_PER_DISTANCE], name=f"{MASS_UNIT}/{DISTANCE_UNIT}"), 1, 2
)
fig.update_layout(
    title_text="Transport stages impact - Relative to distance travelled",
    legend=dict(orientation="h")
)
fig.update_traces(textposition="inside", textinfo="percent+label", hoverinfo="value+name")
fig.show()

Materials phase#

The environmental contribution from the material phase is summarized in the material_details property. The results are aggregated: each item in material_details represents the total environmental impact of a material summed from all its occurrences in the BoM. Listed materials contribute more than 2% of the total impact for the material phase. Materials that do not contribute at least 2% of the total are aggregated under the Other item.

[13]:
sustainability_summary.material_details
[13]:
[<MaterialSummaryResult('stainless-astm-cn-7ms-cast', EE%=45.864330109954146, CC%=37.36950817938181)>,
 <MaterialSummaryResult('beryllium-beralcast191-cast', EE%=35.276841577106666, CC%=48.52278822564834)>,
 <MaterialSummaryResult('steel-1010-annealed', EE%=18.85882831293918, CC%=14.107703594969825)>]
[14]:
materials_df = pd.DataFrame.from_records(
    [
        {
            "Name": item.identity,
            "EE%": item.embodied_energy_percentage,
            EE_HEADER: item.embodied_energy.value,
            "CC%": item.climate_change_percentage,
            CC_HEADER: item.climate_change.value,
            f"Mass before processing [{MASS_UNIT}]": item.mass_before_processing.value,
            f"Mass after processing [{MASS_UNIT}]": item.mass_after_processing.value,
        }
        for item in sustainability_summary.material_details
    ]
)
materials_df
[14]:
Name EE% EE [MJ] CC% CC [kg] Mass before processing [kg] Mass after processing [kg]
0 stainless-astm-cn-7ms-cast 45.864330 153.040336 37.369508 11.963111 1.54595 1.450
1 beryllium-beralcast191-cast 35.276842 117.711949 48.522788 15.533614 0.02700 0.024
2 steel-1010-annealed 18.858828 62.928237 14.107704 4.516303 2.74574 2.640
[15]:
plot_impact(materials_df, "Aggregated materials impact")

Mass before and mass after secondary processing can help determine if the material mass removed during processing contributes a significant fraction of the impact of the overall material phase.

[16]:
fig = go.Figure(
    data=[
        go.Bar(
            name="Mass before secondary processing",
            x=materials_df["Name"],
            y=materials_df[f"Mass before processing [{MASS_UNIT}]"],
        ),
        go.Bar(
            name="Mass after secondary processing",
            x=materials_df["Name"],
            y=materials_df[f"Mass after processing [{MASS_UNIT}]"],
        ),
    ],
    layout=go.Layout(
        xaxis=go.layout.XAxis(title="Materials"),
        yaxis=go.layout.YAxis(title=f"Mass [{MASS_UNIT}]"),
        legend=dict(orientation="h")
    ),
)
fig.show()

Material processing phase#

The environmental contributions from primary and secondary processing (applied to materials) and the joining and finishing processes (applied to parts) are summarized in the primary_processes_details, secondary_processes_details, and joining_and_finishing_processes_details properties respectively. Each of these properties lists the unique process-material pairs (for primary and secondary processing) or individual processes (for joining and finishing) that contribute at least 5% of the total impact for that category of process. The percentage contributions are relative to the total contribution of all processes from the same category. Processes that do not meet the contribution threshold are aggregated under the Other item, with the material set to None.

Primary processing#

[17]:
sustainability_summary.primary_processes_details
[17]:
[<ProcessSummaryResult(process='Primary processing, Casting', material='stainless-astm-cn-7ms-cast', EE%=48.750183378398724, CC%=49.45426648804626)>,
 <ProcessSummaryResult(process='Primary processing, Casting', material='steel-1010-annealed', EE%=34.35704113152114, CC%=34.962162886767715)>,
 <ProcessSummaryResult(process='Primary processing, Metal extrusion, hot', material='steel-1010-annealed', EE%=16.422416844759894, CC%=15.149665185975097)>,
 <ProcessSummaryResult(process='Other', material='None', EE%=0.47035864532024374, CC%=0.4339054392109292)>]
[18]:
primary_process_df = pd.DataFrame.from_records(
    [
        {
            "Process name": item.process_name,
            "Material name": item.material_identity,
            "EE%": item.embodied_energy_percentage,
            EE_HEADER: item.embodied_energy.value,
            "CC%": item.climate_change_percentage,
            CC_HEADER: item.climate_change.value,
        }
        for item in sustainability_summary.primary_processes_details
    ]
)
primary_process_df
[18]:
Process name Material name EE% EE [MJ] CC% CC [kg]
0 Primary processing, Casting stainless-astm-cn-7ms-cast 48.750183 78.024977 49.454266 5.629548
1 Primary processing, Casting steel-1010-annealed 34.357041 54.988661 34.962163 3.979862
2 Primary processing, Metal extrusion, hot steel-1010-annealed 16.422417 26.284182 15.149665 1.724538
3 Other None 0.470359 0.752812 0.433905 0.049393

Add a Name to each item that represents the process-material pair name.

[19]:
primary_process_df["Name"] = primary_process_df.apply(
    lambda row: f"{row['Process name']} - {row['Material name']}", axis=1
)
plot_impact(
    primary_process_df, "Aggregated primary processes impact", textinfo="percent", hoverinfo="value+name+label"
)

Secondary processing#

[20]:
sustainability_summary.secondary_processes_details
[20]:
[<ProcessSummaryResult(process='Secondary processing, Grinding', material='steel-1010-annealed', EE%=44.943044109852245, CC%=44.943044109852245)>,
 <ProcessSummaryResult(process='Secondary processing, Machining, coarse', material='stainless-astm-cn-7ms-cast', EE%=31.06413363087522, CC%=31.06413363087522)>,
 <ProcessSummaryResult(process='Machining, fine', material='steel-1010-annealed', EE%=15.16283759175015, CC%=15.16283759175015)>,
 <ProcessSummaryResult(process='Other', material='None', EE%=8.829984667522393, CC%=8.829984667522389)>]
[21]:
secondary_process_df = pd.DataFrame.from_records(
    [
        {
            "Process name": item.process_name,
            "Material name": item.material_identity,
            "EE%": item.embodied_energy_percentage,
            EE_HEADER: item.embodied_energy.value,
            "CC%": item.climate_change_percentage,
            CC_HEADER: item.climate_change.value,
        }
        for item in sustainability_summary.secondary_processes_details
    ]
)
secondary_process_df
[21]:
Process name Material name EE% EE [MJ] CC% CC [kg]
0 Secondary processing, Grinding steel-1010-annealed 44.943044 1.986082 44.943044 0.130309
1 Secondary processing, Machining, coarse stainless-astm-cn-7ms-cast 31.064134 1.372758 31.064134 0.090068
2 Machining, fine steel-1010-annealed 15.162838 0.670062 15.162838 0.043964
3 Other None 8.829985 0.390207 8.829985 0.025602

Add a Name to each item that represents the process-material pair name.

[22]:
secondary_process_df["Name"] = secondary_process_df.apply(
    lambda row: f"{row['Process name']} - {row['Material name']}", axis=1
)
plot_impact(
    secondary_process_df, "Aggregated secondary processes impact", textinfo="percent", hoverinfo="value+name+label"
)

Joining and finishing#

Joining and finishing processes apply to parts or assemblies and therefore don’t include a material identity.

[23]:
sustainability_summary.joining_and_finishing_processes_details
[23]:
[<ProcessSummaryResult(process='Joining and finishing, Welding, electric', material='None', EE%=100.0, CC%=100.0)>]
[24]:
joining_and_finishing_processes_df = pd.DataFrame.from_records(
    [
        {
            "Name": item.process_name,
            "EE%": item.embodied_energy_percentage,
            EE_HEADER: item.embodied_energy.value,
            "CC%": item.climate_change_percentage,
            CC_HEADER: item.climate_change.value,
        }
        for item in sustainability_summary.joining_and_finishing_processes_details
    ]
)
joining_and_finishing_processes_df
[24]:
Name EE% EE [MJ] CC% CC [kg]
0 Joining and finishing, Welding, electric 100.0 3.223929 100.0 0.23149
[25]:
plot_impact(
    joining_and_finishing_processes_df, "Aggregated secondary processes impact",
    textinfo="percent", hoverinfo="value+name+label"
)

Hierarchical view#

Finally, aggregate the sustainability summary results into a single dataframe and present it in a hierarchical chart. This highlights the largest contributors at each level. In this example, two levels are defined: first the phase and then the contributors in the phase.

First, rename the processes Other rows, so that they remain distinguishable after all processes have been grouped under a general Processes.

Use assign to add a parent column to each dataframe being concatenated. The join argument value inner specifies that only columns common to all dataframes are kept in the result.

[26]:
primary_process_df.loc[(primary_process_df["Name"] == "Other - None"), "Name"] = "Other primary processes"
secondary_process_df.loc[(secondary_process_df["Name"] == "Other - None"), "Name"] = "Other secondary processes"
joining_and_finishing_processes_df.loc[
    (joining_and_finishing_processes_df["Name"] == "Other - None"), "Name"] = "Other joining and finishing processes"

summary_df = pd.concat(
    [
        phases_df.assign(Parent=""),
        transport_df.assign(Parent="Transport"),
        materials_df.assign(Parent="Material"),
        primary_process_df.assign(Parent="Processes"),
        secondary_process_df.assign(Parent="Processes"),
        joining_and_finishing_processes_df.assign(Parent="Processes"),
    ],
    join="inner",
)
summary_df

# A sunburst chart presents hierarchical data radially.

fig = go.Figure(
    go.Sunburst(
        labels=summary_df["Name"],
        parents=summary_df["Parent"],
        values=summary_df[EE_HEADER],
        branchvalues="total",
    ),
    layout_title_text=f"Embodied Energy [{ENERGY_UNIT}]",
)
fig.show()

# An icicle chart presents hierarchical data as rectangular sectors.

fig = go.Figure(
    go.Icicle(
        labels=summary_df["Name"],
        parents=summary_df["Parent"],
        values=summary_df[EE_HEADER],
        branchvalues="total",
    ),
    layout_title_text=f"Embodied Energy [{ENERGY_UNIT}]",
)
fig.show()