Skip to content

Sweep Sub-Module

t3co.cli.sweep

Command-line entry point that runs a T3CO analysis.

python -m t3co.cli.sweep --analysis-id=<id> loads an analysis from the Config file, computes a Ledger for every selected Vehicle-Scenario pair (optimizing the powertrain first when the analysis asks for it), and writes the results CSV, plus optional charts and a grouped summary.

apply_cli_overrides(config, args, argv=None)

Apply command-line settings that were explicitly given onto a Config.

Only flags present in argv override the Config, in either the --flag value or the --flag=value form, so values loaded from the Config file are kept unless the user passed the matching flag.

Parameters:

Name Type Description Default
config Config

Config to update.

required
args Namespace

Parsed command-line arguments.

required
argv list[str] | None

Raw command-line tokens, used to tell which flags were given. Defaults to None (no overrides).

None

Returns:

Name Type Description
Config Config

The same Config, updated in place.

Source code in src/t3co/cli/sweep.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def apply_cli_overrides(config: Config, args, argv: list[str] | None = None) -> Config:
    """Apply command-line settings that were explicitly given onto a Config.

    Only flags present in ``argv`` override the Config, in either the
    ``--flag value`` or the ``--flag=value`` form, so values loaded from the
    Config file are kept unless the user passed the matching flag.

    Args:
        config (Config): Config to update.
        args (argparse.Namespace): Parsed command-line arguments.
        argv (list[str] | None, optional): Raw command-line tokens, used to
            tell which flags were given. Defaults to None (no overrides).

    Returns:
        Config: The same Config, updated in place.
    """
    argv = [] if argv is None else argv

    override_specs = [
        (("--vehicles",), "vehicle_file", args.vehicles),
        (("--scenarios",), "scenario_file", args.scenarios),
        (("--eng-curves",), "eng_eff_imp_curves", args.eng_curves),
        (("--lw-curves",), "lw_imp_curves", args.lw_curves),
        (("--aero-curves",), "aero_drag_imp_curves", args.aero_curves),
        (("--dst-dir",), "dst_dir", args.dst_dir),
        (("--algorithms", "--algos", "--algo"), "algorithms", args.algorithms),
        (("--x-tol",), "x_tol", args.x_tol),
        (("--f-tol",), "f_tol", args.f_tol),
        (("--n-max-gen",), "n_max_gen", int(args.n_max_gen)),
        (("--pop-size",), "pop_size", int(args.pop_size)),
        (("--nth-gen",), "nth_gen", args.nth_gen),
        (("--n-last",), "n_last", args.n_last),
        # getattr keeps apply_cli_overrides usable with argparse namespaces
        # built before this flag existed.
        (
            ("--n-processes",),
            "n_processes",
            int(getattr(args, "n_processes", config.n_processes)),
        ),
    ]

    for flags, attr_name, value in override_specs:
        if _argument_was_provided(argv, *flags):
            setattr(config, attr_name, value)

    if _argument_was_provided(argv, "--selections"):
        config.selections = _normalize_selections_arg(args.selections)

    if _argument_was_provided(argv, "--drive-cycle"):
        config.drive_cycle = _normalize_drive_cycle_arg(args.drive_cycle)

    if _argument_was_provided(argv, "--skip-all-opt", "--skopt"):
        config.skip_all_opt = True

    if _argument_was_provided(argv, "--summary-group-by"):
        config.summary_group_by = args.summary_group_by

    if _argument_was_provided(argv, "--no-parallel"):
        config.parallel = False

    return config

load_vehicle_scenario_energy(selection, config, vehicle=None, scenario=None, energy=None)

Loads the vehicle, scenario, and energy models based on the selection and config.

Parameters:

Name Type Description Default
selection Union[int, str]

The selection index or string.

required
config Config

The configuration instance.

required

Returns:

Type Description
Tuple[Vehicle, Scenario, Energy]

Tuple[Vehicle, Scenario, Energy]: The vehicle, scenario, and energy models.

