-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathprocessTools.py
More file actions
5881 lines (4953 loc) · 196 KB
/
processTools.py
File metadata and controls
5881 lines (4953 loc) · 196 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
"""Process simulation tools for NeqSim.
This module provides Python wrapper functions for creating and running
process simulations using the NeqSim Java library. It includes equipment
like compressors, pumps, heat exchangers, separators, and more.
Four Approaches for Process Simulation
======================================
NeqSim Python offers four ways to build process simulations:
1. **Python Wrappers with Global Process** (Recommended for beginners)
Simple functions that auto-add equipment to a global process.
2. **ProcessContext** (Recommended for production)
Context manager with its own process - supports multiple processes.
3. **ProcessBuilder** (Fluent API)
Chainable builder pattern - great for configuration-driven design.
4. **Direct Java Access** (Full control)
Direct jneqsim access for advanced features.
Approach 1: Python Wrappers (Global Process)
--------------------------------------------
Simple functions that automatically add equipment to a global process.
Use clearProcess() to reset, runProcess() to execute.
>>> from neqsim.thermo import fluid
>>> from neqsim.process import stream, compressor, runProcess, clearProcess
>>>
>>> clearProcess()
>>> my_fluid = fluid('srk')
>>> my_fluid.addComponent('methane', 1.0)
>>> my_fluid.setTemperature(30.0, 'C')
>>> my_fluid.setPressure(10.0, 'bara')
>>>
>>> inlet = stream('inlet', my_fluid)
>>> comp = compressor('compressor1', inlet, pres=50.0)
>>> runProcess()
>>> print(f"Power: {comp.getPower()/1e6:.2f} MW")
Pros: Concise, readable, great for learning and prototyping
Cons: Global state limits to one process at a time
Approach 2: ProcessContext (Explicit Process Management)
---------------------------------------------------------
Context manager that creates its own ProcessSystem. Supports multiple
independent processes running simultaneously.
>>> from neqsim.thermo import fluid
>>> from neqsim.process import ProcessContext
>>>
>>> with ProcessContext("Compression") as ctx:
... my_fluid = fluid('srk')
... my_fluid.addComponent('methane', 1.0)
... my_fluid.setPressure(10.0, 'bara')
...
... inlet = ctx.stream('inlet', my_fluid)
... comp = ctx.compressor('comp1', inlet, pres=50.0)
... ctx.run()
... print(f"Power: {comp.getPower()/1e6:.2f} MW")
Pros: Multiple processes, explicit control, clean resource management
Cons: Slightly more verbose than global wrappers
Approach 3: ProcessBuilder (Fluent/Chainable API)
--------------------------------------------------
Builder pattern with method chaining. Equipment referenced by name.
Ideal for configuration-driven process construction.
>>> from neqsim.thermo import fluid
>>> from neqsim.process import ProcessBuilder
>>>
>>> my_fluid = fluid('srk')
>>> my_fluid.addComponent('methane', 1.0)
>>> my_fluid.setPressure(10.0, 'bara')
>>>
>>> process = (ProcessBuilder("Compression")
... .add_stream('inlet', my_fluid)
... .add_compressor('comp1', 'inlet', pressure=50.0)
... .run())
>>>
>>> print(f"Power: {process.get('comp1').getPower()/1e6:.2f} MW")
Pros: Very readable, chainable, equipment by name, declarative style
Cons: Less direct access during construction
Approach 4: Direct Java Access
-------------------------------
Create and manage ProcessSystem objects explicitly using jneqsim.
>>> from neqsim import jneqsim
>>> from neqsim.thermo import fluid
>>>
>>> my_fluid = fluid('srk')
>>> my_fluid.addComponent('methane', 1.0)
>>> my_fluid.setPressure(10.0, 'bara')
>>>
>>> inlet = jneqsim.process.equipment.stream.Stream('inlet', my_fluid)
>>> comp = jneqsim.process.equipment.compressor.Compressor('comp1', inlet)
>>> comp.setOutletPressure(50.0)
>>>
>>> process = jneqsim.process.processmodel.ProcessSystem()
>>> process.add(inlet)
>>> process.add(comp)
>>> process.run()
Pros: Full access to all Java features, maximum flexibility
Cons: Verbose, requires Java knowledge
Hybrid Approach: Wrappers with process= Parameter
--------------------------------------------------
Wrapper functions accept an optional process= parameter for explicit
process control while keeping concise syntax:
>>> from neqsim.process import stream, compressor, newProcess
>>>
>>> my_process = newProcess('MyProcess')
>>> inlet = stream('inlet', my_fluid, process=my_process)
>>> comp = compressor('comp1', inlet, pres=50.0, process=my_process)
>>> my_process.run()
Choosing an Approach
--------------------
+----------------------------------+--------------------------------+
| Use Case | Recommended Approach |
+==================================+================================+
| Learning / tutorials | Wrappers (global process) |
| Jupyter notebooks | Wrappers (global process) |
| Quick prototyping | Wrappers (global process) |
| Production applications | ProcessContext |
| Multiple parallel processes | ProcessContext |
| Configuration-driven design | ProcessBuilder |
| Full Java API access | Direct jneqsim |
+----------------------------------+--------------------------------+
Available Equipment
-------------------
Streams: stream, virtualstream, neqstream, energystream
Separation: separator, separator3phase, gasscrubber, filters
Compression: compressor, pump, expander
Heat Transfer: heater, cooler, heatExchanger
Valves: valve, safety_valve
Mixing/Splitting: mixer, phasemixer, splitter, compsplitter, staticmixer
Pipelines: pipe, pipeline, beggs_brill_pipe, wellflow
Columns: distillationColumn, simpleTEGAbsorber, waterStripperColumn
Control: calculator, setpoint, adjuster, flowrateadjuster, setter, flowsetter
Special: ejector, flare, flarestack, recycle, saturator, GORfitter
Storage: tank, simplereservoir, manifold
Measurement: waterDewPointAnalyser, hydrateEquilibriumTemperatureAnalyser
Power: windturbine, solarpanel, batterystorage, fuelcell, electrolyzer, co2electrolyzer
Classes: ProcessContext, ProcessBuilder
"""
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Any, Optional, List, Dict, Union
import pandas as pd
from jpype.types import *
from neqsim import jneqsim
processoperations = jneqsim.process.processmodel.ProcessSystem()
_loop_mode: bool = False
_YAML_SUFFIXES = {".yaml", ".yml"}
def _as_float_list(values) -> list[float]:
if values is None:
return []
if hasattr(values, "tolist"):
values = values.tolist()
return [float(v) for v in list(values)]
def _as_float_matrix(values) -> list[list[float]]:
if values is None:
return []
if hasattr(values, "tolist"):
values = values.tolist()
return [[float(v) for v in row] for row in list(values)]
def _resolve_path_in_cwd(
user_path: str,
*,
allowed_suffixes: Optional[set[str]] = None,
must_exist: bool = False,
) -> Path:
"""
Resolve a user-supplied path safely inside the current working directory.
This is used for convenience helpers that read/write local config/result files.
To avoid path traversal / arbitrary file read/write, absolute paths and paths that
escape the current working directory are rejected.
"""
if not isinstance(user_path, str):
raise TypeError("path must be a string")
if "\x00" in user_path:
raise ValueError("Path contains NUL byte.")
base_dir = os.path.abspath(os.getcwd())
resolved_str = os.path.abspath(os.path.join(base_dir, user_path))
# Ensure the normalized path is still within the base directory.
# Using `startswith` on normalized paths is recognized by CodeQL as a safe-access check.
base_prefix = base_dir + os.sep
if resolved_str.startswith(base_prefix):
pass
else:
raise ValueError(
"Path traversal outside the current working directory is not allowed."
)
resolved = Path(resolved_str)
if allowed_suffixes is not None:
suffix = resolved.suffix.lower()
if suffix not in allowed_suffixes:
allowed = ", ".join(sorted(allowed_suffixes))
raise ValueError(f"Invalid file extension '{suffix}'. Allowed: {allowed}.")
if must_exist and not resolved.is_file():
raise FileNotFoundError(f"File not found: {resolved}")
return resolved
class ProcessContext:
"""
Context manager for explicit process simulation management.
ProcessContext provides a clean way to create and manage process
simulations without relying on global state. Each context has its
own ProcessSystem, allowing multiple independent processes.
Args:
name: Name of the process (optional).
Attributes:
process: The underlying ProcessSystem object.
equipment: Dictionary of equipment by name.
Example:
>>> from neqsim.thermo import fluid
>>> from neqsim.process import ProcessContext
>>>
>>> with ProcessContext("Compression") as ctx:
... feed = fluid('srk')
... feed.addComponent('methane', 1.0)
... feed.setPressure(10.0, 'bara')
...
... inlet = ctx.stream('inlet', feed)
... comp = ctx.compressor('comp1', inlet, pres=50.0)
... ctx.run()
... print(f"Power: {comp.getPower()/1e6:.2f} MW")
Example without context manager:
>>> ctx = ProcessContext("MyProcess")
>>> inlet = ctx.stream('inlet', my_fluid)
>>> comp = ctx.compressor('comp1', inlet, pres=50.0)
>>> ctx.run()
"""
def __init__(self, name: str = ""):
"""Create a new ProcessContext with its own ProcessSystem."""
self.process = jneqsim.process.processmodel.ProcessSystem(name)
self.equipment: Dict[str, Any] = {}
self._name = name
def __enter__(self) -> "ProcessContext":
"""Enter the context manager."""
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> bool:
"""Exit the context manager."""
return False
def add(self, equipment: Any) -> Any:
"""
Add equipment to the process.
Args:
equipment: Equipment object to add.
Returns:
The equipment object (for chaining).
"""
self.process.add(equipment)
if hasattr(equipment, "getName"):
self.equipment[equipment.getName()] = equipment
return equipment
def run(self) -> "ProcessContext":
"""
Run the process simulation.
Returns:
Self for method chaining.
"""
self.process.run()
return self
def run_transient(self, dt: float, time: float) -> "ProcessContext":
"""
Run transient simulation.
Args:
dt: Time step in seconds.
time: Total simulation time in seconds.
Returns:
Self for method chaining.
"""
self.process.setTimeStep(dt)
self.process.runTransient(time)
return self
def get(self, name: str) -> Any:
"""
Get equipment by name.
Args:
name: Name of the equipment.
Returns:
The equipment object.
"""
return self.equipment.get(name)
def stream(self, name: str, thermo_system: Any, t: float = 0, p: float = 0) -> Any:
"""Create a stream and add to this process."""
if t != 0:
thermo_system.setTemperature(t)
if p != 0:
thermo_system.setPressure(p)
s = jneqsim.process.equipment.stream.Stream(name, thermo_system)
return self.add(s)
def separator(self, name: str, inlet_stream: Any) -> Any:
"""Create a separator and add to this process."""
sep = jneqsim.process.equipment.separator.Separator(name, inlet_stream)
return self.add(sep)
def separator3phase(self, name: str, inlet_stream: Any) -> Any:
"""Create a 3-phase separator and add to this process."""
sep = jneqsim.process.equipment.separator.ThreePhaseSeparator(
name, inlet_stream
)
return self.add(sep)
def compressor(
self, name: str, inlet_stream: Any, pres: float = 0, efficiency: float = 0.75
) -> Any:
"""Create a compressor and add to this process."""
comp = jneqsim.process.equipment.compressor.Compressor(name, inlet_stream)
if pres > 0:
comp.setOutletPressure(pres)
comp.setIsentropicEfficiency(efficiency)
return self.add(comp)
def pump(
self, name: str, inlet_stream: Any, pres: float = 0, efficiency: float = 0.75
) -> Any:
"""Create a pump and add to this process."""
p = jneqsim.process.equipment.pump.Pump(name, inlet_stream)
if pres > 0:
p.setOutletPressure(pres)
p.setIsentropicEfficiency(efficiency)
return self.add(p)
def expander(self, name: str, inlet_stream: Any, pres: float = 0) -> Any:
"""Create an expander and add to this process."""
exp = jneqsim.process.equipment.expander.Expander(name, inlet_stream)
if pres > 0:
exp.setOutletPressure(pres)
return self.add(exp)
def valve(self, name: str, inlet_stream: Any, pres: float = 0) -> Any:
"""Create a valve and add to this process."""
v = jneqsim.process.equipment.valve.ThrottlingValve(name, inlet_stream)
if pres > 0:
v.setOutletPressure(pres)
return self.add(v)
def heater(self, name: str, inlet_stream: Any, temp: float = 0) -> Any:
"""Create a heater and add to this process."""
h = jneqsim.process.equipment.heatexchanger.Heater(name, inlet_stream)
if temp > 0:
h.setOutTemperature(temp)
return self.add(h)
def cooler(self, name: str, inlet_stream: Any, temp: float = 0) -> Any:
"""Create a cooler and add to this process."""
c = jneqsim.process.equipment.heatexchanger.Cooler(name, inlet_stream)
if temp > 0:
c.setOutTemperature(temp)
return self.add(c)
def mixer(self, name: str) -> Any:
"""Create a mixer and add to this process."""
m = jneqsim.process.equipment.mixer.Mixer(name)
return self.add(m)
def splitter(
self, name: str, inlet_stream: Any, split_factors: List[float] = None
) -> Any:
"""Create a splitter and add to this process."""
s = jneqsim.process.equipment.splitter.Splitter(name, inlet_stream)
if split_factors:
s.setSplitFactors(split_factors)
return self.add(s)
def heat_exchanger(
self, name: str, hot_stream: Any, cold_stream: Any, approach_temp: float = 10.0
) -> Any:
"""Create a heat exchanger and add to this process."""
hx = jneqsim.process.equipment.heatexchanger.HeatExchanger(
name, hot_stream, cold_stream
)
hx.setApproachTemperature(approach_temp)
return self.add(hx)
def pipe(
self, name: str, inlet_stream: Any, length: float = 100.0, diameter: float = 0.1
) -> Any:
"""Create a pipe and add to this process."""
p = jneqsim.process.equipment.pipeline.AdiabaticPipe(name, inlet_stream)
p.setLength(length)
p.setDiameter(diameter)
return self.add(p)
def recycle(self, name: str, inlet_stream: Any = None) -> Any:
"""Create a recycle and add to this process."""
r = jneqsim.process.equipment.util.Recycle(name)
if inlet_stream is not None:
r.addStream(inlet_stream)
return self.add(r)
def gas_scrubber(self, name: str, inlet_stream: Any) -> Any:
"""Create a gas scrubber and add to this process."""
scrubber = jneqsim.process.equipment.separator.GasScrubber(name, inlet_stream)
return self.add(scrubber)
def distillation_column(
self, name: str, trays: int = 5, reboiler: bool = True, condenser: bool = True
) -> Any:
"""Create a distillation column and add to this process."""
column = jneqsim.process.equipment.distillation.DistillationColumn(
trays, reboiler, condenser
)
column.setName(name)
return self.add(column)
def teg_absorber(self, name: str) -> Any:
"""Create a simple TEG absorber and add to this process."""
absorber = jneqsim.process.equipment.absorber.SimpleTEGAbsorber(name)
return self.add(absorber)
def water_stripper_column(self, name: str) -> Any:
"""Create a water stripper column and add to this process."""
column = jneqsim.process.equipment.absorber.WaterStripperColumn(name)
return self.add(column)
def component_splitter(
self, name: str, inlet_stream: Any, split_factors: List[float] = None
) -> Any:
"""Create a component splitter and add to this process."""
splitter = jneqsim.process.equipment.splitter.ComponentSplitter(
name, inlet_stream
)
if split_factors:
splitter.setSplitFactors(split_factors)
return self.add(splitter)
def saturator(self, name: str, inlet_stream: Any) -> Any:
"""Create a stream saturator and add to this process."""
sat = jneqsim.process.equipment.util.StreamSaturatorUtil(name, inlet_stream)
return self.add(sat)
def filters(self, name: str, inlet_stream: Any) -> Any:
"""Create a filter and add to this process."""
f = jneqsim.process.equipment.filter.Filter(name, inlet_stream)
return self.add(f)
def calculator(self, name: str) -> Any:
"""Create a calculator and add to this process."""
calc = jneqsim.process.equipment.util.Calculator(name)
return self.add(calc)
def setpoint(
self,
name: str,
target_equipment: Any,
target_variable: str,
source_equipment: Any,
) -> Any:
"""Create a setpoint controller and add to this process."""
sp = jneqsim.process.equipment.util.SetPoint(
name, target_equipment, target_variable, source_equipment
)
return self.add(sp)
def adjuster(
self,
name: str,
target_equipment: Any = None,
target_variable: str = None,
target_value: float = None,
) -> Any:
"""Create an adjuster and add to this process."""
adj = jneqsim.process.equipment.util.Adjuster(name)
if target_equipment is not None and target_variable is not None:
adj.setAdjustedVariable(target_equipment, target_variable)
if target_value is not None:
adj.setTargetValue(target_value)
return self.add(adj)
def ejector(self, name: str, motive_stream: Any, suction_stream: Any) -> Any:
"""Create an ejector and add to this process."""
ej = jneqsim.process.equipment.ejector.Ejector(
name, motive_stream, suction_stream
)
return self.add(ej)
def flare(self, name: str, inlet_stream: Any = None) -> Any:
"""Create a flare and add to this process."""
f = jneqsim.process.equipment.flare.Flare(name)
if inlet_stream is not None:
f.addStream(inlet_stream)
return self.add(f)
def tank(self, name: str, inlet_stream: Any = None) -> Any:
"""Create a tank and add to this process."""
t = jneqsim.process.equipment.tank.Tank(name)
if inlet_stream is not None:
t.addStream(inlet_stream)
return self.add(t)
class ProcessBuilder:
"""
Fluent builder for constructing process simulations.
ProcessBuilder provides a chainable API for building processes
step by step. Equipment is referenced by name, making it easy
to construct processes from configuration data.
QUICK START
===========
Basic usage follows a simple pattern:
1. Create a fluid (thermodynamic system)
2. Create a ProcessBuilder
3. Chain equipment additions using the fluent API
4. Call .run() to execute the simulation
5. Access results via .get() or .results()
Example::
from neqsim.thermo import fluid
from neqsim.process import ProcessBuilder
# Create feed fluid
feed = fluid('srk')
feed.addComponent('methane', 0.9)
feed.addComponent('ethane', 0.1)
feed.setMolarFlowRate(100.0, 'mol/sec')
feed.setTemperature(25.0, 'C')
feed.setPressure(10.0, 'bara')
# Build and run process
process = (
ProcessBuilder("My Process")
.add_stream('feed', feed)
.add_compressor('comp', 'feed', outlet_pressure=50.0)
.add_cooler('cooler', 'comp', outlet_temperature=30.0)
.add_separator('sep', 'cooler')
.run()
)
# Access results
print(f"Compressor power: {process.get('comp').getPower()/1e3:.1f} kW")
print(f"Gas out temp: {process.get('sep').getGasOutStream().getTemperature('C'):.1f} C")
FLUENT API PATTERN
==================
All add_* methods return ``self``, enabling method chaining::
builder = (
ProcessBuilder()
.add_stream(...)
.add_compressor(...)
.add_cooler(...)
.run()
)
EQUIPMENT CONNECTIONS
=====================
Equipment is connected by referencing upstream equipment by name.
The builder automatically gets the appropriate outlet stream.
**Basic connection** - just use the equipment name::
.add_compressor('comp', inlet='feed') # Gets feed's outlet
.add_cooler('cooler', inlet='comp') # Gets comp's outlet
**Separator outlets** - use dot notation for specific outlets::
.add_separator('sep', inlet='cooler')
.add_compressor('gas_comp', inlet='sep.gas') # Gas outlet
.add_pump('oil_pump', inlet='sep.oil') # Oil outlet
.add_pump('water_pump', inlet='sep.water') # Water outlet (3-phase)
**Available outlet types**:
- ``.gas`` or ``.vapor`` - gas/vapor phase outlet
- ``.liquid`` - liquid outlet (2-phase separator)
- ``.oil`` - oil outlet (3-phase separator)
- ``.water`` or ``.aqueous`` - water outlet (3-phase separator)
- ``.out`` - generic outlet (VirtualStream, etc.)
EQUIPMENT CATEGORIES
====================
**Streams**::
.add_stream(name, fluid, temperature=None, pressure=None,
flow_rate=None, flow_unit='kg/sec')
.add_virtual_stream(name, source=None, flow_rate=None, ...)
.add_neq_stream(name, fluid) # Non-equilibrium stream
.add_energy_stream(name) # Energy/duty stream
.add_well_stream(name, fluid) # Well stream
**Separation**::
.add_separator(name, inlet) # 2-phase separator
.add_three_phase_separator(name, inlet) # 3-phase separator
.add_separator_with_dimensions(name, inlet, inner_diameter, length)
.add_gas_scrubber(name, inlet)
.add_gas_scrubber_with_options(name, inlet, ...)
**Compression**::
.add_compressor(name, inlet, outlet_pressure=None, isentropic_efficiency=None)
.add_compressor_with_chart(name, inlet) # With performance curves
.add_polytopic_compressor(name, inlet, outlet_pressure, efficiency)
**Pumping**::
.add_pump(name, inlet, outlet_pressure=None, efficiency=None)
**Heat Transfer**::
.add_heater(name, inlet, outlet_temperature=None)
.add_cooler(name, inlet, outlet_temperature=None)
.add_heat_exchanger(name, hot_inlet=None, cold_inlet=None)
**Pressure Control**::
.add_valve(name, inlet, outlet_pressure=None)
.add_valve_with_options(name, inlet, outlet_pressure, cv=None, ...)
**Mixing/Splitting**::
.add_mixer(name, inlets=None) # List of inlet names
.add_static_mixer(name, inlets=None)
.add_splitter(name, inlet, split_fractions=None)
.add_splitter_with_flowrates(name, inlet, flowrates, flow_unit)
**Pipelines**::
.add_pipe(name, inlet, length=None, diameter=None)
.add_beggs_brill_pipe(name, inlet, length, elevation, diameter, ...)
.add_two_phase_pipe(name, inlet, length, elevation, diameter, ...)
**Distillation/Absorption**::
.add_distillation_column(name, trays=5, reboiler=True, condenser=True)
.add_teg_absorber(name)
.add_simple_absorber(name, inlet_gas=None, inlet_liquid=None)
.add_water_stripper(name)
**Process Control**::
.add_setpoint(name, source_equipment, source_variable, target_equipment,
target_variable, target_value)
.add_adjuster(name, target_equipment, target_variable, target_value,
adjust_equipment, adjust_variable)
.add_calculator(name)
.add_pid_controller(name, transmitter=None, valve=None, setpoint=None, ...)
**Measurement**::
.add_pressure_transmitter(name, equipment, measurement_point='outlet')
.add_temperature_transmitter(name, equipment, measurement_point='outlet')
.add_flow_transmitter(name, equipment, measurement_point='outlet')
.add_level_transmitter(name, separator)
**Other Equipment**::
.add_ejector(name, motive_inlet=None, suction_inlet=None)
.add_flare(name, inlet=None)
.add_tank(name, inlet=None)
.add_saturator(name, inlet=None)
.add_filter(name, inlet=None)
.add_reactor(name, inlet) # Gibbs reactor
.add_component_splitter(name, inlet, split_factors=None)
RECYCLE LOOPS
=============
Recycles handle "streams that go back" - a common challenge because you
need to reference equipment that doesn't exist yet.
**The Pattern**: Create a virtual stream (initial guess) FIRST, build
forward through the process, then connect the actual output back.
Example - Anti-surge recycle::
process = (
ProcessBuilder()
.add_stream('feed', fluid, flow_rate=100, flow_unit='kg/hr')
# Step 1: Create virtual stream as initial guess
.add_virtual_stream('recycle_guess', source='feed',
flow_rate=5.0, flow_unit='kg/hr')
# Step 2: Build forward using the guess
.add_mixer('mixer', inlets=['feed', 'recycle_guess.out'])
.add_compressor('compressor', inlet='mixer', outlet_pressure=50)
.add_cooler('cooler', inlet='compressor', outlet_temperature=30)
.add_separator('separator', inlet='cooler')
# Step 3: Connect actual output back to virtual stream
.add_recycle('antisurge',
inlet='separator.liquid', # actual stream
outlet='recycle_guess.out', # virtual stream
tolerance=1e-6)
.run()
)
**Alternative helper methods**::
# Using setup/close pattern
.setup_recycle_loop('my_recycle', 'recycle_guess', 'feed',
initial_flow=5.0, initial_flow_unit='kg/hr')
# ... build process ...
.close_recycle_loop('my_recycle', 'separator.liquid')
CONFIGURATION & ACCESS
======================
**Configure equipment after creation**::
.configure('equipment_name', lambda eq: eq.setSomeProperty(value))
**Access equipment**::
process.get('compressor') # Get Java equipment object
process.get('separator').run() # Run single equipment
process['compressor'] # Dict-style access
**Get results**::
process.results() # Returns underlying ProcessSystem
process.run() # Run simulation, returns self
BUILDING FROM CONFIG
====================
For dynamic process construction, use ``add()`` or ``add_from_config()``::
# Single equipment with type string
builder.add('compressor', 'comp1', inlet='feed', outlet_pressure=50)
# From configuration list
config = [
{'type': 'stream', 'name': 'feed', 'fluid': my_fluid},
{'type': 'compressor', 'name': 'comp', 'inlet': 'feed',
'outlet_pressure': 50},
{'type': 'cooler', 'name': 'cooler', 'inlet': 'comp',
'outlet_temperature': 30},
]
builder.add_from_config(config, fluids={'feed_fluid': my_fluid})
COMPLETE EXAMPLES
=================
**Gas Compression Train**::
feed = fluid('srk')
feed.addComponent('methane', 0.85)
feed.addComponent('ethane', 0.10)
feed.addComponent('propane', 0.05)
feed.setMolarFlowRate(1000, 'mol/sec')
feed.setTemperature(25, 'C')
feed.setPressure(5, 'bara')
process = (
ProcessBuilder("Compression Train")
.add_stream('inlet', feed)
.add_gas_scrubber('scrubber', 'inlet')
.add_compressor('stage1', 'scrubber.gas', outlet_pressure=15)
.add_cooler('ic1', 'stage1', outlet_temperature=35)
.add_gas_scrubber('kd1', 'ic1')
.add_compressor('stage2', 'kd1.gas', outlet_pressure=45)
.add_cooler('ic2', 'stage2', outlet_temperature=35)
.add_gas_scrubber('kd2', 'ic2')
.add_compressor('stage3', 'kd2.gas', outlet_pressure=120)
.add_cooler('aftercooler', 'stage3', outlet_temperature=40)
.run()
)
total_power = sum(
process.get(f'stage{i}').getPower() for i in [1, 2, 3]
) / 1e6
print(f"Total compression power: {total_power:.2f} MW")
**Oil/Gas Separation**::
wellstream = fluid('srk')
# ... configure wellstream ...
process = (
ProcessBuilder("Separation")
.add_stream('well', wellstream)
.add_heater('heater', 'well', outlet_temperature=80)
.add_three_phase_separator('hp_sep', 'heater')
.add_valve('gas_valve', 'hp_sep.gas', outlet_pressure=20)
.add_valve('oil_valve', 'hp_sep.oil', outlet_pressure=5)
.add_three_phase_separator('lp_sep', 'oil_valve')
.add_pump('export_pump', 'lp_sep.oil', outlet_pressure=30)
.run()
)
**With Recycle (TEG Dehydration)**::
process = (
ProcessBuilder("TEG Dehydration")
.add_stream('wet_gas', wet_gas_fluid)
.add_virtual_stream('lean_teg_recycle', source='teg_stream',
flow_rate=1000, flow_unit='kg/hr')
.add_teg_absorber('absorber')
.configure('absorber', lambda a: (
a.addGasInStream(process.get('wet_gas').getOutletStream()),
a.addSolventInStream(process.get('lean_teg_recycle').getOutStream())
))
# ... regeneration equipment ...
.add_recycle('teg_recycle',
inlet='teg_cooler',
outlet='lean_teg_recycle.out',
tolerance=1e-4)
.run()
)
See Also
--------
neqsim.thermo.fluid : Create thermodynamic systems
neqsim.process.newProcess : Alternative process creation function
"""
def __init__(self, name: str = ""):
"""Create a new ProcessBuilder."""
self.process = jneqsim.process.processmodel.ProcessSystem(name)
self.equipment: Dict[str, Any] = {}
self._name = name
def _get_outlet(self, ref: Union[str, Any]) -> Any:
"""
Get outlet stream from equipment reference (name or object).
Supports dot notation for selecting specific outlets:
Separators:
- 'separator.gas' or 'separator.vapor' - gas/vapor outlet
- 'separator.liquid' - liquid outlet (2-phase separator)
- 'separator.oil' - oil outlet (3-phase separator)
- 'separator.water' or 'separator.aqueous' - water outlet
Splitters and Manifolds:
- 'splitter.split_0', 'splitter.split_1', etc. - numbered outlets
- 'manifold.split_0', 'manifold.split_1', etc. - numbered outlets
- 'manifold.mixed' - mixed stream (before splitting)
Other:
- 'virtual_stream.out' - output from VirtualStream/Recycle
Examples:
>>> builder.add_compressor('comp', 'sep.gas', pressure=100)
>>> builder.add_pump('pump', 'sep.oil', pressure=50)
>>> builder.add_mixer('mixer', inlets=['feed', 'recycle_guess.out'])
>>> builder.add_valve('valve1', 'splitter.split_0', pressure=10)
>>> builder.add_compressor('comp1', 'manifold.split_0', pressure=100)
"""
if isinstance(ref, str):
# Check for dot notation (e.g., 'separator.gas')
if "." in ref:
parts = ref.split(".", 1)
equip_name = parts[0]
outlet_type = parts[1].lower()
equip = self.equipment.get(equip_name)
if equip is None:
raise ValueError(f"Equipment '{equip_name}' not found")
# Handle VirtualStream .out notation
if outlet_type == "out":
if hasattr(equip, "getOutStream"):
return equip.getOutStream()
elif hasattr(equip, "getOutletStream"):
return equip.getOutletStream()
raise ValueError(
f"Equipment '{equip_name}' does not have an output stream method"
)
# Handle manifold mixed stream outlet (.mixed)
if outlet_type == "mixed":
if hasattr(equip, "getMixedStream"):
return equip.getMixedStream()
raise ValueError(
f"Equipment '{equip_name}' does not have a mixed stream outlet"
)
# Handle splitter/manifold outlets (.split_0, .split_1, etc.)
if outlet_type.startswith("split_"):
if hasattr(equip, "getSplitStream"):
try:
index = int(outlet_type.replace("split_", ""))
split_stream = equip.getSplitStream(index)
if split_stream is not None:
return split_stream
raise ValueError(
f"Equipment '{equip_name}' does not have outlet at index {index}"
)
except ValueError as e:
if "does not have outlet" in str(e):
raise
raise ValueError(
f"Invalid splitter outlet format: '{outlet_type}'. Use 'split_0', 'split_1', etc."
)
raise ValueError(
f"Equipment '{equip_name}' is not a splitter or manifold"
)
# Map outlet type to method
outlet_methods = {
"gas": ["getGasOutStream", "getOutletStream"],
"vapor": ["getGasOutStream", "getOutletStream"],
"liquid": ["getLiquidOutStream", "getOilOutStream"],
"oil": ["getOilOutStream", "getLiquidOutStream"],
"water": ["getWaterOutStream", "getAqueousOutStream"],
"aqueous": ["getWaterOutStream", "getAqueousOutStream"],
}
if outlet_type not in outlet_methods:
raise ValueError(
f"Unknown outlet type '{outlet_type}'. "
f"Valid types: {list(outlet_methods.keys()) + ['out', 'mixed', 'split_N']}"
)
for method_name in outlet_methods[outlet_type]:
if hasattr(equip, method_name):
return getattr(equip, method_name)()
raise ValueError(
f"Equipment '{equip_name}' does not have a '{outlet_type}' outlet"
)
# Standard lookup without dot notation
equip = self.equipment.get(ref)
if equip is None:
raise ValueError(f"Equipment '{ref}' not found")
if hasattr(equip, "getOutletStream"):
return equip.getOutletStream()
elif hasattr(equip, "getOutStream"):
return equip.getOutStream()
elif hasattr(equip, "getGasOutStream"):
return equip.getGasOutStream()
return equip
return ref
def add_stream(
self,
name: str,
thermo_system: Any,
temperature: float = None,
pressure: float = None,
flow_rate: float = None,
flow_unit: str = "kg/sec",