forked from NatLabRockies/H2Integrate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathh2integrate_model.py
More file actions
1555 lines (1354 loc) · 72.9 KB
/
h2integrate_model.py
File metadata and controls
1555 lines (1354 loc) · 72.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
import importlib.util
import numpy as np
import networkx as nx
import openmdao.api as om
import matplotlib.pyplot as plt
from h2integrate.core.sites import SiteLocationComponent
from h2integrate.core.utilities import create_xdsm_from_config
from h2integrate.core.file_utils import get_path, find_file, load_yaml
from h2integrate.finances.finances import AdjustedCapexOpexComp
from h2integrate.core.supported_models import supported_models
from h2integrate.core.inputs.validation import load_tech_yaml, load_plant_yaml, load_driver_yaml
from h2integrate.core.pose_optimization import PoseOptimization
from h2integrate.postprocess.sql_to_csv import convert_sql_to_csv_summary
from h2integrate.core.commodity_stream_definitions import (
multivariable_streams,
is_electricity_producer,
)
from h2integrate.control.control_strategies.pyomo_controller_baseclass import (
PyomoControllerBaseClass,
)
try:
import pyxdsm
except ImportError:
pyxdsm = None
class H2IntegrateModel:
def __init__(self, config_input):
# read in config file; it's a yaml dict that looks like this:
self.load_config(config_input)
# load in supported models
self.supported_models = supported_models.copy()
# load custom models
self.collect_custom_models()
# Check if create_om_reports is specified in driver config
create_om_reports = self.driver_config.get("general", {}).get("create_om_reports", True)
self.prob = om.Problem(reports=create_om_reports)
self.model = self.prob.model
# track if setup has been called via boolean
self.setup_has_been_called = False
# initialize recorder_path attribute
self.recorder_path = None
# create site-level model
# this is an OpenMDAO group that contains all the site information
self.create_site_model()
# create plant-level model
# this is an OpenMDAO group that contains all the technologies
# it will need plant_config but not driver or tech config
self.create_plant_model()
# create technology models
# these are OpenMDAO groups that contain all the components for each technology
# they will need tech_config but not driver or plant config
self.create_technology_models()
self.create_finance_model()
# connect technologies
# technologies are connected within the `technology_interconnections` section of the
# plant config
self.connect_technologies()
# create driver model
# might be an analysis or optimization
self.create_driver_model()
def _load_component_config(self, config_key, config_value, config_path, validator_func):
"""Helper method to load and validate a component configuration.
Args:
config_key (str): Key name for the configuration (e.g., "driver_config")
config_value (dict | str): Configuration value from main config
config_path (Path | None): Path to main config file (None if dict)
validator_func (callable): Validation function to apply
Returns:
tuple: (validated_config, config_file_path, parent_path)
- validated_config: Validated configuration dictionary
- config_file_path: Path to config file (None if dict)
- parent_path: Parent directory of config file (None if dict)
"""
if isinstance(config_value, dict):
# Config provided as embedded dictionary
return validator_func(config_value), None, None
else:
# Config provided as filepath - resolve location
if config_path is None:
file_path = get_path(config_value)
else:
file_path = find_file(config_value, config_path.parent)
# Store parent directory for resolving custom model paths later
parent_path = file_path.parent
return validator_func(file_path), file_path, parent_path
def load_config(self, config_input):
"""Load and validate configuration files for the H2I model.
This method loads the main configuration and the component configuration files
(driver, technology, and plant). Each configuration can be provided either as
a dictionary or as a file path. When file paths are provided, the method
resolves them using multiple search strategies.
Args:
config_input (dict | str | Path): Main configuration containing references to
driver, technology, and plant configurations. This can be:
- A dictionary containing the configuration data directly.
- A string or Path pointing to a YAML file containing the configuration.
Behavior:
- If ``config_input`` is a dict, uses it directly as the main configuration.
- If ``config_input`` is a path, uses ``get_path()`` to resolve and load the YAML
file from multiple search locations (absolute path, relative to CWD, relative to
the H2Integrate package).
- For component configs provided as dicts, validates them directly using
``load_driver_yaml``, ``load_tech_yaml``, and ``load_plant_yaml``.
- For component configs provided as paths and a file-based main config, uses
``find_file()`` to search relative to the main config directory first, then
falls back to other search locations (CWD, H2Integrate package, glob patterns).
- For component configs provided as paths and a dict-based main config, uses
``get_path()`` with standard search locations (absolute, CWD, H2Integrate package).
Sets:
self.name (str): Name of the system from main config.
self.system_summary (str): Summary description from main config.
self.driver_config (dict): Validated driver configuration.
self.technology_config (dict): Validated technology configuration.
self.plant_config (dict): Validated plant configuration.
self.driver_config_path (Path | None): Path to driver config file (None if dict).
self.tech_config_path (Path | None): Path to technology config file (None if dict).
self.plant_config_path (Path | None): Path to plant config file (None if dict).
self.tech_parent_path (Path | None): Parent directory of technology config file.
self.plant_parent_path (Path | None): Parent directory of plant config file.
Note:
The parent path attributes (``tech_parent_path``, ``plant_parent_path``) are used
later to resolve relative paths to custom models and other referenced files within
the technology and plant configurations.
Example:
>>> # Using filepaths
>>> model = H2IntegrateModel("main_config.yaml")
>>> # Using mixed dict and filepaths
>>> config = {
... "name": "my_system",
... "driver_config": "driver.yaml",
... "technology_config": {"technologies": {...}},
... "plant_config": "plant.yaml",
... }
>>> model = H2IntegrateModel(config)
"""
# Load main configuration
if isinstance(config_input, dict):
config = config_input
config_path = None
else:
config_path = get_path(config_input)
config = load_yaml(config_path)
self.name = config.get("name")
self.system_summary = config.get("system_summary")
# Load and validate each component configuration using the helper method
self.driver_config, self.driver_config_path, _ = self._load_component_config(
"driver_config", config.get("driver_config"), config_path, load_driver_yaml
)
self.technology_config, self.tech_config_path, self.tech_parent_path = (
self._load_component_config(
"technology_config", config.get("technology_config"), config_path, load_tech_yaml
)
)
self.plant_config, self.plant_config_path, self.plant_parent_path = (
self._load_component_config(
"plant_config", config.get("plant_config"), config_path, load_plant_yaml
)
)
for name, vals in self.technology_config["technologies"].items():
if "control_strategy" in vals:
controller_model_name = vals["control_strategy"]["model"]
controller_cls = supported_models.get(controller_model_name)
if controller_cls is not None and issubclass(
controller_cls, PyomoControllerBaseClass
):
model_inputs = self.technology_config["technologies"][name]["model_inputs"]
if (
"control_parameters" not in model_inputs
or model_inputs["control_parameters"] is None
):
model_inputs["control_parameters"] = {"tech_name": name}
else:
model_inputs["control_parameters"]["tech_name"] = name
def create_custom_models(self, model_config, config_parent_path, model_types, prefix=""):
"""This method loads custom models from the specified directory and adds them to the
supported models dictionary.
Args:
model_config (dict): dictionary containing models, such as
``technology_config["technologies"]``.
config_parent_path (Path): parent path of the input file that ``model_config`` comes
from. Should either be ``plant_config_path.parent`` or
``tech_config_path.parent``.
model_types (list[str]): list of key names to search for in
``model_config.values()``. Should be
``["performance_model", "cost_model", "financial_model"]`` if ``model_config``
is ``technology_config["technologies"]``.
prefix (str, optional): Prefix of ``model_class_name``, ``model_location`` and
``model``. Defaults to "". Should be ``"finance_"`` if looking for custom
system finance models.
"""
included_custom_models = {}
for name, config in model_config.items():
for model_type in model_types:
if model_type in config:
model_name = config[model_type].get(f"{prefix}model")
# Don't create new custom model or raise an error if the current custom model
# has already been processed. This can happen if there are 2 or more instances
# of the same custom model. Also check that all instances of the same custom
# model tech name use the same class definition.
if model_name in included_custom_models:
model_class_name = config[model_type].get(f"{prefix}model_class_name")
if (
model_class_name
!= included_custom_models[model_name]["model_class_name"]
):
raise (
ValueError(
"User has specified two custom models using the same model"
"name ({model_name}), but with different model classes. "
"Technologies defined with different classes must have "
"different technology names."
)
)
else:
continue
if (model_name not in self.supported_models) and (model_name is not None):
model_class_name = config[model_type].get(f"{prefix}model_class_name")
model_location = config[model_type].get(f"{prefix}model_location")
if not model_class_name or not model_location:
raise ValueError(
f"Custom {model_type} for {name} must specify "
f"'{prefix}model_class_name' and '{prefix}model_location'."
)
# Resolve the full path of the model location
if config_parent_path is not None:
model_path = find_file(model_location, config_parent_path)
else:
model_path = find_file(model_location)
if not model_path.exists():
raise FileNotFoundError(
f"Custom model location {model_path} does not exist."
)
# Dynamically import the custom model class
spec = importlib.util.spec_from_file_location(model_class_name, model_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
custom_model_class = getattr(module, model_class_name)
# Add the custom model to the supported models dictionary
self.supported_models[model_name] = custom_model_class
# Add the custom model to custom models dictionary
included_custom_models[model_name] = {
"model_class_name": model_class_name,
}
else:
if (
config[model_type].get(f"{prefix}model_class_name") is not None
or config[model_type].get(f"{prefix}model_location") is not None
):
msg = (
f"Custom {prefix}model_class_name or {prefix}model_location "
f"specified for '{model_name}', "
f"but '{model_name}' is a built-in H2Integrate "
"model. Using built-in model instead is not allowed. "
f"If you want to use a custom model, please rename it "
"in your configuration."
)
raise ValueError(msg)
def collect_custom_models(self):
"""Collect custom models from the technology configuration and
system finance models found in the plant configuration.
"""
# check for custom technology models
self.create_custom_models(
self.technology_config["technologies"],
self.tech_parent_path,
["performance_model", "cost_model", "finance_model"],
)
# check for custom finance models
if "finance_parameters" in self.plant_config:
finance_groups = self.plant_config["finance_parameters"]["finance_groups"]
# check for single custom finance models
if "model_inputs" in finance_groups:
self.create_custom_models(
self.plant_config,
self.plant_parent_path,
["finance_groups"],
prefix="finance_",
)
# check for named finance models
if any("model_inputs" in v for k, v in finance_groups.items()):
finance_model_names = [k for k, v in finance_groups.items() if "model_inputs" in v]
finance_groups_config = {"finance_groups": finance_groups}
self.create_custom_models(
finance_groups_config,
self.plant_parent_path,
finance_model_names,
prefix="finance_",
)
def create_site_model(self):
"""
Create and configure site component(s) for the system.
This method initializes a site group for each site provided in
``self.plant_config["sites"]``.
This method creates an OpenMDAO Group for each site that contains the location definition
and resources models (if provided in the configuration) for that site.
"""
# Loop through each site defined in the plant config
# If no sites defined in plant_config, nothing to do
if "sites" not in self.plant_config or not self.plant_config["sites"]:
return
for site_name, site_info in self.plant_config["sites"].items():
# Reorganize the plant config to be formatted as expected by the
# resource models
plant_config_reorg = {
"site": site_info,
"plant": self.plant_config["plant"],
}
# Create the site group and resource models
site_group = self.create_site_group(plant_config_reorg, site_info)
# Add the site group to the system model
self.model.add_subsystem(site_name, site_group)
def create_site_group(self, plant_config_dict: dict, site_config: dict):
"""
Create and configure a site Group for the input site configuration.
Args:
plant_config_dict (dict): The plant config dictionary formatted for the resource models
site_config (dict): Information that defines each site, such as latitude,
longitude, and resource models.
Returns:
om.Group: OpenMDAO group for a site
"""
# Initialize the site group
site_group = om.Group()
# Create a site location component (defines latitude, longitude, etc)
site_inputs = {k: v for k, v in site_config.items() if k != "resources"}
site_component = SiteLocationComponent(site_inputs)
site_group.add_subsystem("site_component", site_component, promotes=["*"])
# Add the site resource components
if "resources" in site_config:
for resource_name, resource_config in site_config["resources"].items():
resource_model = resource_config.get("resource_model")
resource_inputs = resource_config.get("resource_parameters")
resource_class = self.supported_models.get(resource_model)
if resource_class:
resource_component = resource_class(
plant_config=plant_config_dict,
resource_config=resource_inputs,
driver_config=self.driver_config,
)
site_group.add_subsystem(
resource_name, resource_component, promotes_inputs=["latitude", "longitude"]
)
return site_group
def create_plant_model(self):
"""
Create the plant-level model.
This method creates an OpenMDAO group that contains all the technologies.
It uses the plant configuration but not the driver or technology configuration.
Information at this level might be used by any technology and info stored here is
the same for each technology. This includes site information, project parameters,
control strategy, and finance parameters.
"""
plant_group = om.Group()
# Create the plant model group and add components
self.plant = self.model.add_subsystem("plant", plant_group, promotes=["*"])
def create_technology_models(self):
# Loop through each technology and instantiate an OpenMDAO object (assume it exists)
# for each technology
self.tech_names = []
self.performance_models = []
self.control_strategies = []
self.dispatch_rule_sets = []
self.cost_models = []
self.finance_models = []
combined_performance_and_cost_models = [
"HOPPComponent",
"h2_storage",
"WOMBATElectrolyzerModel",
"IronComponent",
"ArdWindPlantModel",
]
if any(tech == "site" for tech in self.technology_config["technologies"]):
msg = (
"'site' is an invalid technology name and is reserved for top-level "
"variables. Please change the technology name to something else."
)
raise NameError(msg)
reserved_techs = {"pipe", "cable"}
# Use set intersection to find any reserved names present in the config
invalid_techs = sorted(
set(self.technology_config["technologies"]).intersection(reserved_techs)
)
if invalid_techs:
if len(invalid_techs) == 1:
invalid_tech_msg = f"'{invalid_techs[0]}' is an invalid technology name and is"
else:
names_str = ", ".join(f"'{tech}'" for tech in invalid_techs)
invalid_tech_msg = f"{names_str} are invalid technology names and are"
msg = (
f"{invalid_tech_msg} reserved for internal H2I transport models. "
"Please change the technology name to something else."
)
raise NameError(msg)
# Create a technology group for each technology
for tech_name, individual_tech_config in self.technology_config["technologies"].items():
perf_model = individual_tech_config.get("performance_model", {}).get("model")
if "control_parameters" in individual_tech_config["model_inputs"]:
if "tech_name" in individual_tech_config["model_inputs"]["control_parameters"]:
provided_tech_name = individual_tech_config["model_inputs"][
"control_parameters"
]["tech_name"]
if tech_name != provided_tech_name:
raise ValueError(
f"tech_name in control_parameters ({provided_tech_name}) must match "
f"the top-level name of the tech group ({tech_name})"
)
if perf_model == "FeedstockPerformanceModel":
comp = self.supported_models[perf_model](
driver_config=self.driver_config,
plant_config=self.plant_config,
tech_config=individual_tech_config,
)
self.plant.add_subsystem(f"{tech_name}_source", comp)
else:
tech_group = self.plant.add_subsystem(tech_name, om.Group())
self.tech_names.append(tech_name)
# Check if performance, cost, and finance models are the same
# and in combined_performance_and_cost_models
perf_model = individual_tech_config.get("performance_model", {}).get("model")
cost_model = individual_tech_config.get("cost_model", {}).get("model")
individual_tech_config.get("finance_model", {}).get("model")
if (
perf_model
and (perf_model == cost_model)
and (perf_model in combined_performance_and_cost_models)
):
# Catch dispatch rules for systems that have the same performance & cost models
if "dispatch_rule_set" in individual_tech_config:
control_object = self._process_model(
"dispatch_rule_set", individual_tech_config, tech_group
)
self.control_strategies.append(control_object)
# Catch control models for systems that have the same performance & cost models
if "control_strategy" in individual_tech_config:
control_object = self._process_model(
"control_strategy", individual_tech_config, tech_group
)
self.control_strategies.append(control_object)
comp = self.supported_models[perf_model](
driver_config=self.driver_config,
plant_config=self.plant_config,
tech_config=individual_tech_config,
)
om_model_object = tech_group.add_subsystem(tech_name, comp, promotes=["*"])
self.performance_models.append(om_model_object)
self.cost_models.append(om_model_object)
self.finance_models.append(om_model_object)
continue
# Process the models
# TODO: integrate financial_model into the loop below
model_types = [
"dispatch_rule_set",
"control_strategy",
"performance_model",
"cost_model",
]
for model_type in model_types:
if model_type in individual_tech_config:
om_model_object = self._process_model(
model_type, individual_tech_config, tech_group
)
if "control_strategy" in model_type:
plural_model_type_name = "control_strategies"
else:
plural_model_type_name = model_type + "s"
getattr(self, plural_model_type_name).append(om_model_object)
# Process the finance models
if "finance_model" in individual_tech_config:
if "model" in individual_tech_config["finance_model"]:
finance_name = individual_tech_config["finance_model"]["model"]
if finance_name != individual_tech_config.get("cost_model", {}).get(
"model", ""
):
finance_object = self.supported_models[finance_name]
tech_group.add_subsystem(
f"{tech_name}_finance",
finance_object(
driver_config=self.driver_config,
plant_config=self.plant_config,
tech_config=individual_tech_config,
),
promotes=["*"],
)
self.finance_models.append(finance_object)
for tech_name, individual_tech_config in self.technology_config["technologies"].items():
cost_model = individual_tech_config.get("cost_model", {}).get("model")
if cost_model == "FeedstockCostModel":
comp = self.supported_models[cost_model](
driver_config=self.driver_config,
plant_config=self.plant_config,
tech_config=individual_tech_config,
)
self.plant.add_subsystem(tech_name, comp)
def _process_model(self, model_type, individual_tech_config, tech_group):
# Generalized function to process model definitions
model_name = individual_tech_config[model_type]["model"]
model_object = self.supported_models[model_name]
om_model_object = tech_group.add_subsystem(
model_name,
model_object(
driver_config=self.driver_config,
plant_config=self.plant_config,
tech_config=individual_tech_config,
),
promotes=["*"],
)
return om_model_object
def create_finance_model(self):
"""
Create and configure the finance model(s) for the plant.
This method initializes finance subsystems for the plant based on the
configuration provided in ``self.plant_config["finance_parameters"]``. It
supports both default (single-model) setups and multiple/distinct (subgroup-specific)
finance models.
Within this framework, a finance subgroup serves as a flexible grouping mechanism for
calculating finance metrics across different subsets of technologies.
These groupings can draw on varying finance inputs or models within the same simulation.
To support a wide range of use cases, such as evaluating metrics for only part of a larger
system, finance subgroups may reference multiple finance_groups and may overlap
partially or fully with the technologies included in other finance subgroups.
Behavior:
* If ``finance_parameters`` is not defined in the plant configuration,
no finance model is created.
* If no subgroups are defined, all technologies are grouped together
under a default finance group. ``commodity`` and ``finance_model`` are
required in this case.
* If subgroups are provided, each subgroup defines its own set of
technologies, associated commodity, and finance model(s).
Each subgroup is nested under a unique name of your choice under
["finance_parameters"]["subgroups"] in the plant configuration.
* Subsystems such as ``AdjustedCapexOpexComp`` and
``GenericProductionSummerPerformanceModel``, and the selected finance
models are added to each subgroup's finance group.
* If `commodity_stream` is provided for a subgroup, the output of the
technology specified as the `commodity_stream` must be the same as the
specified commodity for that subgroup.
* Supports both global finance models and technology-specific finance
models. Technology-specific finance models are defined in the technology
configuration.
Raises:
ValueError:
If ["finance_parameters"]["finance_group"] is incomplete (e.g., missing
``commodity`` or ``finance_model``) when no subgroups are defined.
ValueError:
If a subgroup has an invalid technology.
ValueError:
If a specified finance model is not found in
``self.supported_models``.
Side Effects:
* Updates ``self.plant_config["finance_parameters"]["finance_group"] if only a single
finance model is provided (wraps it in a default finance subgroup).
* Constructs and attaches OpenMDAO finance subsystem groups to the
plant model under names ``finance_subgroup_<subgroup_name>``.
* Stores processed subgroup configurations in
``self.finance_subgroups``.
Example:
Suppose ``plant_config["finance_parameters"]["finance_group"]`` defines a single finance
model without subgroups:
>>> self.plant_config["finance_parameters"]["finance_group"] = {
... "commodity": "hydrogen",
... "finance_model": "ProFastLCO",
... "model_inputs": {"discount_rate": 0.08},
... }
>>> self.create_finance_model()
# Creates a default subgroup containing all technologies and
# attaches a ProFAST finance model component to the plant.
"""
# if there aren't any finance parameters don't setup a finance model
if "finance_parameters" not in self.plant_config:
return
subgroups = self.plant_config["finance_parameters"].get("finance_subgroups", None)
if "finance_groups" not in self.plant_config["finance_parameters"]:
raise ValueError("plant_config['finance_parameters'] must define 'finance_groups'.")
finance_subgroups = {}
default_finance_group_name = "default"
# only one finance model is being used with subgroups
if (
"finance_model" in self.plant_config["finance_parameters"]["finance_groups"]
and "model_inputs" in self.plant_config["finance_parameters"]["finance_groups"]
):
if (
default_finance_group_name
in self.plant_config["finance_parameters"]["finance_groups"]
):
# throw an error if the user has an unused finance group named "default".
msg = (
"Invalid key `default` in "
"plant_config['finance_parameters']['finance_groups']. "
"Please rename the `default` key to something else or remove it. "
"The name `default` will be used to reference the finance model group."
)
raise ValueError(msg)
default_model_name = self.plant_config["finance_parameters"]["finance_groups"].pop(
"finance_model"
)
default_model_inputs = self.plant_config["finance_parameters"]["finance_groups"].pop(
"model_inputs"
)
default_model_dict = {
default_finance_group_name: {
"finance_model": default_model_name,
"model_inputs": default_model_inputs,
}
}
self.plant_config["finance_parameters"]["finance_groups"].update(default_model_dict)
if subgroups is None:
# --- Default behavior ---
commodity = self.plant_config["finance_parameters"]["finance_groups"].get("commodity")
finance_model_name = (
self.plant_config["finance_parameters"]["finance_groups"]
.get(default_finance_group_name, {})
.get("finance_model")
)
if not commodity or not finance_model_name:
raise ValueError(
"plant_config['finance_parameters']['finance_groups'] "
"must define 'commodity' and 'finance_model' "
"if no finance_subgroups are provided."
)
# Collect all technologies into one subgroup
all_techs = list(self.technology_config["technologies"].keys())
subgroup = {
"commodity": commodity,
"finance_groups": [default_finance_group_name],
"technologies": all_techs,
}
subgroups = {default_finance_group_name: subgroup}
# --- Normal subgroup handling ---
for subgroup_name, subgroup_params in subgroups.items():
commodity = subgroup_params.get("commodity", None)
commodity_desc = subgroup_params.get("commodity_desc", "")
finance_group_names = subgroup_params.get(
"finance_groups", [default_finance_group_name]
)
tech_names = subgroup_params.get("technologies")
commodity_stream = subgroup_params.get("commodity_stream", None)
if isinstance(finance_group_names, str):
finance_group_names = [finance_group_names]
# check commodity type
if commodity is None:
raise ValueError(
f"Required parameter ``commodity`` not provided in subgroup {subgroup_name}."
)
tech_configs = {}
for tech in tech_names:
if tech in self.technology_config["technologies"]:
tech_configs[tech] = self.technology_config["technologies"][tech]
else:
raise KeyError(
f"Technology '{tech}' not found in the technology configuration, "
f"but is listed in subgroup '{subgroup_name}', "
"Available "
f"technologies: {list(self.technology_config['technologies'].keys())}"
)
if commodity_stream is not None:
if "combiner" not in commodity_stream and commodity_stream not in tech_names:
raise UserWarning(
f"The technology specific for the commodity_stream '{commodity_stream}' "
f"is not included in subgroup '{subgroup_name}' technologies list."
f" Subgroup '{subgroup_name}' includes technologies: {tech_names}."
)
finance_subgroups.update(
{
subgroup_name: {
"tech_configs": tech_configs,
"commodity": commodity,
"commodity_stream": commodity_stream,
"is_system_finance_model": True,
}
}
)
finance_subgroup = om.Group()
# Default logic for handling cases without specified commodity streams
if commodity_stream is None:
if commodity == "electricity":
elec_tech_names = [
tech for tech in tech_configs if is_electricity_producer(tech)
]
if len(elec_tech_names) != 1:
msg = (
f"Multiple electricity producing technologies found in finance subgroup"
f" '{subgroup_name}'. Please specify the commodity_stream for the "
f"finance subgroup {subgroup_name}."
)
raise ValueError(msg)
else:
finance_subgroups[subgroup_name].update(
{"commodity_stream": elec_tech_names[0]}
)
else:
# Default logic for tech-names and the primary commodity streams
default_techs_to_commodities = {
"electrolyzer": "hydrogen",
"geoh2": "hydrogen",
"ammonia": "ammonia",
"doc": "co2",
"oae": "co2",
"methanol": "methanol",
"air_separator": "nitrogen",
}
for default_tech, tech_commodity in default_techs_to_commodities.items():
if commodity == tech_commodity and any(
default_tech in tech_name for tech_name in tech_names
):
commodity_stream_tech_name = [
tech_name for tech_name in tech_names if default_tech in tech_name
]
finance_subgroups[subgroup_name].update(
{"commodity_stream": commodity_stream_tech_name[0]}
)
# Check if a default commodity_stream was found, throw error if not
missing_commodity_stream = (
finance_subgroups[subgroup_name].get("commodity_stream", None) is None
)
if missing_commodity_stream and len(tech_names) > 1:
msg = (
"Could not find a default technology to use as the commodity stream "
f"for commodity {finance_subgroups[subgroup_name]['commodity']}. "
"Please specify the `commodity_stream` for finance subgroup "
f"{subgroup_name}."
)
raise UserWarning(msg)
# Add adjusted capex/opex
adjusted_capex_opex_comp = AdjustedCapexOpexComp(
driver_config=self.driver_config,
tech_configs=tech_configs,
plant_config=self.plant_config,
)
finance_subgroup.add_subsystem(
"adjusted_capex_opex_comp", adjusted_capex_opex_comp, promotes=["*"]
)
# Initialize counter to check if invalid combination of finance
# groups exist within a finance subgroup
n_tech_finances_in_group = 0
for finance_group_name in finance_group_names:
# check if using tech-specific finance model
if any(
tech_name == finance_group_name
for tech_name, tech_params in tech_configs.items()
):
tech_finance_group_name = (
tech_configs.get(finance_group_name).get("finance_model", {}).get("model")
)
# this is created in create_technologies()
if tech_finance_group_name is not None:
n_tech_finances_in_group += 1
# tech specific finance models are created in create_technologies()
# and do not need to be included in the system finance models.
# set commodity_stream to None so that inputs needed for system-level
# finance models are not connected to tech-specific finance models.
# finance_subgroups[subgroup_name].update({"commodity_stream": None})
finance_subgroups[subgroup_name].update({"is_system_finance_model": False})
continue
# if not using a tech-specific finance group, get the finance model and inputs for
# the finance model group specified by finance_group_name
finance_group_config = self.plant_config["finance_parameters"][
"finance_groups"
].get(finance_group_name)
model_name = finance_group_config.get("finance_model") # finance model
fin_model_inputs = finance_group_config.get(
"model_inputs"
) # inputs to finance model
# get finance model component definition
fin_model = self.supported_models.get(model_name)
if fin_model is None:
raise ValueError(f"finance model '{model_name}' not found.")
# filter the plant_config so the finance_parameters only includes data for
# this finance model group
# first, grab information from the plant config, except the finance parameters
filtered_plant_config = {
k: v for k, v in self.plant_config.items() if k != "finance_parameters"
}
# then, reformat the finance_parameters to only include inputs for the
# finance group specified by finance_group_name
filtered_plant_config.update(
{
"finance_parameters": {
"finance_model": model_name, # unused by the finance model
"model_inputs": fin_model_inputs, # inputs for finance model
}
}
)
commodity_desc = subgroup_params.get("commodity_desc", "")
commodity_output_desc = subgroup_params.get("commodity_desc", "")
# check if multiple finance models are specified for the subgroup
if len(finance_group_names) > 1:
# check that the finance model groups do not include tech-specific finances
finance_groups = self.plant_config["finance_parameters"]["finance_groups"]
non_tech_finances = [k for k in finance_group_names if k in finance_groups]
tech_finances = [k for k in finance_group_names if k not in finance_groups]
if n_tech_finances_in_group > 0 and non_tech_finances:
msg = (
f"Cannot run a tech-specific finance model ({tech_finances}) in the "
f"same finance subgroup as a system-level finance model "
f"({non_tech_finances}). Please modify the finance_groups in finance "
f"subgroup {subgroup_name}."
)
raise ValueError(msg)
# if multiple non-tech specific finance model groups are specified for the
# subgroup, the outputs of the finance model must have unique names to
# avoid errors.
if len(non_tech_finances) > 1:
# finance models name their outputs based on the description and commodity
# update the description to include the finance model name to ensure
# uniquely named outputs
commodity_output_desc = commodity_output_desc + f"_{finance_group_name}"
# create the finance component
fin_comp = fin_model(
driver_config=self.driver_config,
tech_config=tech_configs,
plant_config=filtered_plant_config,
commodity_type=commodity,
description=commodity_output_desc,
)
# name the finance component based on the commodity and description
finance_subsystem_name = (
f"{commodity}_finance_{finance_group_name}"
if commodity_desc == ""
else f"{commodity}_{commodity_desc}_finance_{finance_group_name}"
)
# add the finance component to the finance group
finance_subgroup.add_subsystem(finance_subsystem_name, fin_comp, promotes=["*"])
# add the finance group to the subgroup
self.plant.add_subsystem(f"finance_subgroup_{subgroup_name}", finance_subgroup)
self.finance_subgroups = finance_subgroups
def _connect_multivariable_stream(
self, source_tech, dest_tech, stream_name, combiner_counts, splitter_counts
):
"""Connect a multivariable stream between source and destination technologies.
Handles combiner indexing (numbered inputs), splitter indexing (numbered outputs),
and direct connections. Updates combiner_counts/splitter_counts dicts in-place.
Args:
source_tech (str): Name of the source technology.
dest_tech (str): Name of the destination technology.
stream_name (str): Name of the multivariable stream (key in multivariable_streams).
combiner_counts (dict): Tracks the next input index per combiner technology.
splitter_counts (dict): Tracks the next output index per splitter technology.
"""
if "combiner" in dest_tech:
if dest_tech not in combiner_counts:
combiner_counts[dest_tech] = 1
else:
combiner_counts[dest_tech] += 1
stream_index = combiner_counts[dest_tech]
for var_name in multivariable_streams[stream_name]:
self.plant.connect(
f"{source_tech}.{stream_name}:{var_name}_out",
f"{dest_tech}.{stream_name}:{var_name}_in{stream_index}",
)
elif "splitter" in source_tech:
if source_tech not in splitter_counts:
splitter_counts[source_tech] = 1
else:
splitter_counts[source_tech] += 1
stream_index = splitter_counts[source_tech]
for var_name in multivariable_streams[stream_name]:
self.plant.connect(
f"{source_tech}.{stream_name}:{var_name}_out{stream_index}",
f"{dest_tech}.{stream_name}:{var_name}_in",
)
else:
for var_name in multivariable_streams[stream_name]:
self.plant.connect(
f"{source_tech}.{stream_name}:{var_name}_out",
f"{dest_tech}.{stream_name}:{var_name}_in",
)