/
fluids.py
531 lines (425 loc) · 17.6 KB
/
fluids.py
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
# Copyright (c) 2020-2021 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel, and University of Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
import os
import pandas as pd
import numpy as np
from pandapipes import pp_dir
from pandapower.io_utils import JSONSerializableClass
from scipy.interpolate import interp1d
try:
import pplog as logging
except ImportError:
import logging
logger = logging.getLogger(__name__)
class Fluid(JSONSerializableClass):
"""
"""
def __init__(self, name, fluid_type, **kwargs):
"""
:param name:
:type name:
:param fluid_type:
:type fluid_type:
:param kwargs:
:type kwargs:
"""
super(Fluid, self).__init__()
self.name = name
if not isinstance(fluid_type, str) or fluid_type.lower() not in ["gas", "liquid"]:
logger.warning("The fluid %s has the fluid type %s which might cause problems in the "
"pipeflow calculation, as it expects either 'gas' or 'liquid'."
% (name, fluid_type))
self.fluid_type = fluid_type.lower()
self.is_gas = self.fluid_type == "gas"
self.all_properties = kwargs
for prop_name, prop in self.all_properties.items():
if not isinstance(prop, FluidProperty):
logger.warning("The property %s was not defined as a fluid property. This might "
"cause problems when trying to ask for values." % prop_name)
def __repr__(self):
"""
Definition of fluid representation in the console.
:return: representation of fluid in the console
:rtype: str
"""
r = "Fluid %s (%s) with properties:" % (self.name, self.fluid_type)
for key in self.all_properties.keys():
r += "\n - %s (%s)" %(key, self.all_properties[key].__class__.__name__[13:])
return r
def add_property(self, property_name, prop, overwrite=True, warn_on_duplicates=True):
"""
This function adds a new property.
:param property_name: Name of the new property
:type property_name: str
:param prop: Values for the property, for example a curve or just a constant value
:type prop: pandapipes.FluidProperty
:param overwrite: True if existing property with the same name shall be overwritten
:type overwrite: bool
:param warn_on_duplicates: True, if a warning of properties with the same name should be
returned
:type warn_on_duplicates: bool
:Example:
>>> fluid.add_property('water_density', pandapipes.FluidPropertyConstant(998.2061), overwrite=True, warn_on_duplicates=False)
"""
if property_name in self.all_properties:
if warn_on_duplicates:
ow_string = "It will be overwritten." if overwrite else "It will not be replaced."
logger.warning("The property %s already exists. %s" % (property_name, ow_string))
if not overwrite:
return
self.all_properties[property_name] = prop
def get_property(self, property_name, *at_values):
"""
This function returns the value of the requested property.
:param property_name: Name of the searched property
:type property_name: str
:param at_values: Value for which the property should be returned
:type at_values:
:return: Returns property at the certain value
:rtype: pandapipes.FluidProperty
"""
if property_name not in self.all_properties:
raise UserWarning("The property %s was not defined for the fluid %s"
% (property_name, self.name))
return self.all_properties[property_name].get_property(*at_values)
def get_density(self, temperature):
"""
This function returns the density at a certain temperature.
:param temperature: Temperature at which the density is queried
:type temperature: float
:return: Density at the required temperature
"""
return self.get_property("density", temperature)
def get_viscosity(self, temperature):
"""
This function returns the viscosity at a certain temperature.
:param temperature: Temperature at which the viscosity is queried
:type temperature: float
:return: Viscosity at the required temperature
"""
return self.get_property("viscosity", temperature)
def get_heat_capacity(self, temperature):
"""
This function returns the heat capacity at a certain temperature.
:param temperature: Temperature at which the heat capacity is queried
:type temperature: float
:return: Heat capacity at the required temperature
"""
return self.get_property("heat_capacity", temperature)
def get_molar_mass(self):
"""
This function returns the molar mass.
:return: molar mass
"""
return self.get_property("molar_mass")
def get_compressibility(self, temperature):
"""
This function returns the compressibility at a certain temperature.
:param temperature: Temperature at which the compressibility is queried
:type temperature: float
:return: compressibility at the required temperature
"""
return self.get_property("compressibility", temperature)
def get_der_compressibility(self):
"""
This function returns the derivative of the compressibility.
:return: derivative of the compressibility
"""
return self.get_property("der_compressibility")
class FluidProperty(JSONSerializableClass):
"""
Property Base Class
"""
def __init__(self):
"""
"""
super().__init__()
def get_property(self, *args):
"""
:param arg:
:type arg:
:return:
:rtype:
"""
raise NotImplementedError("Please implement a proper fluid property!")
class FluidPropertyInterExtra(FluidProperty):
"""
Creates Property with interpolated or extrapolated values.
"""
json_excludes = JSONSerializableClass.json_excludes + ["prop_getter"]
prop_getter_entries = {"x": "x", "y": "y", "_fill_value_orig": "fill_value"}
def __init__(self, x_values, y_values, method="interpolate_extrapolate"):
"""
:param x_values:
:type x_values:
:param y_values:
:type y_values:
:param method:
:type method:
"""
super(FluidPropertyInterExtra, self).__init__()
if method.lower() == "interpolate_extrapolate":
self.prop_getter = interp1d(x_values, y_values, fill_value="extrapolate")
else:
self.prop_getter = interp1d(x_values, y_values)
def get_property(self, arg):
"""
:param arg: Name of the property and one or more values (x-values) for which the y-values of the property are to be displayed
:type arg: str, float or array
:return: y-value/s
:rtype: float, array
"""
return self.prop_getter(arg)
@classmethod
def from_path(cls, path, method="interpolate_extrapolate"):
"""
Reads a text file with temperature values in the first column and property values in
second column.
:param path: Target path of the txt file
:type path: str
:param method: Method with which the values are to be interpolated
:type method: str
:return: interpolated values
:rtype: pandapipes.FluidProperty
"""
values = np.loadtxt(path)
return cls(values[:, 0], values[:, 1], method=method)
def to_dict(self):
d = super(FluidPropertyInterExtra, self).to_dict()
d.update({k: self.prop_getter.__dict__[k] for k in self.prop_getter_entries.keys()})
# d.update({"x_values": self.prop_getter.x, "y_values": self.prop_getter.y,
# "method": "interpolate_extrapolate"
# if self.prop_getter.fill_value == "extrapolate" else None})
return d
@classmethod
def from_dict(cls, d):
obj = JSONSerializableClass.__new__(cls)
d2 = {cls.prop_getter_entries[k]: v for k, v in d.items()
if k in cls.prop_getter_entries.keys()}
d3 = {k: v for k, v in d.items() if k not in cls.prop_getter_entries.keys()}
d3["prop_getter"] = interp1d(**d2)
obj.__dict__.update(d3)
return obj
class FluidPropertyConstant(FluidProperty):
"""
Creates Property with a constant value.
"""
def __init__(self, value):
"""
:param value:
:type value:
"""
super(FluidPropertyConstant, self).__init__()
self.value = value
def get_property(self, *args):
"""
:param arg: Name of the property
:type arg: str
:return: Value of the property
:rtype: float
:Example:
>>> heat_capacity = get_fluid(net).get_property("heat_capacity")
"""
if len(args) > 1:
raise(UserWarning('Please define either none or an array-like argument'))
elif len(args) == 1:
logger.warning('One constant property has several input variables even though it is '
'independent of these')
output = np.array([self.value]) * np.ones(len(args[0]))
else:
output = np.array([self.value])
return output
@classmethod
def from_path(cls, path):
"""
Reads a text file with temperature values in the first column and property values in
second column.
:param path:
:type path:
:param method:
:type method:
:return:
:rtype:
"""
value = np.loadtxt(path).item()
return cls(value)
class FluidPropertyLinear(FluidProperty):
"""
Creates Property with a linear course.
"""
def __init__(self, slope, offset):
"""
:param slope:
:type slope:
:param offset:
:type offset:
"""
super(FluidPropertyLinear, self).__init__()
self.slope = slope
self.offset = offset
def get_property(self, arg):
"""
:param arg: Name of the property and one or more values (x-values) for which the function of the property should be calculated
:type arg: str, float or array
:return: y-value or function values
:rtype: float, array
:Example:
>>> comp_fact = get_fluid(net).get_property("compressibility", p_bar)
"""
if isinstance(arg, pd.Series):
return self.offset + self.slope * arg.values
else:
return self.offset + self.slope * np.array(arg)
@classmethod
def from_path(cls, path):
"""
Reads a text file with temperature values in the first column and property values in
second column.
:param path:
:type path:
:param method:
:type method:
:return:
:rtype:
"""
slope, offset = np.loadtxt(path)
return cls(slope, offset)
def create_constant_property(net, property_name, value, overwrite=True, warn_on_duplicates=True):
"""
Creates a property with a constant value.
:param net: Name of the network to which the property is added
:type net: pandapipesNet
:param property_name: Name of the new property
:type property_name: str
:param value: Constant value of the property
:type value: float
:param overwrite: True if existing property with the same name shall be overwritten
:type overwrite: basestring
:param warn_on_duplicates: True, if a warning of properties with the same name should be
returned
:type warn_on_duplicates: basestring
"""
prop = FluidPropertyConstant(value)
get_fluid(net).add_property(property_name, prop, overwrite=overwrite,
warn_on_duplicates=warn_on_duplicates)
return prop
def create_linear_property(net, property_name, slope, offset, overwrite=True,
warn_on_duplicates=True):
"""
Creates a property with a linear correlation.
:param net: Name of the network to which the property is added
:type net: pandapipesNet
:param property_name: Name of the new property
:type property_name: str
:param slope: Slope of the linear correlation
:type slope: float
:param offset: Offset of the linear function
:type offset: float
:param overwrite: True if existing property with the same name shall be overwritten
:type overwrite: basestring
:param warn_on_duplicates: True, if a warning of properties with the same name should be
returned
:type warn_on_duplicates: basestring
"""
prop = FluidPropertyLinear(slope, offset)
get_fluid(net).add_property(property_name, prop, overwrite=overwrite,
warn_on_duplicates=warn_on_duplicates)
return prop
def create_constant_fluid(name=None, fluid_type=None, **kwargs):
"""
Creates a constant fluid.
:param name: Name of the fluid
:type name: str
:param fluid_type: Type of the fluid
:type fluid_type: str
:param kwargs: Additional information
:return: Fluid
:rtype: Fluid
"""
properties = dict()
for prop_name, prop in kwargs.items():
properties[str(prop_name)] = FluidPropertyConstant(prop)
return Fluid(name=name, fluid_type=fluid_type, **properties)
def call_lib(fluid):
"""
Creates a fluid with default fluid properties.
:param fluid: Fluid which should be used
:type fluid: str
:return: Fluid - Chosen fluid with default fluid properties
:rtype: Fluid
"""
def interextra_property(prop):
return FluidPropertyInterExtra.from_path(
os.path.join(pp_dir, "properties", fluid, prop + ".txt"))
def constant_property(prop):
return FluidPropertyConstant.from_path(
os.path.join(pp_dir, "properties", fluid, prop + ".txt"))
def linear_property(prop):
return FluidPropertyLinear.from_path(
os.path.join(pp_dir, "properties", fluid, prop + ".txt"))
liquids = ["water"]
gases = ["air", "lgas", "hgas", "hydrogen", "methane"]
if fluid == "natural_gas":
logger.error("'natural_gas' is ambigious. Please choose 'hgas' or 'lgas' "
"(high- or low calorific natural gas)")
if fluid not in liquids and fluid not in gases:
raise AttributeError("Fluid '%s' not found in the fluid library. It might not be "
"implemented yet." % fluid)
phase = "liquid" if fluid in liquids else "gas"
density = interextra_property("density")
viscosity = interextra_property("viscosity")
heat_capacity = interextra_property("heat_capacity")
molar_mass = constant_property("molar_mass")
der_compr = constant_property("der_compressibility")
compr = linear_property("compressibility")
if (phase == 'gas') & (fluid != 'air'):
lhv = constant_property("lower_heating_value")
hhv = constant_property("higher_heating_value")
return Fluid(fluid, phase, density=density, viscosity=viscosity,
heat_capacity=heat_capacity, molar_mass=molar_mass,
compressibility=compr, der_compressibility=der_compr, lhv=lhv, hhv=hhv)
else:
return Fluid(fluid, phase, density=density, viscosity=viscosity,
heat_capacity=heat_capacity, molar_mass=molar_mass, compressibility=compr,
der_compressibility=der_compr)
def get_fluid(net):
"""
This function shows which fluid is used in the net.
:param net: Current network
:type net: pandapipesNet
:return: Fluid - Name of the fluid which is used in the current network
:rtype: Fluid
"""
if "fluid" not in net or net["fluid"] is None:
raise UserWarning("There is no fluid defined for the given net!")
fluid = net["fluid"]
if not isinstance(fluid, Fluid):
logger.warning("The fluid in this net is not of the pandapipes Fluid type. This could lead"
" to errors, as some components might depend on this structure")
return fluid
def _add_fluid_to_net(net, fluid, overwrite=True):
"""
Adds a fluid to a net. If overwrite is False, a warning is printed and the fluid is not set.
:param net: The pandapipes network for which to set fluid
:type net: pandapipesNet
:param fluid: fluid which to insert into the network
:type fluid: Fluid
:param overwrite: If True, an existing fluid will just be overwritten, otherwise a warning is\
printed out and the fluid is not reset.
:type overwrite: bool, default True
:return: No output.
:type: None
"""
if "fluid" in net and net["fluid"] is not None and not overwrite:
fluid_msg = "an existing fluid" if not hasattr(net["fluid"], "name") \
else "the fluid %s" % net["fluid"].name
logger.warning("The fluid %s would replace %s and thus cannot be created. Try to set "
"overwrite to True" % (fluid.name, fluid_msg))
return
if isinstance(fluid, str):
logger.warning("Instead of a pandapipes.Fluid, a string ('%s') was passed to the fluid "
"argument. Internally, it will be passed to call_lib(fluid) to get the "
"respective pandapipes.Fluid." %fluid)
fluid = call_lib(fluid)
net["fluid"] = fluid