-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathconsumer_function_mapper.py
More file actions
1706 lines (1531 loc) · 77.7 KB
/
Copy pathconsumer_function_mapper.py
File metadata and controls
1706 lines (1531 loc) · 77.7 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 logging
from typing import Protocol, assert_never
from uuid import UUID, uuid4
import numpy as np
from pydantic import ValidationError
from ecalc_neqsim_wrapper.fluid_service import NeqSimFluidService
from libecalc.common.consumption_type import ConsumptionType
from libecalc.common.energy_usage_type import EnergyUsageType
from libecalc.common.errors.ecalc_validation_error import (
EcalcValidationException,
ProcessNonPositivePressureValidationException,
ProcessPressureRatioValidationException,
)
from libecalc.common.errors.exceptions import InvalidResourceException
from libecalc.common.fixed_speed_pressure_control import FixedSpeedPressureControl, InterstagePressureControl
from libecalc.common.temporal_model import TemporalModel
from libecalc.common.time_utils import Period, define_time_model_for_period
from libecalc.common.units import Unit
from libecalc.common.utils.rates import RateType
from libecalc.common.variables import ExpressionEvaluator
from libecalc.domain.infrastructure.energy_components.legacy_consumer.consumer_function import ConsumerFunction
from libecalc.domain.infrastructure.energy_components.legacy_consumer.consumer_function.direct_consumer_function import (
DirectConsumerFunction,
)
from libecalc.domain.infrastructure.energy_components.legacy_consumer.system.consumer_function import (
ConsumerSystemConsumerFunction,
SystemComponent,
)
from libecalc.domain.infrastructure.energy_components.legacy_consumer.system.operational_setting import (
ConsumerSystemOperationalSettingExpressions,
)
from libecalc.domain.infrastructure.energy_components.legacy_consumer.system.types import ConsumerSystemComponent
from libecalc.domain.infrastructure.energy_components.legacy_consumer.tabulated import (
TabularConsumerFunction,
TabularEnergyFunction,
)
from libecalc.domain.infrastructure.energy_components.turbine import Turbine
from libecalc.domain.process.compressor.core.base import CompressorWithTurbineModel
from libecalc.domain.process.compressor.core.sampled import CompressorModelSampled
from libecalc.domain.process.compressor.core.train.base import CompressorTrainModel, calculate_pressure_ratio_per_stage
from libecalc.domain.process.compressor.core.train.compressor_train_common_shaft import CompressorTrainCommonShaft
from libecalc.domain.process.compressor.core.train.simplified_train.simplified_train import CompressorTrainSimplified
from libecalc.domain.process.compressor.core.train.stage import CompressorTrainStage
from libecalc.domain.process.entities.process_units.legacy_compressor.legacy_compressor import LegacyCompressor
from libecalc.domain.process.entities.process_units.legacy_mixer.legacy_mixer import LegacyMixer
from libecalc.domain.process.entities.process_units.legacy_splitter.legacy_splitter import (
LegacySplitter,
)
from libecalc.domain.process.entities.process_units.rate_modifier.rate_modifier import RateModifier
from libecalc.domain.process.evaluation_input import (
CompressorEvaluationInput,
CompressorSampledEvaluationInput,
PumpEvaluationInput,
)
from libecalc.domain.process.pump.pump import PumpModel
from libecalc.domain.process.value_objects.chart.chart import ChartData
from libecalc.domain.regularity import Regularity
from libecalc.domain.resource import Resource, Resources
from libecalc.domain.time_series_flow_rate import TimeSeriesFlowRate
from libecalc.domain.time_series_variable import TimeSeriesVariable
from libecalc.expression import Expression
from libecalc.expression.expression import ExpressionType, InvalidExpressionError
from libecalc.presentation.yaml.domain.ecalc_components import (
CompressorProcessSystemComponent,
CompressorSampledComponent,
PumpProcessSystemComponent,
)
from libecalc.presentation.yaml.domain.expression_time_series_flow_rate import ExpressionTimeSeriesFlowRate
from libecalc.presentation.yaml.domain.expression_time_series_fluid_density import ExpressionTimeSeriesFluidDensity
from libecalc.presentation.yaml.domain.expression_time_series_power import ExpressionTimeSeriesPower
from libecalc.presentation.yaml.domain.expression_time_series_power_loss_factor import (
ExpressionTimeSeriesPowerLossFactor,
)
from libecalc.presentation.yaml.domain.expression_time_series_pressure import ExpressionTimeSeriesPressure
from libecalc.presentation.yaml.domain.expression_time_series_variable import ExpressionTimeSeriesVariable
from libecalc.presentation.yaml.domain.reference_service import ReferenceService
from libecalc.presentation.yaml.domain.time_series_expression import TimeSeriesExpression
from libecalc.presentation.yaml.mappers.charts.generic_from_input_chart_data import GenericFromInputChartData
from libecalc.presentation.yaml.mappers.facility_input import (
_create_pump_chart_variable_speed_dto_model_data,
_create_pump_model_single_speed_dto_model_data,
_get_float_column_or_none,
)
from libecalc.presentation.yaml.mappers.fluid_mapper import (
composition_fluid_model_mapper,
predefined_fluid_model_mapper,
)
from libecalc.presentation.yaml.mappers.model import (
InvalidChartResourceException,
_generic_from_design_point_compressor_chart_mapper,
_pressure_control_mapper,
map_yaml_to_fixed_speed_pressure_control,
single_speed_compressor_chart_mapper,
variable_speed_compressor_chart_mapper,
)
from libecalc.presentation.yaml.mappers.simplified_train_mapping_utils import (
CompressorOperationalTimeSeries,
calculate_number_of_stages,
)
from libecalc.presentation.yaml.mappers.utils import (
YAML_UNIT_MAPPING,
convert_control_margin_to_fraction,
convert_efficiency_to_fraction,
convert_temperature_to_kelvin,
)
from libecalc.presentation.yaml.mappers.yaml_mapping_context import MappingContext
from libecalc.presentation.yaml.model_validation_exception import ModelValidationException
from libecalc.presentation.yaml.validation_errors import Location, ModelValidationError
from libecalc.presentation.yaml.yaml_keywords import EcalcYamlKeywords
from libecalc.presentation.yaml.yaml_models.yaml_model import YamlValidator
from libecalc.presentation.yaml.yaml_types.components.legacy.energy_usage_model import (
YamlElectricityEnergyUsageModel,
YamlEnergyUsageModelCompressor,
YamlEnergyUsageModelCompressorSystem,
YamlEnergyUsageModelCompressorTrainMultipleStreams,
YamlEnergyUsageModelDirectElectricity,
YamlEnergyUsageModelDirectFuel,
YamlEnergyUsageModelPump,
YamlEnergyUsageModelPumpSystem,
YamlEnergyUsageModelTabulated,
YamlFuelEnergyUsageModel,
)
from libecalc.presentation.yaml.yaml_types.components.legacy.energy_usage_model.yaml_energy_usage_model_direct import (
ConsumptionRateType,
)
from libecalc.presentation.yaml.yaml_types.components.yaml_expression_type import YamlExpressionType
from libecalc.presentation.yaml.yaml_types.facility_model.yaml_facility_model import (
YamlCompressorTabularModel,
YamlPumpChartSingleSpeed,
YamlPumpChartVariableSpeed,
)
from libecalc.presentation.yaml.yaml_types.models import YamlCompressorWithTurbine
from libecalc.presentation.yaml.yaml_types.models.yaml_compressor_chart import (
YamlGenericFromDesignPointChart,
YamlGenericFromInputChart,
YamlSingleSpeedChart,
YamlVariableSpeedChart,
)
from libecalc.presentation.yaml.yaml_types.models.yaml_compressor_stages import YamlUnknownCompressorStages
from libecalc.presentation.yaml.yaml_types.models.yaml_compressor_trains import (
YamlMultipleStreamsStreamIngoing,
YamlMultipleStreamsStreamOutgoing,
YamlSimplifiedVariableSpeedCompressorTrain,
YamlSingleSpeedCompressorTrain,
YamlVariableSpeedCompressorTrain,
YamlVariableSpeedCompressorTrainMultipleStreamsAndPressures,
)
from libecalc.presentation.yaml.yaml_types.models.yaml_fluid import YamlCompositionFluidModel, YamlPredefinedFluidModel
from libecalc.presentation.yaml.yaml_types.yaml_temporal_model import YamlTemporalModel
from libecalc.process.fluid_stream.fluid_model import FluidModel
from libecalc.process.fluid_stream.fluid_service import FluidService
from libecalc.process.process_units.choke import Choke
from libecalc.process.process_units.liquid_remover import LiquidRemover
from libecalc.process.process_units.temperature_setter import TemperatureSetter
from libecalc.process.shaft import Shaft, SingleSpeedShaft, VariableSpeedShaft
logger = logging.getLogger(__name__)
class InvalidConsumptionType(Exception):
def __init__(self, actual: ConsumptionType, expected: ConsumptionType):
self.actual = actual
self.expected = expected
message = f"Invalid consumption type: expected a model that consumes {expected.value.lower()}, got {actual.value.lower()}."
super().__init__(message)
def handle_condition_list(conditions: list[ExpressionType]):
conditions_with_parentheses = [f"({condition})" for condition in conditions]
return " {*} ".join(conditions_with_parentheses)
class ConditionedModel(Protocol):
condition: YamlExpressionType
conditions: list[YamlExpressionType] | None
def _map_condition(energy_usage_model: ConditionedModel) -> str | int | float | None:
if energy_usage_model.condition:
condition_value = energy_usage_model.condition
return condition_value
elif energy_usage_model.conditions:
return handle_condition_list(energy_usage_model.conditions) # type: ignore[arg-type]
else:
return None
def _all_equal(items: set) -> bool:
return len(items) <= 1
def _is_sampled_compressor(model: CompressorTrainModel | CompressorModelSampled | CompressorWithTurbineModel) -> bool:
if isinstance(model, CompressorModelSampled):
return True
if isinstance(model, CompressorWithTurbineModel) and isinstance(model.compressor_model, CompressorModelSampled):
return True
return False
class InvalidEnergyUsageModelException(Exception):
def __init__(self, period: Period, model: YamlFuelEnergyUsageModel | YamlElectricityEnergyUsageModel, message: str):
self.period = period
self.model = model
self.message = message
super().__init__(f"Invalid energy usage model '{model.type}' with start '{period}'. \n Message: {message}")
def map_rate_fractions(
rate_fractions: list[Expression],
system_rate: Expression,
) -> list[Expression]:
# Multiply rate_fractions with total system rate to get rates
return [
Expression.multiply(
system_rate,
rate_fraction,
)
for rate_fraction in rate_fractions
]
def validate_pressures(
suction_pressure: ExpressionTimeSeriesPressure,
discharge_pressure: ExpressionTimeSeriesPressure,
intermediate_pressure: ExpressionTimeSeriesPressure | None = None,
):
validation_mask = suction_pressure.get_validation_mask()
assert validation_mask == discharge_pressure.get_validation_mask()
suction_pressure_values = suction_pressure.get_values()
discharge_pressure_values = discharge_pressure.get_values()
if intermediate_pressure is not None:
assert validation_mask == intermediate_pressure.get_validation_mask()
intermediate_pressure_values = intermediate_pressure.get_values()
else:
intermediate_pressure_values = None
for i in range(len(suction_pressure_values)):
if validation_mask[i]:
sp = suction_pressure_values[i]
dp = discharge_pressure_values[i]
if sp <= 0:
raise ProcessNonPositivePressureValidationException(
message=f"Invalid pressure at timestep {i + 1}: suction pressure ({sp}) is non-positive, which is not physically possible."
)
if dp <= 0:
raise ProcessNonPositivePressureValidationException(
message=f"Invalid pressure at timestep {i + 1}: discharge pressure ({dp}) is non-positive, which is not physically possible."
)
if intermediate_pressure_values is not None:
ip = intermediate_pressure_values[i]
if ip <= 0:
raise ProcessNonPositivePressureValidationException(
message=f"Invalid pressure at timestep {i + 1}: intermediate pressure ({ip}) is non-positive, which is not physically possible."
)
if not (sp <= ip <= dp):
raise ProcessPressureRatioValidationException(
message=f"Invalid pressures at index {i + 1}: suction pressure ({sp}) must be less than intermediate pressure ({ip}), which must be less than discharge pressure ({dp})."
)
else:
if not (sp <= dp):
raise ProcessPressureRatioValidationException(
message=f"Invalid pressures at index {i + 1}: suction pressure ({sp}) must be less than discharge pressure ({dp})."
)
class CompressorModelMapper:
def __init__(self, resources: Resources, reference_service: ReferenceService, configuration: YamlValidator):
self._reference_service = reference_service
self._resources = resources
self._configuration = configuration
def _create_error(self, message: str, reference: str, key: str | None = None):
yaml_path = self._reference_service.get_yaml_path(reference)
location_keys = [*yaml_path.keys[:-1], reference] # Replace index with name
if key is not None:
key_path = yaml_path.append(key)
location_keys.append(key)
else:
key_path = yaml_path
file_context = self._configuration.get_file_context(key_path.keys)
return ModelValidationError(
message=message,
location=Location(keys=location_keys),
name=reference,
file_context=file_context,
)
def _get_resource(self, resource_name: str, reference: str) -> Resource:
resource = self._resources.get(resource_name)
if resource is None:
raise ModelValidationException(
errors=[
self._create_error(
message=f"Unable to find resource '{resource_name}'.", reference=reference, key="FILE"
)
]
)
return resource
def _get_fluid_model(self, reference: str) -> FluidModel:
model = self._reference_service.get_fluid(reference)
try:
if isinstance(model, YamlPredefinedFluidModel):
return predefined_fluid_model_mapper(model)
elif isinstance(model, YamlCompositionFluidModel):
return composition_fluid_model_mapper(model)
else:
assert_never(model)
except ValidationError as ve:
raise ModelValidationException.from_pydantic(
validation_error=ve,
file_context=self._configuration.get_file_context(
self._reference_service.get_yaml_path(reference).keys
),
) from ve
except EcalcValidationException as e:
raise ModelValidationException(errors=[self._create_error(str(e), reference)]) from e
def _get_compressor_chart(
self,
reference: str,
control_margin: float | None,
) -> ChartData:
model = self._reference_service.get_compressor_chart(reference)
assert isinstance(model, YamlSingleSpeedChart | YamlVariableSpeedChart) # Generic charts are handled separately
try:
if isinstance(model, YamlSingleSpeedChart):
return single_speed_compressor_chart_mapper(
model_config=model, resources=self._resources, control_margin=control_margin
)
elif isinstance(model, YamlVariableSpeedChart):
return variable_speed_compressor_chart_mapper(
model_config=model, resources=self._resources, control_margin=control_margin
)
else:
assert_never(model)
except ValidationError as ve:
raise ModelValidationException.from_pydantic(
validation_error=ve,
file_context=self._configuration.get_file_context(
self._reference_service.get_yaml_path(reference).keys
),
) from ve
except EcalcValidationException as e:
raise ModelValidationException(errors=[self._create_error(str(e), reference)]) from e
def _create_compressor_train_stage(
self,
compressor_chart_reference: str,
inlet_temperature_kelvin: float,
remove_liquid_after_cooling: bool,
fluid_service: FluidService,
shaft: Shaft,
number_of_mixer_ports_this_stage: int = 0,
number_of_splitter_ports_this_stage: int = 0,
pressure_drop_ahead_of_stage: float | None = None,
interstage_pressure_control: InterstagePressureControl | None = None,
control_margin: float | None = None,
) -> CompressorTrainStage:
chart_data = self._get_compressor_chart(compressor_chart_reference, control_margin)
return CompressorTrainStage(
rate_modifier=RateModifier(chart_data, shaft=shaft),
compressor=LegacyCompressor(chart_data, fluid_service=fluid_service, shaft=shaft),
temperature_setter=TemperatureSetter(
required_temperature_kelvin=inlet_temperature_kelvin,
fluid_service=fluid_service,
),
liquid_remover=LiquidRemover(
fluid_service=fluid_service,
)
if remove_liquid_after_cooling
else None,
fluid_service=fluid_service,
choke=(
Choke(
pressure_change=pressure_drop_ahead_of_stage,
fluid_service=fluid_service,
)
if pressure_drop_ahead_of_stage
else None
),
interstage_pressure_control=interstage_pressure_control,
splitter=(
LegacySplitter(number_of_splitter_ports_this_stage + 1)
if number_of_splitter_ports_this_stage > 0
else None
),
mixer=(
LegacyMixer(number_of_mixer_ports_this_stage + 1, fluid_service=fluid_service)
if number_of_mixer_ports_this_stage > 0
else None
),
)
def _create_variable_speed_compressor_train(
self, model: YamlVariableSpeedCompressorTrain
) -> tuple[CompressorTrainCommonShaft, FluidModel]:
fluid_model_reference: str = model.fluid_model
fluid_model = self._get_fluid_model(fluid_model_reference)
train_spec = model.compressor_train
shaft = VariableSpeedShaft()
# Get the fluid service singleton
fluid_service = NeqSimFluidService.instance()
# The stages are pre defined, known
stages_data = train_spec.stages
stages: list[CompressorTrainStage] = []
for stage in stages_data:
control_margin = convert_control_margin_to_fraction(
stage.control_margin,
YAML_UNIT_MAPPING[stage.control_margin_unit],
)
stages.append(
self._create_compressor_train_stage(
compressor_chart_reference=stage.compressor_chart,
inlet_temperature_kelvin=convert_temperature_to_kelvin(
[stage.inlet_temperature],
input_unit=Unit.CELSIUS,
)[0],
remove_liquid_after_cooling=True,
fluid_service=fluid_service,
shaft=shaft,
pressure_drop_ahead_of_stage=stage.pressure_drop_ahead_of_stage,
control_margin=control_margin,
)
)
pressure_control = _pressure_control_mapper(model)
if fluid_model is None:
raise EcalcValidationException("Fluid model is required for compressor train.")
compressor_model = CompressorTrainCommonShaft(
stages=stages,
shaft=shaft,
fluid_service=fluid_service,
energy_usage_adjustment_constant=model.power_adjustment_constant,
energy_usage_adjustment_factor=model.power_adjustment_factor,
calculate_max_rate=model.calculate_max_rate, # type: ignore[arg-type]
pressure_control=pressure_control,
maximum_power=model.maximum_power,
)
return compressor_model, fluid_model
def _create_single_speed_compressor_train(
self, model: YamlSingleSpeedCompressorTrain
) -> tuple[CompressorTrainCommonShaft, FluidModel]:
fluid_model_reference = model.fluid_model
fluid_model = self._get_fluid_model(fluid_model_reference)
train_spec = model.compressor_train
shaft = SingleSpeedShaft()
# Get the fluid service singleton
fluid_service = NeqSimFluidService.instance()
stages: list[CompressorTrainStage] = [
self._create_compressor_train_stage(
compressor_chart_reference=stage.compressor_chart,
inlet_temperature_kelvin=convert_temperature_to_kelvin(
[stage.inlet_temperature],
input_unit=Unit.CELSIUS,
)[0],
remove_liquid_after_cooling=True,
fluid_service=fluid_service,
shaft=shaft,
pressure_drop_ahead_of_stage=stage.pressure_drop_ahead_of_stage,
control_margin=convert_control_margin_to_fraction(
stage.control_margin,
YAML_UNIT_MAPPING[stage.control_margin_unit],
),
)
for stage in train_spec.stages
]
pressure_control = _pressure_control_mapper(model)
maximum_discharge_pressure = model.maximum_discharge_pressure
if maximum_discharge_pressure and pressure_control != FixedSpeedPressureControl.DOWNSTREAM_CHOKE:
raise EcalcValidationException(
f"Setting {EcalcYamlKeywords.maximum_discharge_pressure} for single speed compressor train is currently "
f"only supported with {FixedSpeedPressureControl.DOWNSTREAM_CHOKE.value} pressure control option. "
f"Pressure control option is {pressure_control.value}."
)
if fluid_model is None:
raise EcalcValidationException("Fluid model is required for compressor train.")
compressor_model = CompressorTrainCommonShaft(
stages=stages,
shaft=shaft,
fluid_service=fluid_service,
pressure_control=pressure_control,
maximum_discharge_pressure=maximum_discharge_pressure,
energy_usage_adjustment_constant=model.power_adjustment_constant,
energy_usage_adjustment_factor=model.power_adjustment_factor,
calculate_max_rate=model.calculate_max_rate,
maximum_power=model.maximum_power,
)
return compressor_model, fluid_model
def _create_turbine(self, reference: str) -> Turbine:
model = self._reference_service.get_turbine(reference)
try:
return Turbine(
lower_heating_value=model.lower_heating_value,
loads=model.turbine_loads,
efficiency_fractions=model.turbine_efficiencies,
energy_usage_adjustment_constant=model.power_adjustment_constant,
energy_usage_adjustment_factor=model.power_adjustment_factor,
)
except EcalcValidationException as e:
raise ModelValidationException(errors=[self._create_error(str(e), reference)]) from e
def _create_compressor_with_turbine(
self,
model: YamlCompressorWithTurbine,
operational_data: CompressorOperationalTimeSeries | None = None,
) -> tuple[CompressorWithTurbineModel, FluidModel]:
compressor_train_model, fluid_model = self.create_compressor_model(
model.compressor_model, operational_data=operational_data
)
assert isinstance(compressor_train_model, CompressorTrainModel | CompressorModelSampled)
turbine_model = self._create_turbine(model.turbine_model)
return CompressorWithTurbineModel(
energy_usage_adjustment_constant=model.power_adjustment_constant,
energy_usage_adjustment_factor=model.power_adjustment_factor,
compressor_energy_function=compressor_train_model,
turbine_model=turbine_model,
), fluid_model
def _create_simplified_model_with_prepared_stages(
self,
model: YamlSimplifiedVariableSpeedCompressorTrain,
operational_data: CompressorOperationalTimeSeries | None,
) -> tuple[CompressorTrainSimplified, FluidModel]:
"""Create simplified compressor model with stages prepared from operational data.
Args:
model: YAML simplified compressor model configuration
operational_data: Operational time series data (rates and pressures)
Returns:
CompressorTrainSimplified with stages prepared for the given data
Raises:
DomainValidationException: If operational data is invalid (validated by dataclass)
"""
# Get fluid model
fluid_model = self._get_fluid_model(model.fluid_model)
train_spec = model.compressor_train
shaft = SingleSpeedShaft() # Not used for simplified trains, but required by compressor
if isinstance(train_spec, YamlUnknownCompressorStages):
assert operational_data is not None
# For unknown stages, maximum_pressure_ratio_per_stage is required to determine stage count
if train_spec.maximum_pressure_ratio_per_stage is None:
raise EcalcValidationException(
"MAXIMUM_PRESSURE_RATIO_PER_STAGE is required for unknown compressor stages."
)
suction_pressure = operational_data.suction_pressures
discharge_pressure = operational_data.discharge_pressures
if suction_pressure is None:
raise EcalcValidationException(
"SUCTION_PRESSURE is required for simplified compressor model. "
"Simplified models perform thermodynamic calculations that require pressure data."
)
if discharge_pressure is None:
raise EcalcValidationException(
"DISCHARGE_PRESSURE is required for simplified compressor model. "
"Simplified models perform thermodynamic calculations that require pressure data."
)
number_of_stages = calculate_number_of_stages(
maximum_pressure_ratio_per_stage=train_spec.maximum_pressure_ratio_per_stage,
suction_pressures=suction_pressure,
discharge_pressures=discharge_pressure,
)
yaml_stages = [train_spec for _ in range(number_of_stages)]
else:
# Known stages: prepare charts for existing stages
yaml_stages = train_spec.stages
# operational_data might be None if simplified train with known stages and only generic from design point is used in a system.
# That means it's a fully defined train without knowing operational data.
# Get the fluid service singleton
fluid_service = NeqSimFluidService.instance()
stages: list[CompressorTrainStage] = []
if operational_data is None:
# Expect only generic from design point
for yaml_stage in yaml_stages:
yaml_chart = self._reference_service.get_compressor_chart(yaml_stage.compressor_chart)
assert isinstance(yaml_chart, YamlGenericFromDesignPointChart)
chart = _generic_from_design_point_compressor_chart_mapper(yaml_chart)
inlet_temperature_kelvin = convert_temperature_to_kelvin(
[yaml_stage.inlet_temperature],
input_unit=Unit.CELSIUS,
)[0]
stages.append(
CompressorTrainStage(
rate_modifier=RateModifier(chart, shaft=shaft),
compressor=LegacyCompressor(chart, fluid_service=fluid_service, shaft=shaft),
temperature_setter=TemperatureSetter(
required_temperature_kelvin=inlet_temperature_kelvin,
fluid_service=fluid_service,
),
liquid_remover=LiquidRemover(fluid_service=fluid_service),
fluid_service=fluid_service,
)
)
else:
# Expect generic from input, keep track of inlet and outlet pressures per stage since that is used to create generic from input charts
suction_pressures = operational_data.suction_pressures
discharge_pressures = operational_data.discharge_pressures
if suction_pressures is None:
raise EcalcValidationException(
"SUCTION_PRESSURE is required for simplified compressor model. "
"Simplified models perform thermodynamic calculations that require pressure data."
)
if discharge_pressures is None:
raise EcalcValidationException(
"DISCHARGE_PRESSURE is required for simplified compressor model. "
"Simplified models perform thermodynamic calculations that require pressure data."
)
pressure_ratios_per_stage = np.asarray(
[
calculate_pressure_ratio_per_stage(
suction_pressure=sp, discharge_pressure=dp, n_stages=len(yaml_stages)
)
for sp, dp in zip(suction_pressures, discharge_pressures)
]
)
stage_inlet_pressure = suction_pressures
for yaml_stage in yaml_stages:
stage_outlet_pressure = np.multiply(stage_inlet_pressure, pressure_ratios_per_stage)
yaml_chart = self._reference_service.get_compressor_chart(yaml_stage.compressor_chart)
inlet_temperature_kelvin = convert_temperature_to_kelvin(
[yaml_stage.inlet_temperature],
input_unit=Unit.CELSIUS,
)[0]
if isinstance(yaml_chart, YamlGenericFromDesignPointChart):
chart = _generic_from_design_point_compressor_chart_mapper(yaml_chart)
else:
assert isinstance(yaml_chart, YamlGenericFromInputChart)
chart = GenericFromInputChartData(
fluid_model=fluid_model,
fluid_service=fluid_service,
inlet_temperature=inlet_temperature_kelvin,
inlet_pressure=stage_inlet_pressure.tolist(),
standard_rates=operational_data.rates.tolist(),
outlet_pressure=stage_outlet_pressure.tolist(),
polytropic_efficiency=convert_efficiency_to_fraction(
efficiency_values=[yaml_chart.polytropic_efficiency],
input_unit=YAML_UNIT_MAPPING[yaml_chart.units.efficiency],
)[0],
)
stage_inlet_pressure = stage_outlet_pressure
stages.append(
CompressorTrainStage(
rate_modifier=RateModifier(chart, shaft=shaft),
compressor=LegacyCompressor(chart, fluid_service=fluid_service, shaft=shaft),
temperature_setter=TemperatureSetter(
required_temperature_kelvin=inlet_temperature_kelvin,
fluid_service=fluid_service,
),
liquid_remover=LiquidRemover(fluid_service=fluid_service),
fluid_service=fluid_service,
)
)
# Return unified model with immutable prepared stages
return CompressorTrainSimplified(
stages=stages,
fluid_service=fluid_service,
energy_usage_adjustment_constant=model.power_adjustment_constant,
energy_usage_adjustment_factor=model.power_adjustment_factor,
calculate_max_rate=model.calculate_max_rate,
maximum_power=model.maximum_power,
), fluid_model
def _create_variable_speed_compressor_train_multiple_streams_and_pressures(
self, model: YamlVariableSpeedCompressorTrainMultipleStreamsAndPressures
) -> tuple[CompressorTrainCommonShaft, list[FluidModel | None]]:
stream_references = {stream.name for stream in model.streams}
shaft = VariableSpeedShaft()
# Get the fluid service singleton
fluid_service = NeqSimFluidService.instance()
stream_to_stage_map: dict[str, int] = {}
for stage_index, stage_config in enumerate(model.stages):
for stream_reference in stage_config.stream or []:
if stream_reference in stream_references:
stream_to_stage_map.setdefault(stream_reference, stage_index)
stages = [
self._create_compressor_train_stage(
fluid_service=fluid_service,
shaft=shaft,
number_of_mixer_ports_this_stage=(
sum(
1
for stream_name in (stage_config.stream or [])
for s in model.streams
if s.name == stream_name and isinstance(s, YamlMultipleStreamsStreamIngoing)
)
- (1 if stage_index == 0 else 0)
),
number_of_splitter_ports_this_stage=sum(
1
for stream_name in (stage_config.stream or [])
for s in model.streams
if s.name == stream_name and isinstance(s, YamlMultipleStreamsStreamOutgoing)
),
compressor_chart_reference=stage_config.compressor_chart,
inlet_temperature_kelvin=convert_temperature_to_kelvin(
[stage_config.inlet_temperature], input_unit=Unit.CELSIUS
)[0],
pressure_drop_ahead_of_stage=stage_config.pressure_drop_ahead_of_stage,
remove_liquid_after_cooling=True,
control_margin=convert_control_margin_to_fraction(
stage_config.control_margin, YAML_UNIT_MAPPING[stage_config.control_margin_unit]
),
interstage_pressure_control=(
InterstagePressureControl(
upstream_pressure_control=map_yaml_to_fixed_speed_pressure_control(
stage_config.interstage_control_pressure.upstream_pressure_control
),
downstream_pressure_control=map_yaml_to_fixed_speed_pressure_control(
stage_config.interstage_control_pressure.downstream_pressure_control
),
)
if stage_config.interstage_control_pressure
else None
),
)
for stage_index, stage_config in enumerate(model.stages)
if not any(
stream_to_stage_map.setdefault(stream_reference, stage_index) != stage_index
for stream_reference in (stage_config.stream or [])
if stream_reference not in stream_references or stream_reference in stream_to_stage_map
)
]
fluid_models = [
self._get_fluid_model(stream_config.fluid_model)
if isinstance(stream_config, YamlMultipleStreamsStreamIngoing)
else None
for stream_config in model.streams
]
if not any(fluid_models):
raise EcalcValidationException("An inlet stream is required for this model.")
interstage_pressures = {i for i, stage in enumerate(stages) if stage.has_control_pressure}
stage_number_interstage_pressure = interstage_pressures.pop() if interstage_pressures else None
compressor_model = CompressorTrainCommonShaft(
energy_usage_adjustment_constant=model.power_adjustment_constant,
energy_usage_adjustment_factor=model.power_adjustment_factor,
stages=stages,
shaft=shaft,
fluid_service=fluid_service,
calculate_max_rate=False,
maximum_power=model.maximum_power,
pressure_control=_pressure_control_mapper(model),
stage_number_interstage_pressure=stage_number_interstage_pressure,
)
return compressor_model, fluid_models
def _create_compressor_sampled(self, model: YamlCompressorTabularModel, reference: str) -> CompressorModelSampled:
rate_header = EcalcYamlKeywords.consumer_function_rate
suction_pressure_header = EcalcYamlKeywords.consumer_function_suction_pressure
discharge_pressure_header = EcalcYamlKeywords.consumer_function_discharge_pressure
power_header = EcalcYamlKeywords.consumer_tabular_power
fuel_header = EcalcYamlKeywords.consumer_tabular_fuel
resource = self._get_resource(model.file, reference)
resource_headers = resource.get_headers()
has_fuel = fuel_header in resource_headers
energy_usage_header = fuel_header if has_fuel else power_header
rate_values = _get_float_column_or_none(resource, rate_header)
suction_pressure_values = _get_float_column_or_none(resource, suction_pressure_header)
discharge_pressure_values = _get_float_column_or_none(resource, discharge_pressure_header)
energy_usage_values = resource.get_float_column(energy_usage_header)
# In case of a fuel-driven compressor, the user may provide power interpolation data to emulate turbine power usage in results
power_interpolation_values = None
if has_fuel:
power_interpolation_values = _get_float_column_or_none(resource, power_header)
return CompressorModelSampled(
energy_usage_type=EnergyUsageType.FUEL if energy_usage_header == fuel_header else EnergyUsageType.POWER,
energy_usage_values=energy_usage_values,
rate_values=rate_values,
suction_pressure_values=suction_pressure_values,
discharge_pressure_values=discharge_pressure_values,
power_interpolation_values=power_interpolation_values,
)
def create_compressor_model(
self,
reference: str,
operational_data: CompressorOperationalTimeSeries | None = None,
) -> tuple[
CompressorTrainModel | CompressorModelSampled | CompressorWithTurbineModel,
FluidModel | list[FluidModel | None] | None,
]:
model = self._reference_service.get_compressor_model(reference)
try:
if isinstance(model, YamlSimplifiedVariableSpeedCompressorTrain):
return self._create_simplified_model_with_prepared_stages(
model=model,
operational_data=operational_data,
)
elif isinstance(model, YamlVariableSpeedCompressorTrain):
return self._create_variable_speed_compressor_train(model)
elif isinstance(model, YamlSingleSpeedCompressorTrain):
return self._create_single_speed_compressor_train(model)
elif isinstance(model, YamlCompressorWithTurbine):
return self._create_compressor_with_turbine(model, operational_data=operational_data)
elif isinstance(model, YamlVariableSpeedCompressorTrainMultipleStreamsAndPressures):
return self._create_variable_speed_compressor_train_multiple_streams_and_pressures(model)
elif isinstance(model, YamlCompressorTabularModel):
return self._create_compressor_sampled(model, reference), None
else:
assert_never(model)
except EcalcValidationException as e:
raise ModelValidationException(errors=[self._create_error(str(e), reference=reference)]) from e
class TabularModelMapper:
def __init__(self, resources: Resources, reference_service: ReferenceService, configuration: YamlValidator):
self._reference_service = reference_service
self._resources = resources
self._configuration = configuration
def _create_error(self, message: str, reference: str, key: str | None = None):
yaml_path = self._reference_service.get_yaml_path(reference)
location_keys = [*yaml_path.keys[:-1], reference] # Replace index with name
if key is not None:
key_path = yaml_path.append(key)
location_keys.append(key)
else:
key_path = yaml_path
file_context = self._configuration.get_file_context(key_path.keys)
return ModelValidationError(
message=message,
location=Location(keys=location_keys),
name=reference,
file_context=file_context,
)
def _get_resource(self, resource_name: str, reference: str) -> Resource:
resource = self._resources.get(resource_name)
if resource is None:
raise ModelValidationException(
errors=[
self._create_error(
message=f"Unable to find resource '{resource_name}'.", reference=reference, key="FILE"
)
]
)
return resource
def create_tabular_model(self, reference: str) -> TabularEnergyFunction:
tabular_model = self._reference_service.get_tabulated_model(reference)
resource = self._get_resource(tabular_model.file, reference)
try:
resource_headers = resource.get_headers()
resource_data = [resource.get_float_column(header) for header in resource_headers]
return TabularEnergyFunction(
headers=resource_headers,
data=resource_data,
)
except EcalcValidationException as e:
raise ModelValidationException(errors=[self._create_error(str(e), reference=reference)]) from e
class PumpModelMapper:
def __init__(self, resources: Resources, reference_service: ReferenceService, configuration: YamlValidator):
self._reference_service = reference_service
self._resources = resources
self._configuration = configuration
def _create_error(self, message: str, reference: str, key: str | None = None):
yaml_path = self._reference_service.get_yaml_path(reference)
location_keys = [*yaml_path.keys[:-1], reference] # Replace index with name
if key is not None:
key_path = yaml_path.append(key)
location_keys.append(key)
else:
key_path = yaml_path
file_context = self._configuration.get_file_context(key_path.keys)
return ModelValidationError(
message=message,
location=Location(keys=location_keys),
name=reference,
file_context=file_context,
)
def _get_resource(self, resource_name: str, reference: str) -> Resource:
resource = self._resources.get(resource_name)
if resource is None:
raise ModelValidationException(
errors=[
self._create_error(
message=f"Unable to find resource '{resource_name}'.", reference=reference, key="FILE"
)
]
)
return resource
def create_pump_model(self, reference: str) -> PumpModel:
model = self._reference_service.get_pump_model(reference)
resource_name = model.file
resource = self._get_resource(resource_name, reference)
try:
if isinstance(model, YamlPumpChartSingleSpeed):
return _create_pump_model_single_speed_dto_model_data(resource=resource, facility_data=model)
elif isinstance(model, YamlPumpChartVariableSpeed):
return _create_pump_chart_variable_speed_dto_model_data(resource=resource, facility_data=model)
except EcalcValidationException as e:
raise ModelValidationException(errors=[self._create_error(str(e), reference=reference)]) from e
except InvalidResourceException as e:
raise InvalidChartResourceException(
message=str(e), file_mark=e.file_mark, resource_name=resource_name
) from e
class ConsumerFunctionMapper:
def __init__(
self,
configuration: YamlValidator,
resources: Resources,
references: ReferenceService,
target_period: Period,
expression_evaluator: ExpressionEvaluator,
regularity: Regularity,
energy_usage_model: YamlTemporalModel[YamlFuelEnergyUsageModel]
| YamlTemporalModel[YamlElectricityEnergyUsageModel],
mapping_context: MappingContext,
consumer_id: UUID,
):
self._configuration = configuration
self._resources = resources
self.__references = references
self._compressor_model_mapper = CompressorModelMapper(
resources=resources, configuration=configuration, reference_service=references
)
self._tabular_model_mapper = TabularModelMapper(
resources=resources, configuration=configuration, reference_service=references
)
self._pump_model_mapper = PumpModelMapper(
resources=resources, configuration=configuration, reference_service=references
)
self._target_period = target_period
self._expression_evaluator = expression_evaluator
self._regularity = regularity
self._period_subsets = {}
self._time_adjusted_model = define_time_model_for_period(energy_usage_model, target_period=target_period)
self._mapping_context = mapping_context
self._process_service = mapping_context._process_service
self._consumer_id = consumer_id
for period in self._time_adjusted_model:
start_index, end_index = period.get_period_indices(expression_evaluator.get_periods())
period_regularity = regularity.get_subset(start_index, end_index)
period_evaluator = expression_evaluator.get_subset(start_index, end_index)
self._period_subsets[period] = (period_regularity, period_evaluator)
def _map_direct(
self,
model: YamlEnergyUsageModelDirectFuel | YamlEnergyUsageModelDirectElectricity,
consumes: ConsumptionType,