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, as well as 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 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 on in the MI Service Layer log file, and are logged via 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%=31.56945748870393, CC%=40.05506081817221)>,
 <SustainabilityPhaseSummaryResult('Processes', EE%=59.95417367143312, CC%=52.40516764294889)>,
 <SustainabilityPhaseSummaryResult('Transport', EE%=8.476368839862962, CC%=7.539771538878892)>]

Use the pandas and plotly libraries to visualize the results. The data will first be translated from the BoM Analytics BomSustainabilitySummaryQueryResult to a pandas Dataframe

[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 31.569457 286.103262 40.055061 28.539686
1 Processes 59.954174 543.344296 52.405168 37.339278
2 Transport 8.476369 76.818449 7.539772 5.372173
[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")

The 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.809879274093459, CC%=6.440242424179394)>,
 <TransportSummaryResult('Country 1 to country 2 by air', EE%=90.75802098515888, CC%=91.25967099575654)>,
 <TransportSummaryResult('Airport to distributor by truck', EE%=2.432099740747663, CC%=2.3000865800640695)>]
[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.809879 5.231244 6.440242 0.345981
1 Country 1 to country 2 by air 1500.0 90.758021 69.718904 91.259671 4.902627
2 Airport to distributor by truck 125.0 2.432100 1.868301 2.300087 0.123565
[10]:
plot_impact(transport_df, "Transport stages - environmental impact")

In some situations, it may 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.809879 5.231244 6.440242 0.345981 0.014946 0.000989
1 Country 1 to country 2 by air 1500.0 90.758021 69.718904 91.259671 4.902627 0.046479 0.003268
2 Airport to distributor by truck 125.0 2.432100 1.868301 2.300087 0.123565 0.014946 0.000989
[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()

The 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('beryllium-beralcast191-cast', EE%=41.04868278333434, CC%=54.32870571288889)>,
 <MaterialSummaryResult('stainless-astm-cn-7ms-cast', EE%=40.06955268607085, CC%=31.595335871309544)>,
 <MaterialSummaryResult('steel-1010-annealed', EE%=18.881764530594808, CC%=14.075958415801562)>]
[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 beryllium-beralcast191-cast 41.048683 117.441620 54.328706 15.505242 0.02700 0.024
1 stainless-astm-cn-7ms-cast 40.069553 114.640297 31.595336 9.017210 1.54595 1.450
2 steel-1010-annealed 18.881765 54.021344 14.075958 4.017234 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()

The material processing phase#

The environmental contributions from primary and secondary processing (applied to materials), and 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%=55.92433171310843, CC%=56.01916015300561)>,
 <ProcessSummaryResult(process='Primary processing, Casting', material='steel-1010-annealed', EE%=39.09683391559776, CC%=39.276605734704205)>,
 <ProcessSummaryResult(process='Other', material='None', EE%=4.97883437129381, CC%=4.704234112290182)>]
[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 55.924332 299.624263 56.019160 20.629294
1 Primary processing, Casting steel-1010-annealed 39.096834 209.468038 39.276606 14.463777
2 Other None 4.978834 26.674965 4.704234 1.732354

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.064133630875222)>,
 <ProcessSummaryResult(process='Machining, fine', material='steel-1010-annealed', EE%=15.162837591750153, CC%=15.16283759175015)>,
 <ProcessSummaryResult(process='Other', material='None', EE%=8.82998466752239, CC%=8.829984667522393)>]
[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.959488 44.943044 0.127255
1 Secondary processing, Machining, coarse stainless-astm-cn-7ms-cast 31.064134 1.354376 31.064134 0.087957
2 Machining, fine steel-1010-annealed 15.162838 0.661090 15.162838 0.042933
3 Other None 8.829985 0.384982 8.829985 0.025002

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.217094 100.0 0.230705
[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()