Source code in src/t3co/cli/sweep.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def load_vehicle_scenario_energy(
    selection: Union[int, str],
    config: Config,
    vehicle: Vehicle = None,
    scenario: Scenario = None,
    energy: Energy = None,
) -> Tuple[Vehicle, Scenario, Energy]:
    """
    Loads the vehicle, scenario, and energy models based on the selection and config.

    Args:
        selection (Union[int, str]): The selection index or string.
        config (Config): The configuration instance.

    Returns:
        Tuple[Vehicle, Scenario, Energy]: The vehicle, scenario, and energy models.
    """
    # Workaround for config.dc_files disappearing
    if (
        (not hasattr(config, "dc_files") or config.dc_files is None)
        and config.drive_cycle
        and Path(config.drive_cycle).is_dir()
    ):
        config.dc_files = [
            p.absolute() for p in Path(config.drive_cycle).rglob("*.csv")
        ]

    if isinstance(selection, str) and "_" in selection:
        selection, dc_id = map(int, selection.split("_"))

    if scenario:
        input_scenario = scenario
    else:
        input_scenario = Scenario().from_csv(
            selection=selection, scenario_file=config.scenario_file
        )
        input_scenario.override_from_config(config=config)

    if vehicle:
        input_vehicle = vehicle
    else:
        input_vehicle = Vehicle().from_config(selection=selection, config=config)
        input_vehicle.set_veh_kg()

    if config.dc_files:
        input_scenario.drive_cycle = config.dc_files[int(dc_id)]
        if config.energy_file:
            input_scenario.mpgge = config.energy_df.loc[int(dc_id), "mpgge"]
            input_scenario.primary_fuel_range_mi = config.energy_df.loc[
                int(dc_id),
                "primary_fuel_range_mi",
            ]

    if energy:
        input_energy = energy
    elif (
        input_scenario.mpgge
        and input_scenario.primary_fuel_range_mi
        and not input_scenario.cost_toggles.run_fastsim
    ):
        input_energy = Energy(
            mpgge=float(input_scenario.mpgge),
            primary_fuel_range_mi=float(input_scenario.primary_fuel_range_mi),
        )
    else:
        if not input_scenario.cost_toggles.run_fastsim:
            print(
                f"Warning: run_fastsim is False but mpgge ({input_scenario.mpgge}) "
                f"or primary_fuel_range_mi ({input_scenario.primary_fuel_range_mi}) are missing. "
                "Skipping FASTSim run. Energy values will be default (0)."
            )
            input_energy = Energy(mpgge=0.0, primary_fuel_range_mi=0.0)
        else:
            input_energy = Energy()
            input_energy.run_fastsim_model(
                veh_no=selection,
                vehicle_file=config.vehicle_file,
                scenario=input_scenario,
            )

    return input_vehicle, input_scenario, input_energy

generate_ledger(selection, config)

Generates the ledger for the given selection and config.

Parameters:

Name Type Description Default
selection int

The selection index.

required
config Config

The configuration instance.

required

Returns:

Name Type Description
Dict Dict

The ledger as a dictionary.

Source code in src/t3co/cli/sweep.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def generate_ledger(selection: int, config: Config) -> Dict:
    """
    Generates the ledger for the given selection and config.

    Args:
        selection (int): The selection index.
        config (Config): The configuration instance.

    Returns:
        Dict: The ledger as a dictionary.
    """
    input_vehicle, input_scenario, input_energy = load_vehicle_scenario_energy(
        selection=selection, config=config
    )
    print(f"Running Selection: {selection}: {input_scenario.scenario_name}")

    if not config.skip_all_opt and optimization_installed:
        optimized_vehicle, optimized_energy = run_optimization(
            vehicle=input_vehicle, scenario=input_scenario, config=config
        )
    else:
        optimized_vehicle = None
        optimized_energy = None

    return Ledger(
        vehicle=(input_vehicle if not optimized_vehicle else optimized_vehicle),
        scenario=input_scenario,
        energy=(input_energy if optimized_energy is None else optimized_energy),
        config=config,
    ).to_dict(
        include_calcs=config.include_calcs,
        exclude_list_fields=config.exclude_list_fields,
    )

run_optimization(vehicle, scenario, config)

Optimize the powertrain of one Vehicle-Scenario pair.

Each generation's designs are evaluated in a pool of config.n_processes processes when config.parallel is set and this process may start one, and serially otherwise, for example inside a --run-multi worker. Both paths produce identical results.

Parameters:

Name Type Description Default
vehicle Vehicle

Vehicle whose powertrain is sized.

required
scenario Scenario

Scenario supplying knob bounds and constraints.

required
config Config

Analysis configuration, including the algorithm and convergence settings.

required

Returns:

Name Type Description
tuple tuple

(optimized_vehicle, optimized_energy) for the best design found.

