Skip to content

Optimizer

Optimization model construction and solving for temporal LCA-based pathway optimization.

This module creates and solves Pyomo optimization models that minimize environmental impacts over time while meeting demand constraints and respecting process limits.

Key Functions

  • create_model(): Constructs a Pyomo ConcreteModel from optimization inputs
  • solve_model(): Solves the model and returns denormalized results

Scaling Convention

The optimization uses a two-tier scaling system for numerical stability:

Decision Variables (Real Units)

  • var_installation[p, t]: Number of process units installed (dimensionless)
  • var_operation[p, t]: Operation level (dimensionless, 0 to capacity)

Parameters (Scaled Units)

Foreground parameters (scaled by fg_scale):

  • foreground_production[p, r, tau]: kg product per process unit
  • foreground_biosphere[p, e, tau]: kg emission per process unit
  • foreground_technosphere[p, i, tau]: kg intermediate per process unit

Characterization parameters (scaled by cat_scales[category]):

  • characterization[c, e, t]: impact per kg emission
  • category_impact_limit[c]: maximum impact allowed

Module Reference

Optimization model construction and solving for temporal LCA-based pathway optimization.

This module creates and solves Pyomo optimization models that minimize environmental impacts over time while meeting demand constraints and respecting process limits.

Scaling Convention

The optimization uses a two-tier scaling system for numerical stability:

Decision Variables (REAL UNITS)

  • var_installation[p, t]: Number of process units installed (dimensionless)
  • var_operation[p, t]: Operation level (dimensionless, 0 to capacity)

Both decision variables remain in REAL (unscaled) units to: 1. Maintain physical interpretability 2. Allow direct comparison with process limits 3. Ensure correct background inventory calculations

Parameters (SCALED UNITS)

Foreground parameters (scaled by fg_scale): - foreground_production[p, r, tau]: kg product per process unit [SCALED] - foreground_biosphere[p, e, tau]: kg emission per process unit [SCALED] - foreground_technosphere[p, i, tau]: kg intermediate per process unit [SCALED] - internal_demand_technosphere[p, r, tau]: kg product per process unit [SCALED] - demand[r, t]: kg product demanded [SCALED]

Characterization parameters (scaled by cat_scales[category]): - characterization[c, e, t]: impact per kg emission [SCALED] - category_impact_limits[(c, t)]: time-specific maximum impact allowed [SCALED] - cumulative_category_impact_limits[c]: cumulative maximum impact allowed [SCALED]

Unscaled parameters: - background_inventory[bkg, i, e]: kg emission / kg intermediate [UNSCALED] - mapping[bkg, t]: interpolation weights [UNSCALED, dimensionless] - process_deployment_limits_*: deployment limits [UNSCALED, matches var_installation] - process_operation_limits_*: operation limits [UNSCALED, matches var_operation]

Dimensional Consistency

When SCALED parameters are multiplied by REAL decision variables:

