Skip to content

Visualization Demo Sub-Module

t3co.demos.visualization_demo

Demo for the T3CO visualization module (:class:t3co.visualize.charts.T3COCharts).

This script builds a small T3CO results DataFrame from the bundled demo inputs (without requiring FASTSim or the optimizer), then renders the three available plots with both backends:

  • backend="matplotlib" -> static PNG files
  • backend="plotly" -> interactive, self-contained HTML files

A backend whose optional dependencies are not installed is skipped with a note; install them with pip install "t3co[viz]".

Run from the repository root::

python src/t3co/demos/visualization_demo.py

Outputs are written to ./results/visualization/ (relative to the working dir).

build_demo_results(max_per_fuel=2, max_total=12)

Builds a small results DataFrame by running a handful of selections that span the available fuel types in the demo scenario file.

Parameters:

Name Type Description Default
max_per_fuel int

Max selections to include per distinct fuel type.

2
max_total int

Overall cap on the number of selections.

12

Returns:

Type Description
DataFrame

pd.DataFrame: Flattened T3CO results, one row per selection.

Source code in src/t3co/demos/visualization_demo.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def build_demo_results(max_per_fuel: int = 2, max_total: int = 12) -> pd.DataFrame:
    """
    Builds a small results DataFrame by running a handful of selections that span
    the available fuel types in the demo scenario file.

    Args:
        max_per_fuel (int): Max selections to include per distinct fuel type.
        max_total (int): Overall cap on the number of selections.

    Returns:
        pd.DataFrame: Flattened T3CO results, one row per selection.
    """
    scenario_df = pd.read_csv(SCENARIO_FILE)

    # Pick a spread of selections across fuel types for a varied breakdown chart.
    selections = []
    for _, group in scenario_df.groupby("fuel_type"):
        selections.extend(group["selection"].head(max_per_fuel).tolist())
    selections = sorted(selections)[:max_total]

    rows = []
    for sel in selections:
        try:
            veh = vehicle.Vehicle().from_csv(selection=sel, vehicle_db_file=VEHICLE_FILE)
            veh.set_veh_kg()
            scen = scenario.Scenario().from_csv(selection=sel, scenario_file=SCENARIO_FILE)
            eng = energy.Energy(mpgge=4.0, primary_fuel_range_mi=200.0)
            row = ledger.Ledger(vehicle=veh, scenario=scen, energy=eng).to_dict(
                flatten=True, exclude_list_fields=True
            )
            rows.append(row)
        except Exception as e:  # keep the demo resilient to any single bad selection
            print(f"  skipped selection {sel}: {type(e).__name__}: {e}")

    if not rows:
        raise RuntimeError("Could not build any demo results rows.")
    print(f"Built results for selections: {selections}")
    return pd.DataFrame(rows)

render(results_df, backend)

Renders the three plots for one backend and writes them to OUT_DIR.

Parameters:

Name Type Description Default
results_df DataFrame

The T3CO results to plot.

required
backend str

"matplotlib" (static PNG) or "plotly" (interactive HTML).

required
Source code in src/t3co/demos/visualization_demo.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def render(results_df: pd.DataFrame, backend: str) -> None:
    """
    Renders the three plots for one backend and writes them to ``OUT_DIR``.

    Args:
        results_df (pd.DataFrame): The T3CO results to plot.
        backend (str): "matplotlib" (static PNG) or "plotly" (interactive HTML).
    """
    # T3COCharts imports the plotting libraries lazily, so a missing backend only
    # surfaces while rendering; skip that backend instead of crashing.
    try:
        _render(T3COCharts(results_df=results_df, backend=backend), backend)
    except ImportError as e:
        print(f"\n[{backend}] skipped - {e}")