Source code in src/t3co/cli/sweep.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def run_optimization(vehicle: Vehicle, scenario: Scenario, config: Config) -> tuple:
    """Optimize the powertrain of one Vehicle-Scenario pair.

    Each generation's designs are evaluated in a pool of
    ``config.n_processes`` processes when ``config.parallel`` is set and this
    process may start one, and serially otherwise, for example inside a
    ``--run-multi`` worker. Both paths produce identical results.

    Args:
        vehicle (Vehicle): Vehicle whose powertrain is sized.
        scenario (Scenario): Scenario supplying knob bounds and constraints.
        config (Config): Analysis configuration, including the algorithm and
            convergence settings.

    Returns:
        tuple: ``(optimized_vehicle, optimized_energy)`` for the best design found.
    """
    pool = None
    runner = None
    if config.parallel and _population_pool_is_available():
        pool = Pool(config.n_processes)
        runner = StarmapParallelization(pool.starmap)

    try:
        problem = VehicleDesignOpt(
            vehicle=vehicle, scenario=scenario, config=config, runner=runner
        )
        algorithm = _build_optimization_algorithm(config)

        res = minimize(
            problem,
            algorithm,
            termination=_build_optimization_termination(config),
            seed=1,
            verbose=True,
        )
    finally:
        if pool:
            pool.close()
            pool.join()

    optimized_vehicle, optimized_energy, _ = problem.evaluate_solution(res.X)
    print(optimized_vehicle)
    return optimized_vehicle, optimized_energy

create_results_filepath(config)

Creates the results file path based on the config.

Parameters:

Name Type Description Default
config Config

The configuration instance.

required

Returns:

Name Type Description
Path Path

The path to the results file.

Source code in src/t3co/cli/sweep.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def create_results_filepath(config: Config) -> Path:
    """
    Creates the results file path based on the config.

    Args:
        config (Config): The configuration instance.

    Returns:
        Path: The path to the results file.
    """
    ts = time.strftime("%Y-%m-%d_%H-%M-%S")
    if config.resfile_suffix:
        result_filename = f"results_{ts}_{str(config.resfile_suffix)}.csv".strip("_")
    else:
        selections_string = (
            str(config.selections)
            .strip("[]")
            .replace(" ", "")
            .replace("'", "")
            .replace(",", "-")
        )
        result_filename = f"results_{ts}_sel_{selections_string[:20]}.csv".strip("_")
    # Create an absolute output directory up front: get_path_object resolves
    # absolute paths strictly (they must exist), while a relative dst_dir is
    # joined onto the resources folder and created below.
    if Path(config.dst_dir).is_absolute():
        Path(config.dst_dir).mkdir(parents=True, exist_ok=True)

    output_path = get_path_object(config.dst_dir) / result_filename
    output_path.parent.mkdir(parents=True, exist_ok=True)

    return output_path

append_results_to_csv(reports_list, output_path, write_header=False)

Appends results to a CSV file incrementally to avoid memory issues.

Parameters:

Name Type Description Default
reports_list List[Dict]

The list of reports to append.

required
output_path Union[str, Path]

The output path for the CSV file.

required
write_header bool

Whether to write the header. Defaults to False.

False
Source code in src/t3co/cli/sweep.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def append_results_to_csv(
    reports_list: List[Dict],
    output_path: Union[str, Path],
    write_header: bool = False,
) -> None:
    """
    Appends results to a CSV file incrementally to avoid memory issues.

    Args:
        reports_list (List[Dict]): The list of reports to append.
        output_path (Union[str, Path]): The output path for the CSV file.
        write_header (bool, optional): Whether to write the header. Defaults to False.
    """
    if not reports_list:
        return

    reports_df = pd.DataFrame(reports_list)
    mode = "w" if write_header else "a"
    reports_df.to_csv(
        output_path,
        mode=mode,
        header=write_header,
        index=False,
        doublequote=True,
        quoting=csv.QUOTE_ALL,
    )

sort_csv_file(input_path, output_path=None, sort_by='selection', chunksize=2000)

Sorts a CSV file by a column using external merge sort to handle large files.

Parameters:

Name Type Description Default
input_path Union[str, Path]

The input CSV file path.

required
output_path Union[str, Path]

The output path. If None, overwrites input.

None
sort_by str

Column name to sort by. Defaults to "selection".

'selection'
chunksize int

Number of rows per chunk. Defaults to 2000.

2000

Returns:

Name Type Description
Path Path

The output file path.