scaled_param [kg SCALED/process] × var_real [# processes] = result [kg SCALED]

To convert back to REAL units:

result [kg SCALED] × fg_scale [REAL/SCALED] = result [kg REAL]

Example constraint dimensional analysis:

ProductDemandFulfillment:
    production [kg SCALED/operation] × var_operation [#] = demand [kg SCALED] ✓

OperationLimit (LHS):
    var_operation [#] × production [kg SCALED/operation] × fg_scale = [kg REAL]
OperationLimit (RHS):
    production [kg SCALED/process] × fg_scale × var_installation [#] = [kg REAL]

Classes

Functions

create_model(inputs: OptimizationModelInputs, name: str, objective_category: str, debug_path: str = None) -> pyo.ConcreteModel

Build a Pyomo ConcreteModel for the optimization problem based on the provided inputs.

This function constructs a fully defined Pyomo model using data from a OptimizationModelInputs instance. It uses flexible operation mode where processes can operate between 0 and their maximum installed capacity.

Parameters:

Name Type Description Default
inputs OptimizationModelInputs

Structured input data containing all flows, mappings, and constraints required for model construction.

required
name str

Name of the Pyomo model instance.

required
objective_category str

The category of impact to be minimized in the optimization problem.

required
debug_path str

If provided, specifies the directory path where intermediate model data (such as the LP formulation) or diagnostics may be stored.

None

Returns:

Type Description
ConcreteModel

A fully constructed Pyomo model ready for optimization.

Source code in src/optimex/optimizer.py
  78
  79
  80
  81
  82
  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
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 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
 261
 262
 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
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 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
 358
 359
 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
 392
 393
 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
 420
 421
 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
 552
 553
 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
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 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
 717
 718
 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
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
def create_model(
    inputs: OptimizationModelInputs,
    name: str,
    objective_category: str,
    debug_path: str = None,
) -> pyo.ConcreteModel:
    """
    Build a Pyomo ConcreteModel for the optimization problem based on the provided
    inputs.

    This function constructs a fully defined Pyomo model using data from a `OptimizationModelInputs`
    instance. It uses flexible operation mode where processes can operate between 0 and
    their maximum installed capacity.

    Parameters
    ----------
    inputs : OptimizationModelInputs
        Structured input data containing all flows, mappings, and constraints
        required for model construction.
    name : str
        Name of the Pyomo model instance.
    objective_category : str
        The category of impact to be minimized in the optimization problem.
    debug_path : str, optional
        If provided, specifies the directory path where intermediate model data (such as
        the LP formulation) or diagnostics may be stored.

    Returns
    -------
    pyo.ConcreteModel
        A fully constructed Pyomo model ready for optimization.
    """

    model = pyo.ConcreteModel(name=name)
    model._objective_category = objective_category
    scaled_inputs, scales = inputs.get_scaled_copy()
    model.scales = scales  # Store scales for denormalization later

    logger.info("Creating sets")
    # Sets
    model.PROCESS = pyo.Set(
        doc="Set of processes (or activities), indexed by p",
        initialize=scaled_inputs.PROCESS,
    )
    model.PRODUCT = pyo.Set(
        doc="Set of foreground products, indexed by r",
        initialize=scaled_inputs.PRODUCT,
    )
    model.INTERMEDIATE_FLOW = pyo.Set(
        doc="Set of background products (intermediate flows), indexed by i",
        initialize=scaled_inputs.INTERMEDIATE_FLOW,
    )
    model.ELEMENTARY_FLOW = pyo.Set(
        doc="Set of elementary flows, indexed by e",
        initialize=scaled_inputs.ELEMENTARY_FLOW,
    )
    model.FLOW = pyo.Set(
        initialize=lambda m: m.PRODUCT
        | m.INTERMEDIATE_FLOW
        | m.ELEMENTARY_FLOW,
        doc="Set of all flows, indexed by f",
    )
    model.CATEGORY = pyo.Set(
        doc="Set of impact categories, indexed by c", initialize=scaled_inputs.CATEGORY
    )

    model.BACKGROUND_ID = pyo.Set(
        doc="Set of identifiers of the prospective background databases, indexed by b",
        initialize=scaled_inputs.BACKGROUND_ID,
    )
    model.PROCESS_TIME = pyo.Set(
        doc="Set of process time points, indexed by tau",
        initialize=scaled_inputs.PROCESS_TIME,
    )
    model.SYSTEM_TIME = pyo.Set(
        doc="Set of system time points, indexed by t",
        initialize=scaled_inputs.SYSTEM_TIME,
    )

    # Parameters
    logger.info("Creating parameters")
    model.process_names = pyo.Param(
        model.PROCESS,
        within=pyo.Any,
        doc="Names of the processes",
        default=None,
        initialize=scaled_inputs.process_names,
    )
    model.demand = pyo.Param(
        model.PRODUCT,
        model.SYSTEM_TIME,
        within=pyo.Reals,
        doc="time-explicit external demand vector d",
        default=0,
        initialize=scaled_inputs.demand,
    )
    # Always use 3D base tensors - vintage overrides are applied via sparse lookup
    model.foreground_technosphere = pyo.Param(
        model.PROCESS,
        model.INTERMEDIATE_FLOW,
        model.PROCESS_TIME,
        within=pyo.Reals,
        doc="time-explicit foreground technosphere tensor A (background flows)",
        default=0,
        initialize=scaled_inputs.foreground_technosphere,
    )
    model.foreground_biosphere = pyo.Param(
        model.PROCESS,
        model.ELEMENTARY_FLOW,
        model.PROCESS_TIME,
        within=pyo.Reals,
        doc="time-explicit foreground biosphere tensor B",
        default=0,
        initialize=scaled_inputs.foreground_biosphere,
    )
    model.foreground_production = pyo.Param(
        model.PROCESS,
        model.PRODUCT,
        model.PROCESS_TIME,
        within=pyo.Reals,
        doc="time-explicit foreground production tensor F",
        default=0,
        initialize=scaled_inputs.foreground_production,
    )

    # Store sparse vintage overrides as Python dicts (not Pyomo params)
    # These are looked up at expression construction time
    model._technosphere_vintage_overrides = getattr(
        scaled_inputs, 'foreground_technosphere_vintage_overrides', None
    ) or {}
    model._biosphere_vintage_overrides = getattr(
        scaled_inputs, 'foreground_biosphere_vintage_overrides', None
    ) or {}
    model._production_vintage_overrides = getattr(
        scaled_inputs, 'foreground_production_vintage_overrides', None
    ) or {}

    # Precompute sets of (process, flow) pairs that have overrides for O(1) lookup
    model._technosphere_overrides_index = frozenset(
        (k[0], k[1]) for k in model._technosphere_vintage_overrides
    )
    model._biosphere_overrides_index = frozenset(
        (k[0], k[1]) for k in model._biosphere_vintage_overrides
    )
    model._production_overrides_index = frozenset(
        (k[0], k[1]) for k in model._production_vintage_overrides
    )

    model.internal_demand_technosphere = pyo.Param(
        model.PROCESS,
        model.PRODUCT,
        model.PROCESS_TIME,
        within=pyo.Reals,
        doc="time-explicit internal demand tensor A^{internal}",
        default=0,
        initialize=scaled_inputs.internal_demand_technosphere,
    )
    model.background_inventory = pyo.Param(
        model.BACKGROUND_ID,
        model.INTERMEDIATE_FLOW,
        model.ELEMENTARY_FLOW,
        within=pyo.Reals,
        doc="prospective background inventory tensor G",
        default=0,
        initialize=scaled_inputs.background_inventory,
    )
    model.mapping = pyo.Param(
        model.BACKGROUND_ID,
        model.SYSTEM_TIME,
        within=pyo.Reals,
        doc="time-explicit background mapping tensor M",
        default=0,
        initialize=scaled_inputs.mapping,
    )
    model.characterization = pyo.Param(
        model.CATEGORY,
        model.ELEMENTARY_FLOW,
        model.SYSTEM_TIME,
        within=pyo.Reals,
        doc="time-explicit characterization tensor Q",
        default=0,
        initialize=scaled_inputs.characterization,
    )
    model.operation_flow = pyo.Param(
        model.PROCESS,
        model.FLOW,
        within=pyo.Binary,
        doc="operation flow matrix",
        default=0,
        initialize=scaled_inputs.operation_flow,
    )
    model.process_operation_start = pyo.Param(
        model.PROCESS,
        within=pyo.NonNegativeIntegers,
        doc="start time of process operation",
        default=0,
        initialize={k: v[0] for k, v in scaled_inputs.operation_time_limits.items()},
    )
    model.process_operation_end = pyo.Param(
        model.PROCESS,
        within=pyo.NonNegativeIntegers,
        doc="end time of process operation",
        default=0,
        initialize={k: v[1] for k, v in scaled_inputs.operation_time_limits.items()},
    )
    model.process_deployment_limits_max = pyo.Param(
        model.PROCESS,
        model.SYSTEM_TIME,
        within=pyo.Reals,
        doc="maximum time specific process deployment limit S_max",
        default=scaled_inputs.process_deployment_limits_max_default,
        initialize=(
            scaled_inputs.process_deployment_limits_max
            if scaled_inputs.process_deployment_limits_max is not None
            else {}
        ),
    )
    model.process_deployment_limits_min = pyo.Param(
        model.PROCESS,
        model.SYSTEM_TIME,
        within=pyo.Reals,
        doc="minimum time specific process deployment limit S_min",
        default=scaled_inputs.process_deployment_limits_min_default,
        initialize=(
            scaled_inputs.process_deployment_limits_min
            if scaled_inputs.process_deployment_limits_min is not None
            else {}
        ),
    )
    model.process_operation_limits_max = pyo.Param(
        model.PROCESS,
        model.SYSTEM_TIME,
        within=pyo.Reals,
        doc="maximum time specific process operation limit O_max",
        default=scaled_inputs.process_operation_limits_max_default,
        initialize=(
            scaled_inputs.process_operation_limits_max
            if scaled_inputs.process_operation_limits_max is not None
            else {}
        ),
    )
    model.process_operation_limits_min = pyo.Param(
        model.PROCESS,
        model.SYSTEM_TIME,
        within=pyo.Reals,
        doc="minimum time specific process operation limit O_min",
        default=scaled_inputs.process_operation_limits_min_default,
        initialize=(
            scaled_inputs.process_operation_limits_min
            if scaled_inputs.process_operation_limits_min is not None
            else {}
        ),
    )
    model.cumulative_process_limits_max = pyo.Param(
        model.PROCESS,
        within=pyo.Reals,
        doc="maximum cumulatative process limit S_max,cum",
        default=scaled_inputs.cumulative_process_limits_max_default,
        initialize=(
            scaled_inputs.cumulative_process_limits_max
            if scaled_inputs.cumulative_process_limits_max is not None
            else {}
        ),
    )
    model.cumulative_process_limits_min = pyo.Param(
        model.PROCESS,
        within=pyo.Reals,
        doc="minimum cumulatative process limit S_min,cum",
        default=scaled_inputs.cumulative_process_limits_min_default,
        initialize=(
            scaled_inputs.cumulative_process_limits_min
            if scaled_inputs.cumulative_process_limits_min is not None
            else {}
        ),
    )
    model.process_coupling = pyo.Param(
        model.PROCESS,
        model.PROCESS,
        within=pyo.NonNegativeReals,
        doc="coupling matrix",
        initialize=(
            scaled_inputs.process_coupling
            if scaled_inputs.process_coupling is not None
            else {}
        ),
        default=0,  # Set default coupling value to 0 if not defined
    )

    # Existing (brownfield) capacity: capacity installed before SYSTEM_TIME
    # These contribute to operation capacity but NOT to installation-phase impacts
    model.existing_capacity = pyo.Param(
        model.PROCESS,
        pyo.Any,  # Installation year (can be any year before SYSTEM_TIME)
        within=pyo.NonNegativeReals,
        doc="Existing capacity (process, installation_year) -> amount",
        initialize=(
            scaled_inputs.existing_capacity
            if scaled_inputs.existing_capacity is not None
            else {}
        ),
        default=0,
    )
    # Store the existing capacity dict for iteration
    model._existing_capacity_dict = (
        scaled_inputs.existing_capacity
        if scaled_inputs.existing_capacity is not None
        else {}
    )

    # Build ACTIVE_VINTAGE_TIME index: valid (process, vintage, time) tuples
    # where vintage is active (in operation phase) at time t
    def _build_active_vintage_index(m):
        """
        Build set of valid (process, vintage, time) tuples where vintage is active at time t.

        A vintage v is active at time t if:
        - tau = t - v (process-relative time)
        - op_start <= tau <= op_end (within operation phase)

        This includes both:
        - Greenfield vintages: v in SYSTEM_TIME (new installations)
        - Brownfield vintages: v from existing_capacity (pre-existing installations)
        """
        indices = []
        for p in m.PROCESS:
            op_start = pyo.value(m.process_operation_start[p])
            op_end = pyo.value(m.process_operation_end[p])

            # Greenfield vintages (new installations within system time horizon)
            for v in m.SYSTEM_TIME:
                for t in m.SYSTEM_TIME:
                    tau = t - v  # Process-relative time
                    if v <= t and op_start <= tau <= op_end:
                        indices.append((p, v, t))

            # Brownfield vintages (existing capacity installed before system time)
            for (proc, inst_year), _ in model._existing_capacity_dict.items():
                if proc == p:
                    for t in m.SYSTEM_TIME:
                        tau = t - inst_year
                        if op_start <= tau <= op_end:
                            indices.append((p, inst_year, t))
        return indices

    model.ACTIVE_VINTAGE_TIME = pyo.Set(
        dimen=3,
        initialize=_build_active_vintage_index,
        doc="Set of (process, vintage, time) tuples where vintage is in operation phase at time t"
    )

    # Store category impact limit data for constraint generation
    model._category_impact_limits = (
        scaled_inputs.category_impact_limits
        if scaled_inputs.category_impact_limits is not None
        else {}
    )

    model.cumulative_category_impact_limits = pyo.Param(
        model.CATEGORY,
        within=pyo.Reals,
        doc="cumulative maximum impact limit per category",
        default=float("inf"),
        initialize=(
            scaled_inputs.cumulative_category_impact_limits
            if scaled_inputs.cumulative_category_impact_limits is not None
            else {}
        ),
    )

    # Variables
    logger.info("Creating variables")
    model.var_installation = pyo.Var(
        model.PROCESS,
        model.SYSTEM_TIME,
        within=pyo.NonNegativeReals,
        doc="Installation of the process",
    )

    # Deployment limits
    model.ProcessDeploymentLimitMax = pyo.Constraint(
        model.PROCESS,
        model.SYSTEM_TIME,
        rule=lambda m, p, t: m.var_installation[p, t] <= m.process_deployment_limits_max[p, t],
    )

    model.ProcessDeploymentLimitMin = pyo.Constraint(
        model.PROCESS,
        model.SYSTEM_TIME,
        rule=lambda m, p, t: m.var_installation[p, t] >= m.process_deployment_limits_min[p, t],
    )

    model.CumulativeProcessLimitMax = pyo.Constraint(
        model.PROCESS,
        rule=lambda m, p: sum(m.var_installation[p, t] for t in m.SYSTEM_TIME)
        <= m.cumulative_process_limits_max[p],
    )
    model.CumulativeProcessLimitMin = pyo.Constraint(
        model.PROCESS,
        rule=lambda m, p: sum(m.var_installation[p, t] for t in m.SYSTEM_TIME)
        >= m.cumulative_process_limits_min[p],
    )

    # Process coupling
    def process_coupling_rule(model, p1, p2, t):
        if (
            model.process_coupling[p1, p2] > 0
        ):  # only create constraint for non-zero coupling
            return (
                model.var_installation[p1, t]
                == model.process_coupling[p1, p2] * model.var_installation[p2, t]
            )
        else:
            return pyo.Constraint.Skip

    model.ProcessCouplingConstraint = pyo.Constraint(
        model.PROCESS, model.PROCESS, model.SYSTEM_TIME, rule=process_coupling_rule
    )

    def in_operation_phase(p, tau):
        return model.process_operation_start[p] <= tau <= model.process_operation_end[p]

    # 3D operation variable: (process, vintage, time)
    # Each vintage cohort has its own operation variable for merit-order dispatch
    model.var_operation = pyo.Var(
        model.ACTIVE_VINTAGE_TIME,
        within=pyo.NonNegativeReals,
        doc="Operational activity level per vintage (process, vintage, time)",
    )

    # Operation limits apply to TOTAL operation across all vintages
    def process_operation_limit_max_rule(m, p, t):
        active_vintages = [
            (proc, v, time)
            for (proc, v, time) in m.ACTIVE_VINTAGE_TIME
            if proc == p and time == t
        ]
        if not active_vintages:
            return pyo.Constraint.Skip
        total_op = sum(m.var_operation[proc, v, time] for (proc, v, time) in active_vintages)
        return total_op <= m.process_operation_limits_max[p, t]

    model.ProcessOperationLimitMax = pyo.Constraint(
        model.PROCESS,
        model.SYSTEM_TIME,
        rule=process_operation_limit_max_rule,
    )

    def process_operation_limit_min_rule(m, p, t):
        active_vintages = [
            (proc, v, time)
            for (proc, v, time) in m.ACTIVE_VINTAGE_TIME
            if proc == p and time == t
        ]
        if not active_vintages:
            return pyo.Constraint.Skip
        total_op = sum(m.var_operation[proc, v, time] for (proc, v, time) in active_vintages)
        return total_op >= m.process_operation_limits_min[p, t]

    model.ProcessOperationLimitMin = pyo.Constraint(
        model.PROCESS,
        model.SYSTEM_TIME,
        rule=process_operation_limit_min_rule,
    )

    # Expression builders using sparse vintage override lookup
    # Base tensor is always 3D; overrides are checked first for vintage-specific values
    def scale_tensor_by_installation(tensor: pyo.Param, flow_set: str, overrides: dict, overrides_index: frozenset):
        def expr(m, p, x, t):
            result = 0
            for tau in m.PROCESS_TIME:
                vintage = t - tau
                if (vintage in m.SYSTEM_TIME) and (
                    not in_operation_phase(p, tau) or not m.operation_flow[p, x]
                ):
                    # Check sparse override first, fall back to base 3D tensor
                    key = (p, x, tau, vintage)
                    if key in overrides:
                        flow_value = overrides[key]
                    else:
                        flow_value = tensor[p, x, tau]
                    result += flow_value * m.var_installation[p, vintage]
            return result

        return pyo.Expression(
            model.PROCESS, getattr(model, flow_set), model.SYSTEM_TIME, rule=expr
        )

    def scale_tensor_by_operation(tensor: pyo.Param, flow_set: str, overrides: dict, overrides_index: frozenset):
        """
        Scale tensor by operation, summing flows across active vintages.

        With 3D var_operation[p, v, t], we sum flow contributions from each
        vintage cohort operating at time t.
        """
        def expr(m, p, x, t):
            # Only apply operational scaling to flows marked as operational
            if pyo.value(m.operation_flow[p, x]) == 0:
                return 0

            op_start = pyo.value(m.process_operation_start[p])
            op_end = pyo.value(m.process_operation_end[p])

            total = 0
            # Sum flows across all active vintages at time t
            for (proc, v, time) in m.ACTIVE_VINTAGE_TIME:
                if proc != p or time != t:
                    continue

                # Get vintage-specific flow rate
                if (p, x) in overrides_index:
                    # Vintage-aware: sum flow rates across all operating taus for this vintage
                    flow_rate = sum(
                        overrides.get((p, x, tau, v), tensor[p, x, tau])
                        for tau in m.PROCESS_TIME
                        if op_start <= tau <= op_end
                    )
                else:
                    # No overrides: all vintages have same flow rate
                    flow_rate = sum(
                        tensor[p, x, tau]
                        for tau in m.PROCESS_TIME
                        if op_start <= tau <= op_end
                    )

                total += flow_rate * m.var_operation[p, v, t]

            return total

        return pyo.Expression(
            model.PROCESS, getattr(model, flow_set), model.SYSTEM_TIME, rule=expr
        )

    # Create expressions with sparse vintage override lookup
    model.scaled_technosphere_dependent_on_installation = (
        scale_tensor_by_installation(
            model.foreground_technosphere,
            "INTERMEDIATE_FLOW",
            model._technosphere_vintage_overrides,
            model._technosphere_overrides_index,
        )
    )
    model.scaled_biosphere_dependent_on_installation = scale_tensor_by_installation(
        model.foreground_biosphere,
        "ELEMENTARY_FLOW",
        model._biosphere_vintage_overrides,
        model._biosphere_overrides_index,
    )
    model.scaled_technosphere_dependent_on_operation = scale_tensor_by_operation(
        model.foreground_technosphere,
        "INTERMEDIATE_FLOW",
        model._technosphere_vintage_overrides,
        model._technosphere_overrides_index,
    )
    model.scaled_biosphere_dependent_on_operation = scale_tensor_by_operation(
        model.foreground_biosphere,
        "ELEMENTARY_FLOW",
        model._biosphere_vintage_overrides,
        model._biosphere_overrides_index,
    )
    # Internal demand has no vintage overrides
    _empty_index = frozenset()
    model.scaled_internal_demand_dependent_on_installation = (
        scale_tensor_by_installation(
            model.internal_demand_technosphere, "PRODUCT", {}, _empty_index
        )
    )
    model.scaled_internal_demand_dependent_on_operation = (
        scale_tensor_by_operation(
            model.internal_demand_technosphere, "PRODUCT", {}, _empty_index
        )
    )

    def scaled_inventory_tensor(model, p, e, t):
        """
        Returns a Pyomo expression for the total inventory impact for a given
        process p, elementary flow e, and time step t.
        """

        return sum(
            (
                model.scaled_technosphere_dependent_on_installation[p, i, t]
                + model.scaled_technosphere_dependent_on_operation[p, i, t]
            )
            * sum(
                model.background_inventory[bkg, i, e] * model.mapping[bkg, t]
                for bkg in model.BACKGROUND_ID
            )
            for i in model.INTERMEDIATE_FLOW
        ) + (
            model.scaled_biosphere_dependent_on_installation[p, e, t]
            + model.scaled_biosphere_dependent_on_operation[p, e, t]
        )

    model.scaled_inventory = pyo.Expression(
        model.PROCESS,
        model.ELEMENTARY_FLOW,
        model.SYSTEM_TIME,
        rule=scaled_inventory_tensor,
    )

    # Helper to get production value with sparse override lookup
    def get_production_value(p, r, tau, vintage):
        """Get production value, checking sparse overrides first."""
        key = (p, r, tau, vintage)
        if key in model._production_vintage_overrides:
            return model._production_vintage_overrides[key]
        return model.foreground_production[p, r, tau]

    # O(1) check if production overrides exist for a given process/product
    def has_production_overrides(p, r):
        """Check if any vintage overrides exist for this process/product."""
        return (p, r) in model._production_overrides_index

    def operation_capacity_constraint_rule(model, p, v, t, r):
        """
        Per-vintage capacity constraint: var_operation[p, v, t] ≤ capacity_for_vintage(p, v, t)

        This constraint ensures each vintage's operation level cannot exceed its
        own production capacity.

        For greenfield (v in SYSTEM_TIME): capacity = production_rate * var_installation[p, v]
        For brownfield (v not in SYSTEM_TIME): capacity = production_rate * existing_capacity[p, v]
        """
        fg_scale = model.scales["foreground"]
        op_start = pyo.value(model.process_operation_start[p])
        op_end = pyo.value(model.process_operation_end[p])

        # Calculate production rate for this vintage
        if has_production_overrides(p, r):
            production_per_unit = sum(
                pyo.value(get_production_value(p, r, tau_op, v))
                for tau_op in model.PROCESS_TIME
                if op_start <= tau_op <= op_end
            )
        else:
            production_per_unit = sum(
                model.foreground_production[p, r, tau_op]
                for tau_op in model.PROCESS_TIME
                if op_start <= tau_op <= op_end
            )

        if pyo.value(production_per_unit) == 0:
            return pyo.Constraint.Skip

        # Determine capacity based on vintage type
        if v in model.SYSTEM_TIME:
            # Greenfield: capacity from var_installation
            capacity = production_per_unit * model.var_installation[p, v] * fg_scale
        else:
            # Brownfield: capacity from existing_capacity dict
            existing_cap = model._existing_capacity_dict.get((p, v), 0)
            if existing_cap == 0:
                return pyo.Constraint.Skip
            capacity = pyo.value(production_per_unit) * existing_cap * fg_scale

        return model.var_operation[p, v, t] <= capacity

    # Build constraint over ACTIVE_VINTAGE_TIME × PRODUCT
    def _build_operation_capacity_constraints(m):
        """Generate constraint indices for per-vintage capacity bounds."""
        for (p, v, t) in m.ACTIVE_VINTAGE_TIME:
            for r in m.PRODUCT:
                yield (p, v, t, r)

    model.OperationCapacity = pyo.Constraint(
        _build_operation_capacity_constraints(model),
        rule=lambda m, p, v, t, r: operation_capacity_constraint_rule(m, p, v, t, r),
    )

    def product_demand_fulfillment_rule(model, r, t):
        """
        Demand constraint: total_production == external_demand + internal_consumption

        With 3D var_operation[p, v, t], sum production across all active vintages.
        Each vintage may have different production rates (if overrides exist).
        """
        total_production = 0

        # Sum production across all active vintages at time t
        for (p, v, time) in model.ACTIVE_VINTAGE_TIME:
            if time != t:
                continue

            op_start = pyo.value(model.process_operation_start[p])
            op_end = pyo.value(model.process_operation_end[p])

            # Get production rate for this vintage
            if has_production_overrides(p, r):
                production_rate = sum(
                    pyo.value(get_production_value(p, r, tau_op, v))
                    for tau_op in model.PROCESS_TIME
                    if op_start <= tau_op <= op_end
                )
            else:
                production_rate = sum(
                    model.foreground_production[p, r, tau_op]
                    for tau_op in model.PROCESS_TIME
                    if op_start <= tau_op <= op_end
                )

            total_production += production_rate * model.var_operation[p, v, t]

        external_demand = model.demand[r, t]
        internal_consumption = sum(
            model.scaled_internal_demand_dependent_on_installation[p, r, t]
            + model.scaled_internal_demand_dependent_on_operation[p, r, t]
            for p in model.PROCESS
        )
        return total_production == external_demand + internal_consumption

    model.ProductDemandFulfillment = pyo.Constraint(
        model.PRODUCT, model.SYSTEM_TIME, rule=product_demand_fulfillment_rule
    )

    def category_process_time_specific_impact(model, c, p, t):
        return sum(
            model.characterization[c, e, t]
            * (model.scaled_inventory[p, e, t])  # Total inventory impact
            for e in model.ELEMENTARY_FLOW
        )

    # impact of process p at time t in category c
    model.specific_impact = pyo.Expression(
        model.CATEGORY,
        model.PROCESS,
        model.SYSTEM_TIME,
        rule=category_process_time_specific_impact,
    )

    # Total impact
    def total_impact_in_category(model, c):
        return sum(
            model.specific_impact[c, p, t]
            for p in model.PROCESS
            for t in model.SYSTEM_TIME
        )

    model.total_impact = pyo.Expression(model.CATEGORY, rule=total_impact_in_category)

    # Time-specific impact (impact at a specific time across all processes)
    def time_specific_impact_rule(model, c, t):
        return sum(model.specific_impact[c, p, t] for p in model.PROCESS)

    model.time_specific_impact = pyo.Expression(
        model.CATEGORY, model.SYSTEM_TIME, rule=time_specific_impact_rule
    )

    # Time-specific category impact limits
    def category_impact_limits_rule(model, c, t):
        if (c, t) in model._category_impact_limits:
            return model.time_specific_impact[c, t] <= model._category_impact_limits[(c, t)]
        return pyo.Constraint.Skip

    model.CategoryImpactLimits = pyo.Constraint(
        model.CATEGORY, model.SYSTEM_TIME, rule=category_impact_limits_rule
    )

    # Cumulative category impact limit
    def cumulative_category_impact_limit_rule(model, c):
        return model.total_impact[c] <= model.cumulative_category_impact_limits[c]

    model.CumulativeCategoryImpactLimits = pyo.Constraint(
        model.CATEGORY, rule=cumulative_category_impact_limit_rule
    )

    # Flow limits
    # Store flow limits data for constraint generation
    model._flow_limits_max = (
        scaled_inputs.flow_limits_max
        if scaled_inputs.flow_limits_max is not None
        else {}
    )
    model._flow_limits_min = (
        scaled_inputs.flow_limits_min
        if scaled_inputs.flow_limits_min is not None
        else {}
    )
    model._cumulative_flow_limits_max = (
        scaled_inputs.cumulative_flow_limits_max
        if scaled_inputs.cumulative_flow_limits_max is not None
        else {}
    )
    model._cumulative_flow_limits_min = (
        scaled_inputs.cumulative_flow_limits_min
        if scaled_inputs.cumulative_flow_limits_min is not None
        else {}
    )

    # Expression for total product output at time t (in SCALED units)
    def total_product_flow_rule(model, r, t):
        """
        Calculate total product output at time t, summing across all active vintages.
        Consistent with 3D var_operation[p, v, t].
        """
        total = 0
        for (p, v, time) in model.ACTIVE_VINTAGE_TIME:
            if time != t:
                continue

            op_start = pyo.value(model.process_operation_start[p])
            op_end = pyo.value(model.process_operation_end[p])

            # Get production rate for this vintage
            if has_production_overrides(p, r):
                production_rate = sum(
                    pyo.value(get_production_value(p, r, tau_op, v))
                    for tau_op in model.PROCESS_TIME
                    if op_start <= tau_op <= op_end
                )
            else:
                production_rate = sum(
                    model.foreground_production[p, r, tau_op]
                    for tau_op in model.PROCESS_TIME
                    if op_start <= tau_op <= op_end
                )

            total += production_rate * model.var_operation[p, v, t]
        return total

    model.total_product_flow = pyo.Expression(
        model.PRODUCT, model.SYSTEM_TIME, rule=total_product_flow_rule
    )

    # Expression for total intermediate flow consumed at time t (in SCALED units)
    def total_intermediate_flow_rule(model, i, t):
        return sum(
            model.scaled_technosphere_dependent_on_installation[p, i, t]
            + model.scaled_technosphere_dependent_on_operation[p, i, t]
            for p in model.PROCESS
        )

    model.total_intermediate_flow = pyo.Expression(
        model.INTERMEDIATE_FLOW, model.SYSTEM_TIME, rule=total_intermediate_flow_rule
    )

    # Expression for total elementary flow at time t (in SCALED units)
    # This includes both foreground biosphere flows AND background inventory flows
    # (flows from intermediate flows going through background databases)
    def total_elementary_flow_rule(model, e, t):
        # Foreground biosphere contribution
        foreground_flow = sum(
            model.scaled_biosphere_dependent_on_installation[p, e, t]
            + model.scaled_biosphere_dependent_on_operation[p, e, t]
            for p in model.PROCESS
        )
        # Background inventory contribution (via intermediate flows)
        background_flow = sum(
            (
                model.scaled_technosphere_dependent_on_installation[p, i, t]
                + model.scaled_technosphere_dependent_on_operation[p, i, t]
            )
            * sum(
                model.background_inventory[bkg, i, e] * model.mapping[bkg, t]
                for bkg in model.BACKGROUND_ID
            )
            for i in model.INTERMEDIATE_FLOW
            for p in model.PROCESS
        )
        return foreground_flow + background_flow

    model.total_elementary_flow = pyo.Expression(
        model.ELEMENTARY_FLOW, model.SYSTEM_TIME, rule=total_elementary_flow_rule
    )

    # Helper function to get total flow for any flow type
    def get_total_flow(model, f, t):
        if f in model.PRODUCT:
            return model.total_product_flow[f, t]
        elif f in model.INTERMEDIATE_FLOW:
            return model.total_intermediate_flow[f, t]
        elif f in model.ELEMENTARY_FLOW:
            return model.total_elementary_flow[f, t]
        else:
            return 0

    # Time-specific flow limit constraints (max)
    def flow_limit_max_rule(model, f, t):
        if (f, t) not in model._flow_limits_max:
            return pyo.Constraint.Skip
        fg_scale = model.scales["foreground"]
        limit = model._flow_limits_max[(f, t)]
        total_flow = get_total_flow(model, f, t)
        # total_flow is SCALED, convert limit to scaled units
        return total_flow <= limit / fg_scale

    model.FlowLimitMax = pyo.Constraint(
        model.FLOW, model.SYSTEM_TIME, rule=flow_limit_max_rule
    )

    # Time-specific flow limit constraints (min)
    def flow_limit_min_rule(model, f, t):
        if (f, t) not in model._flow_limits_min:
            return pyo.Constraint.Skip
        fg_scale = model.scales["foreground"]
        limit = model._flow_limits_min[(f, t)]
        total_flow = get_total_flow(model, f, t)
        # total_flow is SCALED, convert limit to scaled units
        return total_flow >= limit / fg_scale

    model.FlowLimitMin = pyo.Constraint(
        model.FLOW, model.SYSTEM_TIME, rule=flow_limit_min_rule
    )

    # Cumulative flow limit constraints (max)
    def cumulative_flow_limit_max_rule(model, f):
        if f not in model._cumulative_flow_limits_max:
            return pyo.Constraint.Skip
        fg_scale = model.scales["foreground"]
        limit = model._cumulative_flow_limits_max[f]
        total_flow = sum(get_total_flow(model, f, t) for t in model.SYSTEM_TIME)
        # total_flow is SCALED, convert limit to scaled units
        return total_flow <= limit / fg_scale

    model.CumulativeFlowLimitMax = pyo.Constraint(
        model.FLOW, rule=cumulative_flow_limit_max_rule
    )

    # Cumulative flow limit constraints (min)
    def cumulative_flow_limit_min_rule(model, f):
        if f not in model._cumulative_flow_limits_min:
            return pyo.Constraint.Skip
        fg_scale = model.scales["foreground"]
        limit = model._cumulative_flow_limits_min[f]
        total_flow = sum(get_total_flow(model, f, t) for t in model.SYSTEM_TIME)
        # total_flow is SCALED, convert limit to scaled units
        return total_flow >= limit / fg_scale

    model.CumulativeFlowLimitMin = pyo.Constraint(
        model.FLOW, rule=cumulative_flow_limit_min_rule
    )

    def objective_function(model):
        return model.total_impact[model._objective_category]

    model.OBJ = pyo.Objective(sense=pyo.minimize, rule=objective_function)

    if debug_path is not None:
        model.write(
            debug_path,
            io_options={"symbolic_solver_labels": True},
            format=ProblemFormat.cpxlp,
        )
    return model

solve_model(model: pyo.ConcreteModel, solver_name: str = 'gurobi', solver_args: Dict[str, Any] = None, solver_options: Dict[str, Any] = None, tee: bool = True, compute_iis: bool = False, **solve_kwargs: Any) -> Tuple[pyo.ConcreteModel, float, SolverResults]

Solve a Pyomo optimization model using a specified solver and denormalize the objective (and optional duals) using stored scales.

Parameters:

Name Type Description Default
model ConcreteModel

The Pyomo model to be solved. Must have attribute scales with keys 'foreground' and 'characterization'.

required
solver_name str

Name of the solver (default: "gurobi").

'gurobi'
solver_args dict

Args to pass to SolverFactory.

None
solver_options dict

Solver-specific options, e.g. timelimit, mipgap.

None
tee bool

If True, prints solver output.

True
compute_iis bool

If True and infeasible, writes IIS to file.

False
**solve_kwargs Any

Additional kwargs for solver.solve().

{}

Returns:

Name Type Description
model ConcreteModel

The solved model (with original scaling preserved).

true_obj float

The denormalized objective value.

results SolverResults

The raw Pyomo solver results object.

Source code in src/optimex/optimizer.py
def solve_model(
    model: pyo.ConcreteModel,
    solver_name: str = "gurobi",
    solver_args: Dict[str, Any] = None,
    solver_options: Dict[str, Any] = None,
    tee: bool = True,
    compute_iis: bool = False,
    **solve_kwargs: Any,
) -> Tuple[pyo.ConcreteModel, float, SolverResults]:
    """
    Solve a Pyomo optimization model using a specified solver and
    denormalize the objective (and optional duals) using stored scales.

    Parameters
    ----------
    model : pyo.ConcreteModel
        The Pyomo model to be solved. Must have attribute `scales` with keys
        'foreground' and 'characterization'.
    solver_name : str, optional
        Name of the solver (default: "gurobi").
    solver_args : dict, optional
        Args to pass to SolverFactory.
    solver_options : dict, optional
        Solver-specific options, e.g. timelimit, mipgap.
    tee : bool, optional
        If True, prints solver output.
    compute_iis : bool, optional
        If True and infeasible, writes IIS to file.
    **solve_kwargs
        Additional kwargs for solver.solve().

    Returns
    -------
    model : pyo.ConcreteModel
        The solved model (with original scaling preserved).
    true_obj : float
        The denormalized objective value.
    results : SolverResults
        The raw Pyomo solver results object.
    """
    # 1) Instantiate solver
    solver_args = solver_args or {}
    solver = pyo.SolverFactory(solver_name, **solver_args)
    if solver_options:
        for opt, val in solver_options.items():
            solver.options[opt] = val

    # 2) Solve model
    results = solver.solve(model, tee=tee, **solve_kwargs)

    termination = results.solver.termination_condition

    # 3) Check termination and handle non-optimal outcomes
    if termination != pyo.TerminationCondition.optimal:
        msg = f"Solver [{solver_name}] termination: {termination}"

        if termination == pyo.TerminationCondition.infeasible:
            if compute_iis:
                try:
                    write_iis(model, iis_file_name="model_iis.ilp", solver=solver)
                    msg += " — IIS written to model_iis.ilp"
                except Exception as e:
                    msg += f" — IIS generation failed: {e}"
            else:
                msg += " — rerun with compute_iis=True to diagnose"
        elif termination == pyo.TerminationCondition.unbounded or (
            termination == pyo.TerminationCondition.other
            and "unbounded" in str(results).lower()
        ):
            msg += (
                " — the model is unbounded. Common cause: installation-dependent"
                " flows (non-operation technosphere/biosphere exchanges) that produce"
                " a net-negative impact allow var_installation to grow without bound."
                " Fix by setting finite process_deployment_limits_max for affected"
                " processes, or ensure installation-dependent flows do not create"
                " a negative-impact incentive for over-installation."
            )
        elif termination == pyo.TerminationCondition.other:
            msg += (
                " — solver returned non-standard termination. Run with tee=True"
                " for detailed solver output. Common causes: unbounded model"
                " (set finite process_deployment_limits_max) or numerical issues."
            )

        # Append full solver details
        msg += f"\n\nFull solver results:\n{results}"

        raise RuntimeError(msg)

    model.solutions.load_from(results)
    logger.info(
        f"Solver [{solver_name}] termination: {termination}"
    )

    # 4) Denormalize objective
    scaled_obj = pyo.value(model.OBJ)
    fg_scale = getattr(model, "scales", {}).get("foreground", 1.0)
    catscales = getattr(model, "scales", {}).get("characterization", {})
    if model._objective_category and model._objective_category in catscales:
        cat_scale = catscales[model._objective_category]
    else:
        cat_scale = 1.0

    true_obj = scaled_obj * fg_scale * cat_scale
    logger.info(f"Objective (scaled): {scaled_obj:.6g}")
    logger.info(f"Objective (real):   {true_obj:.6g}")

    # 5) (Optional) Denormalize duals
    if hasattr(model, "dual"):
        denorm_duals: Dict[Any, float] = {}
        # Example: demand constraint duals
        for idx, con in getattr(model, "demand_constraint", {}).items():
            λ = model.dual.get(con, None)
            if λ is not None:
                denorm_duals[f"demand_{idx}"] = λ * fg_scale
        # Example: impact constraint duals
        for c, con in getattr(model, "category_impact_constraint", {}).items():
            μ = model.dual.get(con, None)
            if μ is not None:
                denorm_duals[f"impact_{c}"] = μ * catscales.get(c, 1.0)
        logger.info(f"Denormalized duals: {denorm_duals}")

    return model, true_obj, results

validate_operation_bounds(model: pyo.ConcreteModel, tolerance: float = 1e-06) -> Dict[str, Any]

Validate that operation levels respect capacity constraints.

This function performs post-solve validation to ensure that var_operation[p, v, t] does not exceed the production capacity for each vintage.

With 3D operation variables: - Greenfield: var_operation[p, v, t] <= production_rate * var_installation[p, v] * fg_scale - Brownfield: var_operation[p, v, t] <= production_rate * existing_capacity[p, v] * fg_scale

Parameters:

Name Type Description Default
model ConcreteModel

A solved Pyomo model.

required
tolerance float

Relative tolerance for validation (default: 1e-6).

1e-06

Returns:

Type Description
dict

Validation results with keys: - "valid": bool, True if all operation levels respect capacity - "violations": list of tuples (process, vintage, time, operation, capacity, violation_type) - "max_violation": float, maximum violation found - "summary": str, human-readable summary

Raises:

Type Description
ValueError

If model is not solved.

Source code in src/optimex/optimizer.py
def validate_operation_bounds(model: pyo.ConcreteModel, tolerance: float = 1e-6) -> Dict[str, Any]:
    """
    Validate that operation levels respect capacity constraints.

    This function performs post-solve validation to ensure that var_operation[p, v, t]
    does not exceed the production capacity for each vintage.

    With 3D operation variables:
    - Greenfield: var_operation[p, v, t] <= production_rate * var_installation[p, v] * fg_scale
    - Brownfield: var_operation[p, v, t] <= production_rate * existing_capacity[p, v] * fg_scale

    Parameters
    ----------
    model : pyo.ConcreteModel
        A solved Pyomo model.
    tolerance : float, optional
        Relative tolerance for validation (default: 1e-6).

    Returns
    -------
    dict
        Validation results with keys:
        - "valid": bool, True if all operation levels respect capacity
        - "violations": list of tuples (process, vintage, time, operation, capacity, violation_type)
        - "max_violation": float, maximum violation found
        - "summary": str, human-readable summary

    Raises
    ------
    ValueError
        If model is not solved.
    """
    if not hasattr(model, "var_operation"):
        raise ValueError("Model must have var_operation")

    violations = []
    max_violation = 0.0
    fg_scale = model.scales["foreground"]

    # Get sparse overrides for production with precomputed index for O(1) lookup
    production_overrides = getattr(model, "_production_vintage_overrides", {}) or {}
    production_overrides_index = getattr(model, "_production_overrides_index", frozenset())
    existing_cap_dict = getattr(model, "_existing_capacity_dict", {})

    def get_prod_value(p, r, tau, vintage):
        """Get production value, checking sparse overrides first."""
        key = (p, r, tau, vintage)
        if key in production_overrides:
            return production_overrides[key]
        return pyo.value(model.foreground_production[p, r, tau])

    def has_prod_overrides(p, r):
        """O(1) check if any vintage overrides exist for this process/product."""
        return (p, r) in production_overrides_index

    # Validate per-vintage operation bounds
    for (p, v, t) in model.ACTIVE_VINTAGE_TIME:
        operation_value = pyo.value(model.var_operation[p, v, t])
        op_start = pyo.value(model.process_operation_start[p])
        op_end = pyo.value(model.process_operation_end[p])

        max_capacity = 0.0
        for r in model.PRODUCT:
            # Get production rate for this vintage
            if has_prod_overrides(p, r):
                production_rate = sum(
                    get_prod_value(p, r, tau_op, v)
                    for tau_op in model.PROCESS_TIME
                    if op_start <= tau_op <= op_end
                )
            else:
                production_rate = sum(
                    pyo.value(model.foreground_production[p, r, tau_op])
                    for tau_op in model.PROCESS_TIME
                    if op_start <= tau_op <= op_end
                )

            if production_rate == 0:
                continue

            # Calculate capacity for this vintage
            if v in model.SYSTEM_TIME:
                # Greenfield: capacity from var_installation
                installed = pyo.value(model.var_installation[p, v])
                capacity = production_rate * installed * fg_scale
            else:
                # Brownfield: capacity from existing_capacity dict
                existing_cap = existing_cap_dict.get((p, v), 0)
                capacity = production_rate * existing_cap * fg_scale

            max_capacity = max(max_capacity, capacity)

        # Check if operation exceeds capacity
        if operation_value < -tolerance:
            violation = abs(operation_value)
            violations.append((p, v, t, operation_value, max_capacity, "negative"))
            max_violation = max(max_violation, violation)
        elif max_capacity > 0 and operation_value > max_capacity * (1.0 + tolerance):
            violation = operation_value - max_capacity
            violations.append((p, v, t, operation_value, max_capacity, "exceeds_capacity"))
            max_violation = max(max_violation, violation)

    # Generate summary
    is_valid = len(violations) == 0
    if is_valid:
        summary = "✓ All per-vintage operation levels respect capacity constraints"
    else:
        summary = (
            f"✗ Found {len(violations)} per-vintage operation bound violations. "
            f"Max violation: {max_violation:.2e}"
        )

    return {
        "valid": is_valid,
        "violations": violations,
        "max_violation": max_violation,
        "summary": summary,
    }

save_solved_model(model: pyo.ConcreteModel, path: Union[str, Path], objective_value: float = None) -> None

Save a solved Pyomo model to disk for later use.

This function saves the model's solution state (variable values, scales, and metadata) to a pickle file, allowing you to reload it later and use it with PostProcessor without re-running the optimization.

Parameters:

Name Type Description Default
model ConcreteModel

The solved Pyomo model to save.

required
path str or Path

File path to save the model. Should have .pkl extension.

required
objective_value float

The denormalized objective value from solve_model(). If provided, it will be stored with the model.

None

Examples:

>>> model, obj, results = solve_model(model)
>>> save_solved_model(model, "solved_model.pkl", objective_value=obj)
Notes

The saved file contains: - The complete Pyomo model with all variable values - Model scales for denormalization - Optionally: objective value

Warning: Only load files from trusted sources.

Source code in src/optimex/optimizer.py
def save_solved_model(
    model: pyo.ConcreteModel,
    path: Union[str, Path],
    objective_value: float = None,
) -> None:
    """
    Save a solved Pyomo model to disk for later use.

    This function saves the model's solution state (variable values, scales,
    and metadata) to a pickle file, allowing you to reload it later and use
    it with PostProcessor without re-running the optimization.

    Parameters
    ----------
    model : pyo.ConcreteModel
        The solved Pyomo model to save.
    path : str or Path
        File path to save the model. Should have .pkl extension.
    objective_value : float, optional
        The denormalized objective value from solve_model().
        If provided, it will be stored with the model.

    Examples
    --------
    >>> model, obj, results = solve_model(model)
    >>> save_solved_model(model, "solved_model.pkl", objective_value=obj)

    Notes
    -----
    The saved file contains:
    - The complete Pyomo model with all variable values
    - Model scales for denormalization
    - Optionally: objective value

    Warning: Only load files from trusted sources.
    """
    path = Path(path)

    # Store additional metadata on the model
    if objective_value is not None:
        model._saved_objective_value = objective_value

    with open(path, "wb") as f:
        dill.dump(model, f, protocol=dill.HIGHEST_PROTOCOL)

    logger.info(f"Saved solved model to: {path}")

load_solved_model(path: Union[str, Path]) -> Tuple[pyo.ConcreteModel, float]

Load a previously saved solved Pyomo model from disk.

This function deserializes a model saved with save_solved_model(), restoring the complete solved state for use with PostProcessor.

Parameters:

Name Type Description Default
path str or Path

File path to the saved model (.pkl file).

required

Returns:

Name Type Description
model ConcreteModel

The loaded solved model, ready for use with PostProcessor.

objective_value float or None

The denormalized objective value, if it was saved.

Examples:

>>> model, obj = load_solved_model("solved_model.pkl")
>>> pp = PostProcessor(model)
>>> pp.plot_impacts()
Notes

Warning: Only load files from trusted sources, as dill can execute arbitrary code during deserialization.

Source code in src/optimex/optimizer.py
def load_solved_model(
    path: Union[str, Path],
) -> Tuple[pyo.ConcreteModel, float]:
    """
    Load a previously saved solved Pyomo model from disk.

    This function deserializes a model saved with save_solved_model(), restoring
    the complete solved state for use with PostProcessor.

    Parameters
    ----------
    path : str or Path
        File path to the saved model (.pkl file).

    Returns
    -------
    model : pyo.ConcreteModel
        The loaded solved model, ready for use with PostProcessor.
    objective_value : float or None
        The denormalized objective value, if it was saved.

    Examples
    --------
    >>> model, obj = load_solved_model("solved_model.pkl")
    >>> pp = PostProcessor(model)
    >>> pp.plot_impacts()

    Notes
    -----
    Warning: Only load files from trusted sources, as dill
    can execute arbitrary code during deserialization.
    """
    path = Path(path)

    with open(path, "rb") as f:
        model = dill.load(f)

    # Retrieve stored metadata
    objective_value = getattr(model, "_saved_objective_value", None)

    logger.info(f"Loaded solved model from: {path}")

    return model, objective_value