Source code in src/t3co/cli/sweep.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def sort_csv_file(
    input_path: Union[str, Path],
    output_path: Union[str, Path] = None,
    sort_by: str = "selection",
    chunksize: int = 2000,
) -> Path:
    """
    Sorts a CSV file by a column using external merge sort to handle large files.

    Args:
        input_path (Union[str, Path]): The input CSV file path.
        output_path (Union[str, Path], optional): The output path. If None, overwrites input.
        sort_by (str, optional): Column name to sort by. Defaults to "selection".
        chunksize (int, optional): Number of rows per chunk. Defaults to 2000.

    Returns:
        Path: The output file path.
    """
    input_path = Path(input_path)
    if output_path is None:
        output_path = input_path
    else:
        output_path = Path(output_path)

    # Create a temporary directory for sorted chunks
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_dir_path = Path(temp_dir)
        chunk_files = []

        with open(input_path, "r", newline="", encoding="utf-8") as f_in:
            # Use QUOTE_MINIMAL to avoid issues with unquoted booleans (e.g. True)
            # which cause QUOTE_NONNUMERIC to fail
            reader = csv.reader(f_in, doublequote=True, quoting=csv.QUOTE_MINIMAL)
            try:
                header = next(reader)
            except StopIteration:
                return output_path  # Empty file

            try:
                sort_idx = header.index(sort_by)
            except ValueError:
                print(f"Warning: Column '{sort_by}' not found. Skipping sort.")
                if input_path != output_path:
                    shutil.copy(input_path, output_path)
                return output_path

            chunk = []
            chunk_num = 0

            for row in reader:
                chunk.append(row)
                if len(chunk) >= chunksize:
                    # Sort chunk in memory
                    try:
                        chunk.sort(key=lambda x: float(x[sort_idx]))
                    except (ValueError, TypeError):
                        chunk.sort(key=lambda x: str(x[sort_idx]))

                    chunk_filename = temp_dir_path / f"chunk_{chunk_num}.csv"
                    with open(
                        chunk_filename, "w", newline="", encoding="utf-8"
                    ) as f_out:
                        writer = csv.writer(
                            f_out,
                            doublequote=True,
                            quoting=csv.QUOTE_ALL,
                        )
                        writer.writerows(chunk)

                    chunk_files.append(chunk_filename)
                    chunk = []
                    chunk_num += 1

            # Process last chunk
            if chunk:
                try:
                    chunk.sort(key=lambda x: float(x[sort_idx]))
                except (ValueError, TypeError):
                    chunk.sort(key=lambda x: str(x[sort_idx]))

                chunk_filename = temp_dir_path / f"chunk_{chunk_num}.csv"
                with open(chunk_filename, "w", newline="", encoding="utf-8") as f_out:
                    writer = csv.writer(
                        f_out,
                        doublequote=True,
                        quoting=csv.QUOTE_ALL,
                    )
                    writer.writerows(chunk)
                chunk_files.append(chunk_filename)

        # Merge chunks
        if not chunk_files:
            # Only header existed
            with open(output_path, "w", newline="", encoding="utf-8") as f_out:
                writer = csv.writer(
                    f_out,
                    doublequote=True,
                    quoting=csv.QUOTE_ALL,
                )
                writer.writerow(header)
            return output_path

        # Open all chunk files
        files = [open(cf, "r", newline="", encoding="utf-8") for cf in chunk_files]
        readers = [
            csv.reader(f, doublequote=True, quoting=csv.QUOTE_MINIMAL) for f in files
        ]

        # Use heapq.merge
        def key_func(row):
            val = row[sort_idx]
            try:
                return float(val)
            except (ValueError, TypeError):
                return str(val)

        with open(output_path, "w", newline="", encoding="utf-8") as f_out:
            writer = csv.writer(f_out, doublequote=True, quoting=csv.QUOTE_ALL)
            writer.writerow(header)

            for row in heapq.merge(*readers, key=key_func):
                writer.writerow(row)

        # Close files
        for f in files:
            f.close()

    return output_path

    return output_path

export_results_to_csv(reports_list, config, output_path=None, return_filepath=True, return_df=False, sort_values=False)

Exports the results to a CSV file.

Parameters:

Name Type Description Default
reports_list List[Dict]

The list of reports.

required
config Config

The configuration instance.

required
output_path Union[str, Path]

The output path for the CSV file. Defaults to None.

None
return_filepath bool

Whether to return the file path. Defaults to True.

True
return_df bool

Whether to return the DataFrame. Defaults to False.

False
sort_values bool

Whether to sort the values by selection. Defaults to False.

False

Returns:

Type Description
Tuple[Union[Path, None], Union[DataFrame, None]]

Tuple[Union[Path, None], Union[pd.DataFrame, None]]: The output path and DataFrame if specified.

Source code in src/t3co/cli/sweep.py
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
def export_results_to_csv(
    reports_list: List[Dict],
    config: Config,
    output_path: Union[str, Path] = None,
    return_filepath: bool = True,
    return_df: bool = False,
    sort_values: bool = False,
) -> Tuple[Union[Path, None], Union[pd.DataFrame, None]]:
    """
    Exports the results to a CSV file.

    Args:
        reports_list (List[Dict]): The list of reports.
        config (Config): The configuration instance.
        output_path (Union[str, Path], optional): The output path for the CSV file. Defaults to None.
        return_filepath (bool, optional): Whether to return the file path. Defaults to True.
        return_df (bool, optional): Whether to return the DataFrame. Defaults to False.
        sort_values (bool, optional): Whether to sort the values by selection. Defaults to False.

    Returns:
        Tuple[Union[Path, None], Union[pd.DataFrame, None]]: The output path and DataFrame if specified.
    """
    reports_df = pd.DataFrame(reports_list)

    if not output_path:
        output_path = create_results_filepath(config=config)

    if sort_values:
        reports_df = reports_df.sort_values(by="selection").reset_index(drop=True)

    reports_df.to_csv(
        output_path,
        index=False,
        escapechar="\\",
        doublequote=True,
        quoting=csv.QUOTE_NONNUMERIC,
    )

    return (output_path if return_filepath else None), (
        reports_df if return_df else None
    )

summarize_run_results(config, results_path)

Writes a grouped summary of a sweep's results file when config.summary_group_by is set.

Parameters:

Name Type Description Default
config Config

The configuration instance.

required
results_path Union[str, Path]

The results CSV written by the sweep.

required

Returns:

Type Description
Path | None

Path | None: Path of the summary CSV, or None if no summary was requested.

Source code in src/t3co/cli/sweep.py
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def summarize_run_results(config: Config, results_path: Union[str, Path]) -> Path | None:
    """
    Writes a grouped summary of a sweep's results file when config.summary_group_by is set.

    Args:
        config (Config): The configuration instance.
        results_path (Union[str, Path]): The results CSV written by the sweep.

    Returns:
        Path | None: Path of the summary CSV, or None if no summary was requested.
    """
    group_cols = parse_group_by(config.summary_group_by)
    if not group_cols:
        return None
    summary_path = write_results_summary(results_path, group_cols=group_cols)
    print(f"T3CO results summary saved to: {summary_path}")
    return summary_path

save_default_plots(results_csv, backend=DEFAULT_PLOT_BACKEND)

Generates and saves a default set of TCO charts from a results CSV.

Writes figures next to the results file: a TCO cost breakdown, a histogram of the discounted TCO, and - when a fuel-type grouping is available - a violin plot. With the Plotly backend all charts are combined into a single self-contained HTML report; with matplotlib each chart is a separate PNG.

The plotting dependencies are optional; if they are missing (or charting fails) the run is unaffected and a note is printed.

Parameters:

Name Type Description Default
results_csv Union[str, Path]

Path to the T3CO results CSV.

required
backend str

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

DEFAULT_PLOT_BACKEND

Returns:

Type Description
List[Path]

List[Path]: Paths of the saved figure files (empty if plotting was skipped).

Source code in src/t3co/cli/sweep.py
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
def save_default_plots(
    results_csv: Union[str, Path],
    backend: str = DEFAULT_PLOT_BACKEND,
) -> List[Path]:
    """
    Generates and saves a default set of TCO charts from a results CSV.

    Writes figures next to the results file: a TCO cost breakdown, a histogram of
    the discounted TCO, and - when a fuel-type grouping is available - a violin
    plot. With the Plotly backend all charts are combined into a single
    self-contained HTML report; with matplotlib each chart is a separate PNG.

    The plotting dependencies are optional; if they are missing (or charting
    fails) the run is unaffected and a note is printed.

    Args:
        results_csv (Union[str, Path]): Path to the T3CO results CSV.
        backend (str): "plotly" (interactive HTML) or "matplotlib" (static PNG).

    Returns:
        List[Path]: Paths of the saved figure files (empty if plotting was skipped).
    """
    try:
        from t3co.visualize.charts import T3COCharts
    except ImportError as e:
        print(f"Skipping --plot: {e}")
        return []

    results_csv = Path(results_csv)
    try:
        tc = T3COCharts(filename=results_csv, backend=backend)
    except Exception as e:
        print(f"Skipping --plot: could not initialize charts ({type(e).__name__}: {e})")
        return []

    out_dir = results_csv.parent
    stem = results_csv.stem

    group_col = "vehicle_fuel_type" if "vehicle_fuel_type" in tc.group_columns else "None"

    figure_specs = {}
    if tc.backend == "plotly":
        # Interactive HTML fragments with their own dropdowns.
        figure_specs["explorer"] = lambda: tc.interactive_explorer_html()
        # TCO breakdown with a client-side "Group by" dropdown that facets the
        # scenarios into subplots.
        figure_specs["tco_breakdown"] = lambda: tc.grouped_tco_html()
        figure_specs["tco_histogram"] = lambda: tc.interactive_histogram_html(n_bins=10)
        if group_col != "None":
            figure_specs["tco_violin"] = lambda: tc.interactive_violin_html(
                default_x=group_col, default_y="discounted_tco_dol"
            )
    else:
        # One separate stacked bar per scenario (ungrouped); pass grouping
        # columns explicitly to arrange the bars into subplots instead.
        figure_specs["tco_breakdown"] = lambda: tc.generate_tco_plots()
        figure_specs["tco_histogram"] = lambda: tc.generate_histogram(
            hist_col="discounted_tco_dol", n_bins=10
        )
        if group_col != "None":
            figure_specs["tco_violin"] = lambda: tc.generate_violin_plot(
                x_group_col=group_col, y_group_col="discounted_tco_dol"
            )

    # Generate the figures, skipping any individual chart that fails.
    figures = {}
    for name, make_fig in figure_specs.items():
        try:
            figures[name] = make_fig()
        except Exception as e:
            print(f"  could not generate '{name}' plot ({type(e).__name__}: {e})")
    if not figures:
        return []

    # Writing is best-effort too: a full disk or read-only folder must not fail
    # a sweep whose results CSV has already been saved.
    saved = []
    if tc.backend == "plotly":
        # Combine all charts into a single self-contained HTML report.
        out = out_dir / f"{stem}_charts.html"
        try:
            T3COCharts.write_html_report(list(figures.values()), out)
        except Exception as e:
            print(f"  could not write the plot report {out} ({type(e).__name__}: {e})")
            return []
        saved.append(out)
        print(f"Saved plots: {out}")
    else:
        for name, fig in figures.items():
            out = out_dir / f"{stem}_{name}.png"
            try:
                fig.savefig(out, bbox_inches="tight", dpi=120)
            except Exception as e:
                print(f"  could not write '{name}' plot to {out} ({type(e).__name__}: {e})")
                continue
            saved.append(out)
            print(f"Saved plot: {out}")
    return saved

run_t3co(config, save_results=True, plot_backend=None)

Runs the T3CO analysis.

Parameters:

Name Type Description Default
config Config

The configuration instance.

required
save_results bool

Whether to save the results. Defaults to True.

True
plot_backend str

If set ("plotly" or "matplotlib"), generates and saves default TCO charts next to the results CSV. Defaults to None.

None
Source code in src/t3co/cli/sweep.py
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
def run_t3co(
    config: Config, save_results: bool = True, plot_backend: str = None
) -> None:
    """
    Runs the T3CO analysis.

    Args:
        config (Config): The configuration instance.
        save_results (bool, optional): Whether to save the results. Defaults to True.
        plot_backend (str, optional): If set ("plotly" or "matplotlib"), generates and
            saves default TCO charts next to the results CSV. Defaults to None.
    """
    reports_list = []
    error_list = []
    for selection in config.selections_list:
        # try:
        reports_list.append(generate_ledger(selection=selection, config=config))
        # except ValueError:
        #     error_list.append(selection)
        #     continue

    if save_results:
        output_path, reports_df = export_results_to_csv(
            reports_list=reports_list,
            config=config,
            return_filepath=True,
            return_df=True,
        )
        print(reports_df)
        if len(error_list):
            print(f"Selections {error_list} were skipped due to assumptions errors.")
        print(f"T3CO results saved to: {output_path}")
        summarize_run_results(config=config, results_path=output_path)
        if plot_backend and output_path:
            save_default_plots(output_path, backend=plot_backend)