File: compressible.py

package info (click to toggle)
python-fluids 1.0.27-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 13,384 kB
  • sloc: python: 59,459; f90: 1,033; javascript: 49; makefile: 47
file content (1942 lines) | stat: -rw-r--r-- 76,268 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
"""Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017, 2018, 2019, 2020 Caleb Bell <Caleb.Andrew.Bell@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

This module contains equations for modeling flow where density changes
significantly during the process - compressible flow. Also included are
equations for choked flow - the phenomenon where the velocity of a fluid
reaches its speed of sound.

For reporting bugs, adding feature requests, or submitting pull requests,
please use the `GitHub issue tracker <https://github.com/CalebBell/fluids/>`_
or contact the author at Caleb.Andrew.Bell@gmail.com.


.. contents:: :local:

Compression Processes
---------------------
.. autofunction:: isothermal_work_compression
.. autofunction:: isentropic_work_compression
.. autofunction:: isentropic_T_rise_compression
.. autofunction:: isentropic_efficiency
.. autofunction:: polytropic_exponent

Compressible Flow
-----------------
.. autofunction:: isothermal_gas

Empirical Compressible Flow
---------------------------
.. autofunction:: Panhandle_A
.. autofunction:: Panhandle_B
.. autofunction:: Weymouth
.. autofunction:: Spitzglass_high
.. autofunction:: Spitzglass_low
.. autofunction:: Oliphant
.. autofunction:: Fritzsche
.. autofunction:: Muller
.. autofunction:: IGT

Critical Flow
-------------
.. autofunction:: T_critical_flow
.. autofunction:: P_critical_flow
.. autofunction:: is_critical_flow
.. autofunction:: P_isothermal_critical_flow
.. autofunction:: P_upstream_isothermal_critical_flow

Stagnation Point
----------------
.. autofunction:: stagnation_energy
.. autofunction:: P_stagnation
.. autofunction:: T_stagnation
.. autofunction:: T_stagnation_ideal

"""

from math import exp, isinf, log, pi, sqrt

from fluids.constants import R
from fluids.numerics import brenth, lambertw, secant

__all__ = ['Panhandle_A', 'Panhandle_B', 'Weymouth', 'Spitzglass_high',
           'Spitzglass_low', 'Oliphant', 'Fritzsche', 'Muller', 'IGT', 'isothermal_gas',
           'isothermal_work_compression', 'polytropic_exponent',
           'isentropic_work_compression', 'isentropic_efficiency',
           'isentropic_T_rise_compression', 'T_critical_flow',
           'P_critical_flow', 'P_isothermal_critical_flow',
           'is_critical_flow', 'stagnation_energy', 'P_stagnation',
           'T_stagnation', 'T_stagnation_ideal']

def isothermal_work_compression(P1, P2, T, Z=1.0):
    r'''Calculates the work of compression or expansion of a gas going through
    an isothermal process.

    .. math::
        W = zRT\ln\left(\frac{P_2}{P_1}\right)

    Parameters
    ----------
    P1 : float
        Inlet pressure, [Pa]
    P2 : float
        Outlet pressure, [Pa]
    T : float
        Temperature of the gas going through an isothermal process, [K]
    Z : float
        Constant compressibility factor of the gas, [-]

    Returns
    -------
    W : float
        Work performed per mole of gas compressed/expanded [J/mol]

    Notes
    -----
    The full derivation with all forms is as follows:

    .. math::
        W = \int_{P_1}^{P_2} V dP = zRT\int_{P_1}^{P_2} \frac{1}{P} dP

    .. math::
        W = zRT\ln\left(\frac{P_2}{P_1}\right) = P_1 V_1 \ln\left(\frac{P_2}
        {P_1}\right) = P_2 V_2 \ln\left(\frac{P_2}{P_1}\right)

    The substitutions are according to the ideal gas law with compressibility:

    .. math:
        PV = ZRT

    The work of compression/expansion is the change in enthalpy of the gas.
    Returns negative values for expansion and positive values for compression.

    An average compressibility factor can be used where Z changes. For further
    accuracy, this expression can be used repeatedly with small changes in
    pressure and the work from each step summed.

    This is the best possible case for compression; all actual compresssors
    require more work to do the compression.

    By making the compression take a large number of stages and cooling the gas
    between stages, this can be approached reasonable closely. Integrally
    geared compressors are often used for this purpose.

    Examples
    --------
    >>> isothermal_work_compression(1E5, 1E6, 300)
    5743.427304244769

    References
    ----------
    .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
       Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
       Professional Publishing, 2009.
    '''
    return Z*R*T*log(P2/P1)


def isentropic_work_compression(T1, k, Z=1.0, P1=None, P2=None, W=None, eta=None):
    r'''Calculation function for dealing with compressing or expanding a gas
    going through an isentropic, adiabatic process assuming constant Cp and Cv.
    The polytropic model is the same equation; just provide `n` instead of `k`
    and use a polytropic efficiency for `eta` instead of a isentropic
    efficiency. Can calculate any of the following, given all the other inputs:

    * W, Work of compression
    * P2, Pressure after compression
    * P1, Pressure before compression
    * eta, isentropic efficiency of compression

    .. math::
        W = \left(\frac{k}{k-1}\right)ZRT_1\left[\left(\frac{P_2}{P_1}
        \right)^{(k-1)/k}-1\right]/\eta_{isentropic}

    Parameters
    ----------
    T1 : float
        Initial temperature of the gas, [K]
    k : float
        Isentropic exponent of the gas (Cp/Cv) or polytropic exponent `n` to
        use this as a polytropic model instead [-]
    Z : float, optional
        Constant compressibility factor of the gas, [-]
    P1 : float, optional
        Inlet pressure, [Pa]
    P2 : float, optional
        Outlet pressure, [Pa]
    W : float, optional
        Work performed per mole of gas compressed/expanded [J/mol]
    eta : float, optional
        Isentropic efficiency of the process or polytropic efficiency of the
        process to use this as a polytropic model instead [-]

    Returns
    -------
    W, P1, P2, or eta : float
        The missing input which was solved for [base SI]

    Notes
    -----
    For the same compression ratio, this is always of larger magnitude than the
    isothermal case.

    The full derivation is as follows:

    For constant-heat capacity "isentropic" fluid,

    .. math::
        V = \frac{P_1^{1/k}V_1}{P^{1/k}}

    .. math::
        W = \int_{P_1}^{P_2} V dP = \int_{P_1}^{P_2}\frac{P_1^{1/k}V_1}
        {P^{1/k}}dP

    .. math::
        W = \frac{P_1^{1/k} V_1}{1 - \frac{1}{k}}\left[P_2^{1-1/k} -
        P_1^{1-1/k}\right]

    After performing the integration and substantial mathematical manipulation
    we can obtain:

    .. math::
        W = \left(\frac{k}{k-1}\right) P_1 V_1 \left[\left(\frac{P_2}{P_1}
        \right)^{(k-1)/k}-1\right]

    Using PV = ZRT:

    .. math::
        W = \left(\frac{k}{k-1}\right)ZRT_1\left[\left(\frac{P_2}{P_1}
        \right)^{(k-1)/k}-1\right]

    The work of compression/expansion is the change in enthalpy of the gas.
    Returns negative values for expansion and positive values for compression.

    An average compressibility factor should be used as Z changes. For further
    accuracy, this expression can be used repeatedly with small changes in
    pressure and new values of isentropic exponent, and the work from each step
    summed.

    For the polytropic case this is not necessary, as `eta` corrects for the
    simplification.

    Examples
    --------
    >>> isentropic_work_compression(P1=1E5, P2=1E6, T1=300, k=1.4, eta=0.78)
    10416.876986384483

    References
    ----------
    .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
       Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
       Professional Publishing, 2009.
    '''
    if W is None and eta is not None and P1 is not None and P2 is not None:
        return k/(k - 1.0)*Z*R*T1*((P2/P1)**((k-1.)/k) - 1.0)/eta
    elif P1 is None and eta is not None and W is not None and P2 is not None:
        return P2*(1.0 + W*eta/(R*T1*Z) - W*eta/(R*T1*Z*k))**(-k/(k - 1.0))
    elif P2 is None and eta is not None and W is not None and P1 is not None:
        return P1*(1.0 + W*eta/(R*T1*Z) - W*eta/(R*T1*Z*k))**(k/(k - 1.0))
    elif eta is None and P1 is not None and P2 is not None and W is not None:
        return R*T1*Z*k*((P2/P1)**((k - 1.0)/k) - 1.0)/(W*(k - 1.0))
    else:
        raise ValueError('Three of W, P1, P2, and eta must be specified.')


def isentropic_T_rise_compression(T1, P1, P2, k, eta=1):
    r'''Calculates the increase in temperature of a fluid which is compressed
    or expanded under isentropic, adiabatic conditions assuming constant
    Cp and Cv.  The polytropic model is the same equation; just provide `n`
    instead of `k` and use a polytropic efficienty for `eta` instead of a
    isentropic efficiency.

    .. math::
        T_2 = T_1 + \frac{\Delta T_s}{\eta_s} = T_1 \left\{1 + \frac{1}
        {\eta_s}\left[\left(\frac{P_2}{P_1}\right)^{(k-1)/k}-1\right]\right\}

    Parameters
    ----------
    T1 : float
        Initial temperature of gas [K]
    P1 : float
        Initial pressure of gas [Pa]
    P2 : float
        Final pressure of gas [Pa]
    k : float
        Isentropic exponent of the gas (Cp/Cv) or polytropic exponent `n` to
        use this as a polytropic model instead [-]
    eta : float
        Isentropic efficiency of the process or polytropic efficiency of the
        process to use this as a polytropic model instead [-]

    Returns
    -------
    T2 : float
        Final temperature of gas [K]

    Notes
    -----
    For the ideal case of `eta` = 1, the model simplifies to:

    .. math::
        \frac{T_2}{T_1} = \left(\frac{P_2}{P_1}\right)^{(k-1)/k}

    Examples
    --------
    >>> isentropic_T_rise_compression(286.8, 54050, 432400, 1.4)
    519.5230938217768

    References
    ----------
    .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
       Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
       Professional Publishing, 2009.
    .. [2] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors
       Suppliers Association, Tulsa, OK, 2012.
    '''
    dT = T1*((P2/P1)**((k - 1.0)/k) - 1.0)/eta
    return T1 + dT


def isentropic_efficiency(P1, P2, k, eta_s=None, eta_p=None):
    r'''Calculates either isentropic or polytropic efficiency from the other
    type of efficiency.

    .. math::
        \eta_s = \frac{(P_2/P_1)^{(k-1)/k}-1}
        {(P_2/P_1)^{\frac{k-1}{k\eta_p}}-1}

    .. math::
        \eta_p = \frac{\left(k - 1\right) \ln{\left (\frac{P_{2}}{P_{1}}
        \right )}}{k \ln{\left (\frac{1}{\eta_{s}} \left(\eta_{s}
        + \left(\frac{P_{2}}{P_{1}}\right)^{\frac{1}{k} \left(k - 1\right)}
        - 1\right) \right )}}

    Parameters
    ----------
    P1 : float
        Initial pressure of gas [Pa]
    P2 : float
        Final pressure of gas [Pa]
    k : float
        Isentropic exponent of the gas (Cp/Cv) [-]
    eta_s : float, optional
        Isentropic (adiabatic) efficiency of the process, [-]
    eta_p : float, optional
        Polytropic efficiency of the process, [-]

    Returns
    -------
    eta_s or eta_p : float
        Isentropic or polytropic efficiency, depending on input, [-]

    Notes
    -----
    The form for obtained `eta_p` from `eta_s` was derived with SymPy.

    Examples
    --------
    >>> isentropic_efficiency(1E5, 1E6, 1.4, eta_p=0.78)
    0.7027614191263858

    References
    ----------
    .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
       Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
       Professional Publishing, 2009.
    '''
    if eta_s is None and eta_p is not None:
        return ((P2/P1)**((k-1.0)/k)-1.0)/((P2/P1)**((k-1.0)/(k*eta_p))-1.0)
    elif eta_p is None and eta_s is not None:
        return (k - 1.0)*log(P2/P1)/(k*log(
            (eta_s + (P2/P1)**((k - 1.0)/k) - 1.0)/eta_s))
    else:
        raise ValueError('Either eta_s or eta_p is required')


def polytropic_exponent(k, n=None, eta_p=None):
    r'''Calculates one of:

        * Polytropic exponent from polytropic efficiency
        * Polytropic efficiency from the polytropic exponent

    .. math::
        n = \frac{k\eta_p}{1 - k(1-\eta_p)}

    .. math::
        \eta_p = \frac{\left(\frac{n}{n-1}\right)}{\left(\frac{k}{k-1}
        \right)} = \frac{n(k-1)}{k(n-1)}

    Parameters
    ----------
    k : float
        Isentropic exponent of the gas (Cp/Cv) [-]
    n : float, optional
        Polytropic exponent of the process [-]
    eta_p : float, optional
        Polytropic efficiency of the process, [-]

    Returns
    -------
    n or eta_p : float
        Polytropic exponent or polytropic efficiency, depending on input, [-]

    Notes
    -----

    Examples
    --------
    >>> polytropic_exponent(1.4, eta_p=0.78)
    1.5780346820809246

    References
    ----------
    .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
       Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
       Professional Publishing, 2009.
    '''
    if n is None and eta_p is not None:
        return k*eta_p/(1.0 - k*(1.0 - eta_p))
    elif eta_p is None and n is not None:
        return n*(k - 1.0)/(k*(n - 1.0))
    else:
        raise ValueError('Either n or eta_p is required')


def T_critical_flow(T, k):
    r'''Calculates critical flow temperature `Tcf` for a fluid with the
    given isentropic coefficient. `Tcf` is in a flow (with Ma=1) whose
    stagnation conditions are known. Normally used with converging/diverging
    nozzles.

    .. math::
        \frac{T^*}{T_0} = \frac{2}{k+1}

    Parameters
    ----------
    T : float
        Stagnation temperature of a fluid with Ma=1 [K]
    k : float
        Isentropic coefficient []

    Returns
    -------
    Tcf : float
        Critical flow temperature at Ma=1 [K]

    Notes
    -----
    Assumes isentropic flow.

    Examples
    --------
    Example 12.4 in [1]_:

    >>> T_critical_flow(473, 1.289)
    413.2809086937528

    References
    ----------
    .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    '''
    return T*2.0/(k + 1.0)


def P_critical_flow(P, k):
    r'''Calculates critical flow pressure `Pcf` for a fluid with the
    given isentropic coefficient. `Pcf` is in a flow (with Ma=1) whose
    stagnation conditions are known. Normally used with converging/diverging
    nozzles.

    .. math::
        \frac{P^*}{P_0} = \left(\frac{2}{k+1}\right)^{k/(k-1)}

    Parameters
    ----------
    P : float
        Stagnation pressure of a fluid with Ma=1 [Pa]
    k : float
        Isentropic coefficient []

    Returns
    -------
    Pcf : float
        Critical flow pressure at Ma=1 [Pa]

    Notes
    -----
    Assumes isentropic flow.

    Examples
    --------
    Example 12.4 in [1]_:

    >>> P_critical_flow(1400000, 1.289)
    766812.9022792266

    References
    ----------
    .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    '''
    return P*(2.0/(k + 1.))**(k/(k - 1.0))


def P_isothermal_critical_flow(P, fd, D, L):
    r'''Calculates critical flow pressure `Pcf` for a fluid flowing
    isothermally and suffering pressure drop caused by a pipe's friction factor.

    .. math::
        P_2 = P_{1} e^{\frac{1}{2 D} \left(D \left(\operatorname{LambertW}
        {\left (- e^{\frac{1}{D} \left(- D - L f_d\right)} \right )} + 1\right)
        + L f_d\right)}

    Parameters
    ----------
    P : float
        Inlet pressure [Pa]
    fd : float
        Darcy friction factor for flow in pipe [-]
    D : float
        Diameter of pipe, [m]
    L : float
        Length of pipe, [m]

    Returns
    -------
    Pcf : float
        Critical flow pressure of a compressible gas flowing from `P1` to `Pcf`
        in a tube of length L and friction factor `fd` [Pa]

    Notes
    -----
    Assumes isothermal flow. Developed based on the `isothermal_gas` model,
    using SymPy.

    The isothermal gas model is solved for maximum mass flow rate; any pressure
    drop under it is impossible due to the formation of a shock wave.

    Examples
    --------
    >>> P_isothermal_critical_flow(P=1E6, fd=0.00185, L=1000., D=0.5)
    389699.73176

    References
    ----------
    .. [1] Wilkes, James O. Fluid Mechanics for Chemical Engineers with
       Microfluidics and CFD. 2 edition. Upper Saddle River, NJ: Prentice Hall,
       2005.
    '''
    # Correct branch of lambertw found by trial and error
    lambert_term = float((lambertw(-exp((-D - L*fd)/D), -1)).real)
    return P*exp((D*(lambert_term + 1.0) + L*fd)/(2.0*D))


def P_upstream_isothermal_critical_flow(P, fd, D, L):
    """Not part of the public API. Reverses `P_isothermal_critical_flow`.

    Examples
    --------
    >>> P_upstream_isothermal_critical_flow(P=389699.7317645518, fd=0.00185,
    ... L=1000., D=0.5)
    1000000.00000
    """
    lambertw_term = float(lambertw(-exp(-(fd*L+D)/D), -1).real)
    return exp(-0.5*(D*lambertw_term+fd*L+D)/D)*P


def is_critical_flow(P1, P2, k):
    r'''Determines if a flow of a fluid driven by pressure gradient
    P1 - P2 is critical, for a fluid with the given isentropic coefficient.
    This function calculates critical flow pressure, and checks if this is
    larger than P2. If so, the flow is critical and choked.

    Parameters
    ----------
    P1 : float
        Higher, source pressure [Pa]
    P2 : float
        Lower, downstream pressure [Pa]
    k : float
        Isentropic coefficient []

    Returns
    -------
    flowtype : bool
        True if the flow is choked; otherwise False

    Notes
    -----
    Assumes isentropic flow. Uses P_critical_flow function.

    Examples
    --------
    Examples 1-2 from API 520.

    >>> is_critical_flow(670E3, 532E3, 1.11)
    False
    >>> is_critical_flow(670E3, 101E3, 1.11)
    True

    References
    ----------
    .. [1] API. 2014. API 520 - Part 1 Sizing, Selection, and Installation of
       Pressure-relieving Devices, Part I - Sizing and Selection, 9E.
    '''
    Pcf = P_critical_flow(P1, k)
    return Pcf > P2


def stagnation_energy(V):
    r'''Calculates the increase in enthalpy `dH` which is provided by a fluid's
    velocity `V`.

    .. math::
        \Delta H = \frac{V^2}{2}

    Parameters
    ----------
    V : float
        Velocity [m/s]

    Returns
    -------
    dH : float
        Incease in enthalpy [J/kg]

    Notes
    -----
    The units work out. This term is pretty small, but not trivial.

    Examples
    --------
    >>> stagnation_energy(125)
    7812.5

    References
    ----------
    .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    '''
    return 0.5*V*V


def P_stagnation(P, T, Tst, k):
    r'''Calculates stagnation flow pressure `Pst` for a fluid with the
    given isentropic coefficient and specified stagnation temperature and
    normal temperature. Normally used with converging/diverging nozzles.

    .. math::
        \frac{P_0}{P}=\left(\frac{T_0}{T}\right)^{\frac{k}{k-1}}

    Parameters
    ----------
    P : float
        Normal pressure of a fluid [Pa]
    T : float
        Normal temperature of a fluid [K]
    Tst : float
        Stagnation temperature of a fluid moving at a certain velocity [K]
    k : float
        Isentropic coefficient []

    Returns
    -------
    Pst : float
        Stagnation pressure of a fluid moving at a certain velocity [Pa]

    Notes
    -----
    Assumes isentropic flow.

    Examples
    --------
    Example 12-1 in [1]_.

    >>> P_stagnation(54050., 255.7, 286.8, 1.4)
    80772.80495900588

    References
    ----------
    .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    '''
    return P*(Tst/T)**(k/(k - 1.0))


def T_stagnation(T, P, Pst, k):
    r'''Calculates stagnation flow temperature `Tst` for a fluid with the
    given isentropic coefficient and specified stagnation pressure and
    normal pressure. Normally used with converging/diverging nozzles.

    .. math::
        T=T_0\left(\frac{P}{P_0}\right)^{\frac{k-1}{k}}

    Parameters
    ----------
    T : float
        Normal temperature of a fluid [K]
    P : float
        Normal pressure of a fluid [Pa]
    Pst : float
        Stagnation pressure of a fluid moving at a certain velocity [Pa]
    k : float
        Isentropic coefficient []

    Returns
    -------
    Tst : float
        Stagnation temperature of a fluid moving at a certain velocity [K]

    Notes
    -----
    Assumes isentropic flow.

    Examples
    --------
    Example 12-1 in [1]_.

    >>> T_stagnation(286.8, 54050, 54050*8, 1.4)
    519.5230938217768

    References
    ----------
    .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    '''
    return T*(Pst/P)**((k - 1.0)/k)


def T_stagnation_ideal(T, V, Cp):
    r'''Calculates the ideal stagnation temperature `Tst` calculated assuming
    the fluid has a constant heat capacity `Cp` and with a specified
    velocity `V` and temperature `T`.

    .. math::
        T^* = T + \frac{V^2}{2C_p}

    Parameters
    ----------
    T : float
        Tempearture [K]
    V : float
        Velocity [m/s]
    Cp : float
        Ideal heat capacity [J/kg/K]

    Returns
    -------
    Tst : float
        Stagnation temperature [J/kg]

    Examples
    --------
    Example 12-1 in [1]_.

    >>> T_stagnation_ideal(255.7, 250, 1005.)
    286.79452736318405

    References
    ----------
    .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    '''
    return T + 0.5*V*V/Cp

def isothermal_gas_err_P1(P1, fd, rho, P2, L, D, m):
    return m - isothermal_gas(rho, fd, P1=P1, P2=P2, L=L, D=D)

def isothermal_gas_err_P2(P2, rho, fd, P1, L, D, m):
    return m - isothermal_gas(rho, fd, P1=P1, P2=P2, L=L, D=D)

def isothermal_gas_err_P2_basis(P1, P2, rho, fd, m, L, D):
    return abs(P2 - isothermal_gas(rho, fd, m=m, P1=P1, P2=None, L=L, D=D))

def isothermal_gas_err_D(D, m, rho, fd, P1, P2, L):
    return m - isothermal_gas(rho, fd, P1=P1, P2=P2, L=L, D=D)

def isothermal_gas(rho, fd, P1=None, P2=None, L=None, D=None, m=None):
    r'''Calculation function for dealing with flow of a compressible gas in a
    pipeline for the complete isothermal flow equation. Can calculate any of
    the following, given all other inputs:

    * Mass flow rate
    * Upstream pressure (numerical)
    * Downstream pressure (analytical or numerical if an overflow occurs)
    * Diameter of pipe (numerical)
    * Length of pipe

    A variety of forms of this equation have been presented, differing in their
    use of the ideal gas law and choice of gas constant. The form here uses
    density explicitly, allowing for non-ideal values to be used.

    .. math::
        \dot m^2 = \frac{\left(\frac{\pi D^2}{4}\right)^2 \rho_{avg}
        \left(P_1^2-P_2^2\right)}{P_1\left(f_d\frac{L}{D} + 2\ln\frac{P_1}{P_2}
        \right)}

    Parameters
    ----------
    rho : float
        Average density of gas in pipe, [kg/m^3]
    fd : float
        Darcy friction factor for flow in pipe [-]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    m : float, optional
        Mass flow rate of gas through pipe, [kg/s]

    Returns
    -------
    m, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    The solution for P2 has the following closed form, derived using Maple:

    .. math::
        P_2={P_1 \left( {{ e}^{0.5\cdot{\frac {1}{{m}^{2}} \left( -C{m}^{2}
        +\text{ lambertW} \left(-{\frac {BP_1}{{m}^{2}}{{ e}^{-{\frac {-C{m}^{
        2}+BP_1}{{m}^{2}}}}}}\right){}{m}^{2}+BP_1 \right) }}} \right) ^{-1}}

    .. math::
       B = \frac{\pi^2 D^4}{4^2} \rho_{avg}

    .. math::
       C = f_d \frac{L}{D}

    A wide range of conditions are impossible due to choked flow. See
    `P_isothermal_critical_flow` for details. An exception is raised when
    they occur.

    The 2 multiplied by the logarithm is often shown  as a power of the
    pressure ratio; this is only the case when the pressure ratio is raised to
    the power of 2 before its logarithm is taken.

    A number of limitations exist for this model:

        * Density dependence is that of an ideal gas.
        * If calculating the pressure drop, the average gas density cannot
          be known immediately; iteration must be used to correct this.
        * The friction factor depends on both the gas density and velocity,
          so it should be solved for iteratively as well. It changes throughout
          the pipe as the gas expands and velocity increases.
        * The model is not easily adapted to include elevation effects due to
          the acceleration term included in it.
        * As the gas expands, it will change temperature slightly, further
          altering the density and friction factor.

    There are many commercial packages which perform the actual direct
    integration of the flow, such as OLGA Dynamic Multiphase Flow Simulator,
    or ASPEN Hydraulics.

    This expression has also been presented with the ideal gas assumption
    directly incorporated into it [4]_ (note R is the specific gas constant, in
    units of J/kg/K):

    .. math::
        \dot m^2 = \frac{\left(\frac{\pi D^2}{4}\right)^2
        \left(P_1^2-P_2^2\right)}{RT\left(f_d\frac{L}{D} + 2\ln\frac{P_1}{P_2}
        \right)}

    Examples
    --------
    >>> isothermal_gas(rho=11.3, fd=0.00185, P1=1E6, P2=9E5, L=1000, D=0.5)
    145.4847572636031

    References
    ----------
    .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,
       2009.
    .. [2] Kim, J. and Singh, N. "A Novel Equation for Isothermal Pipe Flow.".
       Chemical Engineering, June 2012, http://www.chemengonline.com/a-novel-equation-for-isothermal-pipe-flow/?printmode=1
    .. [3] Wilkes, James O. Fluid Mechanics for Chemical Engineers with
       Microfluidics and CFD. 2 edition. Upper Saddle River, NJ: Prentice Hall,
       2005.
    .. [4] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical
       and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.
    '''
    if m is None and P1 is not None and P2 is not None and L is not None and D is not None:
        Pcf = P_isothermal_critical_flow(P=P1, fd=fd, D=D, L=L)
        if P2 < Pcf:
            raise ValueError('Given outlet pressure is not physically possible ' # numba: delete
f'due to the formation of choked flow at P2={Pcf:f}, specified outlet pressure was {P2:f}') # numba: delete
#            raise ValueError("Not possible") # numba: uncomment
        if P2 > P1:
            raise ValueError('Specified outlet pressure is larger than the '
                             'inlet pressure; fluid will flow backwards.')
        return sqrt(0.0625*pi*pi*D**4*rho/(P1*(fd*L/D + 2.0*log(P1/P2)))*(P1*P1 - P2*P2))
    elif L is None and P1 is not None and P2 is not None and D is not None and m is not None:
        return D*(pi*pi*D**4*rho*(P1*P1 - P2*P2) - 32.0*P1*m*m*log(P1/P2))/(16.0*P1*fd*m*m)
    elif P1 is None and L is not None and P2 is not None and D is not None and m is not None:
        Pcf = P_upstream_isothermal_critical_flow(P=P2, fd=fd, D=D, L=L)

        try:
            # Use the explicit solution for P2 with different P1 guesses;
            # newton doesn't like solving for m.
            P1 = secant(isothermal_gas_err_P2_basis, (P2+Pcf)/2., args=(P2, rho, fd, m, L, D))
            if not (P2 <= P1):
                raise ValueError("Failed")
            return P1
        except:
            try:
                return brenth(isothermal_gas_err_P1, P2, Pcf, args=(fd, rho, P2, L, D, m))
            except:
                m_max = isothermal_gas(rho, fd, P1=Pcf, P2=P2, L=L, D=D)  # numba: delete
                raise ValueError(f'The desired mass flow rate of {m:f} kg/s cannot ' # numba: delete
                                 'be achieved with the specified downstream pressure; the maximum flowrate is ' # numba: delete
                                 f'{m_max:f} kg/s at an upstream pressure of {Pcf:f} Pa') # numba: delete
#                raise ValueError("Failed") # numba: uncomment
    elif P2 is None and L is not None and P1 is not None and D is not None and m is not None:
        try:
            Pcf = P_isothermal_critical_flow(P=P1, fd=fd, D=D, L=L)
            m_max = isothermal_gas(rho, fd, P1=P1, P2=Pcf, L=L, D=D)
            if not (m <= m_max):
                raise ValueError("Failed")

            C = fd*L/D
            B = (pi/4*D**2)**2*rho
            arg = -B/m**2*P1*exp(-(-C*m**2+B*P1)/m**2)
            # Consider the two real branches of the lambertw function.
            # The k=-1 branch produces the higher P2 values; the k=0 branch is
            # physically impossible.
            lambert_ans = float(lambertw(arg, k=-1).real)
            # Large overflow problem here; also divide by zero problems!
            # Fail and try a numerical solution if it doesn't work.
            if isinf(lambert_ans):
                raise ValueError("Should not be infinity")
            P2 = P1/exp((-C*m**2+lambert_ans*m**2+B*P1)/m**2/2.)
            if not (P2 < P1):
                raise ValueError("Should not be the case")
            return P2
        except:
            Pcf = P_isothermal_critical_flow(P=P1, fd=fd, D=D, L=L)
            try:
                return brenth(isothermal_gas_err_P2, Pcf, P1, args=(rho, fd, P1, L, D, m))
            except:
                m_max = isothermal_gas(rho, fd, P1=P1, P2=Pcf, L=L, D=D)
                raise ValueError('The desired mass flow rate cannot be achieved ' # numba: delete
                                 f'with the specified upstream pressure of {P1:f} Pa; the maximum flowrate is {m_max:f} ' # numba: delete
                                 f'kg/s at a downstream pressure of {Pcf:f}') # numba: delete
#                raise ValueError("Failed") # numba: uncomment
            # A solver which respects its boundaries is required here.
            # brenth cuts the time down from 2 ms to 200 mircoseconds.
            # Is is believed Pcf and P1 will always bracked the root, however
            # leave the commented code for testing
    elif D is None and P2 is not None and P1 is not None and L is not None and m is not None:
        return secant(isothermal_gas_err_D, 0.1, args=(m, rho, fd, P1, P2, L))
    else:
        raise ValueError('This function solves for either mass flow, upstream \
pressure, downstream pressure, diameter, or length; all other inputs \
must be provided.')


def Panhandle_A(SG, Tavg, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
                Ps=101325., Zavg=1.0, E=0.92):
    r'''Calculation function for dealing with flow of a compressible gas in a
    pipeline with the Panhandle A formula. Can calculate any of the following,
    given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe
    * Length of pipe

    A variety of different constants and expressions have been presented
    for the Panhandle A equation. Here, a new form is developed with all units
    in base SI, based on the work of [1]_.

    .. math::
        Q = 158.02053 E \left(\frac{T_s}{P_s}\right)^{1.0788}\left[\frac{P_1^2
        -P_2^2}{L \cdot {SG}^{0.8539} T_{avg}Z_{avg}}\right]^{0.5394}D^{2.6182}

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    [1]_'s original constant was 4.5965E-3, and it has units of km (length),
    kPa, mm (diameter), and flowrate in m^3/day.

    The form in [2]_ has the same exponents as used here, units of mm
    (diameter), kPa, km (length), and flow in m^3/hour; its leading constant is
    1.9152E-4.

    The GPSA [3]_ has a leading constant of 0.191, a bracketed power of 0.5392,
    a specific gravity power of 0.853, and otherwise the same constants.
    It is in units of mm (diameter) and kPa and m^3/day; length is stated to be
    in km, but according to the errata is in m.

    [4]_ has a leading constant of 1.198E7, a specific gravity of power of 0.8541,
    and a power of diameter which is under the root of 4.854 and is otherwise
    the same. It has units of kPa and m^3/day, but is otherwise in base SI
    units.

    [5]_ has a leading constant of 99.5211, but its reference correction has no
    exponent; other exponents are the same as here. It is entirely in base SI
    units.

    [6]_ has pressures in psi, diameter in inches, length in miles, Q in
    ft^3/day, T in degrees Rankine, and a constant of 435.87.
    Its reference condition power is 1.07881, and it has a specific gravity
    correction outside any other term with a power of 0.4604.

    Examples
    --------
    >>> Panhandle_A(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, Tavg=277.15)
    42.56082051195928

    References
    ----------
    .. [1] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,
       FL: CRC Press, 2005.
    .. [2] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,
       2009.
    .. [3] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors
       Suppliers Association, Tulsa, OK, 2012.
    .. [4] Campbell, John M. Gas Conditioning and Processing, Vol. 2: The
       Equipment Modules. 7th edition. Campbell Petroleum Series, 1992.
    .. [5] Coelho, Paulo M., and Carlos Pinho. "Considerations about Equations
       for Steady State Flow in Natural Gas Pipelines." Journal of the
       Brazilian Society of Mechanical Sciences and Engineering 29, no. 3
       (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.
    .. [6] Ikoku, Chi U. Natural Gas Production Engineering. Malabar, Fla:
       Krieger Pub Co, 1991.
    '''
    c1 = 1.0788
    c2 = 0.8539
    c3 = 0.5394
    c4 = 2.6182
    c5 = 158.0205328706957220332831680508433862787 # 45965*10**(591/1250)/864
    if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:
        return c5*E*(Ts/Ps)**c1*((P1**2 - P2**2)/(L*SG**c2*Tavg*Zavg))**c3*D**c4
    elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:
        return (Q*(Ts/Ps)**(-c1)*(SG**(-c2)*(P1**2 - P2**2)/(L*Tavg*Zavg))**(-c3)/(E*c5))**(1./c4)
    elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:
        return sqrt(L*SG**c2*Tavg*Zavg*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(1./c3) + P2**2)
    elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:
        return sqrt(-L*SG**c2*Tavg*Zavg*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(1./c3) + P1**2)
    elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:
        return SG**(-c2)*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(-1./c3)*(P1**2 - P2**2)/(Tavg*Zavg)
    else:
        raise ValueError('This function solves for either flow, upstream \
pressure, downstream pressure, diameter, or length; all other inputs \
must be provided.')


def Panhandle_B(SG, Tavg, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
                Ps=101325., Zavg=1.0, E=0.92):
    r'''Calculation function for dealing with flow of a compressible gas in a
    pipeline with the Panhandle B formula. Can calculate any of the following,
    given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe
    * Length of pipe

    A variety of different constants and expressions have been presented
    for the Panhandle B equation. Here, a new form is developed with all units
    in base SI, based on the work of [1]_.

    .. math::
        Q = 152.88116 E \left(\frac{T_s}{P_s}\right)^{1.02}\left[\frac{P_1^2
        -P_2^2}{L \cdot {SG}^{0.961} T_{avg}Z_{avg}}\right]^{0.51}D^{2.53}

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    [1]_'s original constant was 1.002E-2, and it has units of km (length),
    kPa, mm (diameter), and flowrate in m^3/day.

    The form in [2]_ has the same exponents as used here, units of mm
    (diameter), kPa, km (length), and flow in m^3/hour; its leading constant is
    4.1749E-4.

    The GPSA [3]_ has a leading constant of 0.339, and otherwise the same constants.
    It is in units of mm (diameter) and kPa and m^3/day; length is stated to be
    in km, but according to the errata is in m.

    [4]_ has a leading constant of 1.264E7, a diameter power of 4.961 which is
    also under the 0.51 power, and is otherwise the same. It has units of kPa
    and m^3/day, but is otherwise in base SI units.

    [5]_ has a leading constant of 135.8699, but its reference correction has
    no exponent and its specific gravity has a power of 0.9608; the other
    exponents are the same as here. It is entirely in base SI units.

    [6]_ has pressures in psi, diameter in inches, length in miles, Q in
    ft^3/day, T in degrees Rankine, and a constant of 737 with the exponents
    the same as here.

    Examples
    --------
    >>> Panhandle_B(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, Tavg=277.15)
    42.35366178004172

    References
    ----------
    .. [1] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,
       FL: CRC Press, 2005.
    .. [2] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,
       2009.
    .. [3] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors
       Suppliers Association, Tulsa, OK, 2012.
    .. [4] Campbell, John M. Gas Conditioning and Processing, Vol. 2: The
       Equipment Modules. 7th edition. Campbell Petroleum Series, 1992.
    .. [5] Coelho, Paulo M., and Carlos Pinho. "Considerations about Equations
       for Steady State Flow in Natural Gas Pipelines." Journal of the
       Brazilian Society of Mechanical Sciences and Engineering 29, no. 3
       (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.
    .. [6] Ikoku, Chi U. Natural Gas Production Engineering. Malabar, Fla:
       Krieger Pub Co, 1991.
    '''
    c1 = 1.02 # reference condition power
    c2 = 0.961 # sg power
    c3 = 0.51 # main power
    c4 = 2.53 # diameter power
    c5 = 152.8811634298055458624385985866624419060 # 4175*10**(3/25)/36
    if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:
        return c5*E*(Ts/Ps)**c1*((P1**2 - P2**2)/(L*SG**c2*Tavg*Zavg))**c3*D**c4
    elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:
        return (Q*(Ts/Ps)**(-c1)*(SG**(-c2)*(P1**2 - P2**2)/(L*Tavg*Zavg))**(-c3)/(E*c5))**(1./c4)
    elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:
        return sqrt(L*SG**c2*Tavg*Zavg*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(1./c3) + P2**2)
    elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:
        return sqrt(-L*SG**c2*Tavg*Zavg*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(1./c3) + P1**2)
    elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:
        return SG**(-c2)*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(-1./c3)*(P1**2 - P2**2)/(Tavg*Zavg)
    else:
        raise ValueError('This function solves for either flow, upstream \
pressure, downstream pressure, diameter, or length; all other inputs \
must be provided.')


def Weymouth(SG, Tavg, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
             Ps=101325., Zavg=1.0, E=0.92):
    r'''Calculation function for dealing with flow of a compressible gas in a
    pipeline with the Weymouth formula. Can calculate any of the following,
    given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe
    * Length of pipe

    A variety of different constants and expressions have been presented
    for the Weymouth equation. Here, a new form is developed with all units
    in base SI, based on the work of [1]_.

    .. math::
        Q = 137.32958 E \frac{T_s}{P_s}\left[\frac{P_1^2
        -P_2^2}{L \cdot {SG} \cdot T_{avg}Z_{avg}}\right]^{0.5}D^{2.667}

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    [1]_'s original constant was 3.7435E-3, and it has units of km (length),
    kPa, mm (diameter), and flowrate in m^3/day.

    The form in [2]_ has the same exponents as used here, units of mm
    (diameter), kPa, km (length), and flow in m^3/hour; its leading constant is
    1.5598E-4.

    The GPSA [3]_ has a leading constant of 0.1182, and otherwise the same constants.
    It is in units of mm (diameter) and kPa and m^3/day; length is stated to be
    in km, but according to the errata is in m.

    [4]_ has a leading constant of 1.162E7, a diameter power of 5.333 which is
    also under the 0.50 power, and is otherwise the same. It has units of kPa
    and m^3/day, but is otherwise in base SI units.

    [5]_ has a leading constant of 137.2364; the other
    exponents are the same as here. It is entirely in base SI units.

    [6]_ has pressures in psi, diameter in inches, length in miles, Q in
    ft^3/hour, T in degrees Rankine, and a constant of 18.062 with the
    exponents the same as here.

    Examples
    --------
    >>> Weymouth(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, Tavg=277.15)
    32.07729055913029

    References
    ----------
    .. [1] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,
       FL: CRC Press, 2005.
    .. [2] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,
       2009.
    .. [3] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors
       Suppliers Association, Tulsa, OK, 2012.
    .. [4] Campbell, John M. Gas Conditioning and Processing, Vol. 2: The
       Equipment Modules. 7th edition. Campbell Petroleum Series, 1992.
    .. [5] Coelho, Paulo M., and Carlos Pinho. "Considerations about Equations
       for Steady State Flow in Natural Gas Pipelines." Journal of the
       Brazilian Society of Mechanical Sciences and Engineering 29, no. 3
       (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.
    .. [6] Ikoku, Chi U. Natural Gas Production Engineering. Malabar, Fla:
       Krieger Pub Co, 1991.
    '''
    c3 = 0.5 # main power
    c4 = 2.667 # diameter power
    c5 = 137.3295809942512546732179684618143090992 # 37435*10**(501/1000)/864
    if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:
        return c5*E*(Ts/Ps)*((P1**2 - P2**2)/(L*SG*Tavg*Zavg))**c3*D**c4
    elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:
        return (Ps*Q*((P1**2 - P2**2)/(L*SG*Tavg*Zavg))**(-c3)/(E*Ts*c5))**(1./c4)
    elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:
        return sqrt(L*SG*Tavg*Zavg*(D**(-c4)*Ps*Q/(E*Ts*c5))**(1./c3) + P2**2)
    elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:
        return sqrt(-L*SG*Tavg*Zavg*(D**(-c4)*Ps*Q/(E*Ts*c5))**(1./c3) + P1**2)
    elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:
        return (D**(-c4)*Ps*Q/(E*Ts*c5))**(-1./c3)*(P1**2 - P2**2)/(SG*Tavg*Zavg)
    else:
        raise ValueError('This function solves for either flow, upstream \
pressure, downstream pressure, diameter, or length; all other inputs \
must be provided.')


def _to_solve_Spitzglass_high(D, Q, SG, Tavg, L, P1, P2, Ts, Ps, Zavg, E):
     return Q - Spitzglass_high(SG=SG, Tavg=Tavg, L=L, D=D,
                                  P1=P1, P2=P2, Ts=Ts, Ps=Ps,Zavg=Zavg, E=E)

def Spitzglass_high(SG, Tavg, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
                Ps=101325., Zavg=1.0, E=1.):
    r'''Calculation function for dealing with flow of a compressible gas in a
    pipeline with the Spitzglass (high pressure drop) formula. Can calculate
    any of the following, given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe (numerical solution)
    * Length of pipe

    A variety of different constants and expressions have been presented
    for the Spitzglass (high pressure drop) formula. Here, the form as in [1]_
    is used but with a more precise metric conversion from inches to m.

    .. math::
        Q = 125.1060 E \left(\frac{T_s}{P_s}\right)\left[\frac{P_1^2
        -P_2^2}{L \cdot {SG} T_{avg}Z_{avg} (1 + 0.09144/D + \frac{150}{127}D)}
        \right]^{0.5}D^{2.5}

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    This equation is often presented without any correction for reference
    conditions for specific gravity.

    This model is also presented in [2]_ with a leading constant of 1.0815E-2,
    the same exponents as used here, units of mm  (diameter), kPa, km (length),
    and flow in m^3/hour.

    Examples
    --------
    >>> Spitzglass_high(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, Tavg=277.15)
    29.42670246281681

    References
    ----------
    .. [1] Coelho, Paulo M., and Carlos Pinho. "Considerations about Equations
       for Steady State Flow in Natural Gas Pipelines." Journal of the
       Brazilian Society of Mechanical Sciences and Engineering 29, no. 3
       (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.
    .. [2] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,
       FL: CRC Press, 2005.
    '''
    c3 = 1.181102362204724409448818897637795275591 # 0.03/inch or 150/127
    c4 = 0.09144
    c5 = 125.1060
    if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:
        return (c5*E*Ts/Ps*D**2.5*sqrt((P1**2-P2**2)
                        /(L*SG*Zavg*Tavg*(1 + c4/D + c3*D))))
    elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:
        return secant(_to_solve_Spitzglass_high, 0.5, args=(Q, SG, Tavg, L, P1, P2, Ts, Ps, Zavg, E))
    elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:
        return sqrt((D**6*E**2*P2**2*Ts**2*c5**2
                         + D**2*L*Ps**2*Q**2*SG*Tavg*Zavg*c3
                         + D*L*Ps**2*Q**2*SG*Tavg*Zavg
                         + L*Ps**2*Q**2*SG*Tavg*Zavg*c4)/(D**6*E**2*Ts**2*c5**2))
    elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:
        return sqrt((D**6*E**2*P1**2*Ts**2*c5**2
                         - D**2*L*Ps**2*Q**2*SG*Tavg*Zavg*c3
                         - D*L*Ps**2*Q**2*SG*Tavg*Zavg
                         - L*Ps**2*Q**2*SG*Tavg*Zavg*c4)/(D**6*E**2*Ts**2*c5**2))
    elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:
        return (D**6*E**2*Ts**2*c5**2*(P1**2 - P2**2)
                /(Ps**2*Q**2*SG*Tavg*Zavg*(D**2*c3 + D + c4)))
    else:
        raise ValueError('This function solves for either flow, upstream \
pressure, downstream pressure, diameter, or length; all other inputs \
must be provided.')

def _to_solve_Spitzglass_low(D, Q, SG, Tavg, L, P1, P2, Ts, Ps, Zavg, E):
    return Q - Spitzglass_low(SG=SG, Tavg=Tavg, L=L, D=D, P1=P1, P2=P2, Ts=Ts, Ps=Ps, Zavg=Zavg, E=E)

def Spitzglass_low(SG, Tavg, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
                Ps=101325., Zavg=1.0, E=1.):
    r'''Calculation function for dealing with flow of a compressible gas in a
    pipeline with the Spitzglass (low pressure drop) formula. Can calculate
    any of the following, given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe (numerical solution)
    * Length of pipe

    A variety of different constants and expressions have been presented
    for the Spitzglass (low pressure drop) formula. Here, the form as in [1]_
    is used but with a more precise metric conversion from inches to m.

    .. math::
        Q = 125.1060 E \left(\frac{T_s}{P_s}\right)\left[\frac{2(P_1
        -P_2)(P_s+1210)}{L \cdot {SG} \cdot T_{avg}Z_{avg} (1 + 0.09144/D
        + \frac{150}{127}D)}\right]^{0.5}D^{2.5}

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    This equation is often presented without any correction for reference
    conditions for specific gravity.

    This model is also presented in [2]_ with a leading constant of 5.69E-2,
    the same exponents as used here, units of mm  (diameter), kPa, km (length),
    and flow in m^3/hour. However, it is believed to contain a typo, and gives
    results <1/3 of the correct values. It is also present in [2]_ in imperial
    form; this is believed correct, but makes a slight assumption not done in
    [1]_.

    This model is present in [3]_ without reference corrections. The 1210
    constant in [1]_ is an approximation necessary for the reference correction
    to function without a square of the pressure difference. The GPSA version
    is as follows, and matches this formulation very closely:

    .. math::
        Q = 0.821 \left[\frac{(P_1-P_2)D^5}{L \cdot {SG}
        (1 + 91.44/D + 0.0018D)}\right]^{0.5}

    The model is also shown in [4]_, with diameter in inches, length in feet,
    flow in MMSCFD, pressure drop in inH2O, and a rounded leading constant of
    0.09; this makes its predictions several percent higher than the model here.

    Examples
    --------
    >>> Spitzglass_low(D=0.154051, P1=6720.3199, P2=0, L=54.864, SG=0.6, Tavg=288.7)
    0.9488775242530617

    References
    ----------
    .. [1] Coelho, Paulo M., and Carlos Pinho. "Considerations about Equations
       for Steady State Flow in Natural Gas Pipelines." Journal of the
       Brazilian Society of Mechanical Sciences and Engineering 29, no. 3
       (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.
    .. [2] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,
       FL: CRC Press, 2005.
    .. [3] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors
       Suppliers Association, Tulsa, OK, 2012.
    .. [4] PetroWiki. "Pressure Drop Evaluation along Pipelines" Accessed
       September 11, 2016. http://petrowiki.org/Pressure_drop_evaluation_along_pipelines#Spitzglass_equation_2.
    '''
    c3 = 1.181102362204724409448818897637795275591 # 0.03/inch or 150/127
    c4 = 0.09144
    c5 = 125.1060
    if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:
        return c5*Ts/Ps*D**2.5*E*sqrt(((P1-P2)*2*(Ps+1210.))/(L*SG*Tavg*Zavg*(1 + c4/D + c3*D)))
    elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:
        return secant(_to_solve_Spitzglass_low, 0.5, args=(Q, SG, Tavg, L, P1, P2, Ts, Ps, Zavg, E))
    elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:
        return 0.5*(2.0*D**6*E**2*P2*Ts**2*c5**2*(Ps + 1210.0) + D**2*L*Ps**2*Q**2*SG*Tavg*Zavg*c3 + D*L*Ps**2*Q**2*SG*Tavg*Zavg + L*Ps**2*Q**2*SG*Tavg*Zavg*c4)/(D**6*E**2*Ts**2*c5**2*(Ps + 1210.0))
    elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:
        return 0.5*(2.0*D**6*E**2*P1*Ts**2*c5**2*(Ps + 1210.0) - D**2*L*Ps**2*Q**2*SG*Tavg*Zavg*c3 - D*L*Ps**2*Q**2*SG*Tavg*Zavg - L*Ps**2*Q**2*SG*Tavg*Zavg*c4)/(D**6*E**2*Ts**2*c5**2*(Ps + 1210.0))
    elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:
        return 2.0*D**6*E**2*Ts**2*c5**2*(P1*Ps + 1210.0*P1 - P2*Ps - 1210.0*P2)/(Ps**2*Q**2*SG*Tavg*Zavg*(D**2*c3 + D + c4))
    else:
        raise ValueError('This function solves for either flow, upstream \
pressure, downstream pressure, diameter, or length; all other inputs \
must be provided.')

def _to_solve_Oliphant(D, Q, SG, Tavg, L, P1, P2, Ts, Ps, Zavg, E):
    return Q - Oliphant(SG=SG, Tavg=Tavg, L=L, D=D, P1=P1, P2=P2, Ts=Ts, Ps=Ps, Zavg=Zavg, E=E)

def Oliphant(SG, Tavg, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
             Ps=101325., Zavg=1.0, E=0.92):
    r'''Calculation function for dealing with flow of a compressible gas in a
    pipeline with the Oliphant formula. Can calculate any of the following,
    given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe (numerical solution)
    * Length of pipe

    This model is a more complete conversion to metric of the Imperial version
    presented in [1]_.

    .. math::
        Q = 84.5872\left(D^{2.5} + 0.20915D^3\right)\frac{T_s}{P_s}\left(\frac
        {P_1^2 - P_2^2}{L\cdot {SG} \cdot T_{avg}}\right)^{0.5}

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    Recommended in [1]_ for use between vacuum and 100 psi.

    The model is simplified by grouping constants here; however, it is presented
    in the imperial unit set inches (diameter), miles (length), psi, Rankine,
    and MMSCFD in [1]_:

    .. math::
        Q = 42(24)\left(D^{2.5} + \frac{D^3}{30}\right)\left(\frac{14.4}{P_s}
        \right)\left(\frac{T_s}{520}\right)\left[\left(\frac{0.6}{SG}\right)
        \left(\frac{520}{T_{avg}}\right)\left(\frac{P_1^2 - P_2^2}{L}\right)
        \right]^{0.5}

    Examples
    --------
    >>> Oliphant(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, Tavg=277.15)
    28.851535408143057

    References
    ----------
    .. [1] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors
       Suppliers Association, Tulsa, OK, 2012.
    .. [2] F. N. Oliphant, "Production of Natural Gas," Report. USGS, 1902.
    '''
    # c1 = 42*24*Q*foot**3/day*(mile)**0.5*9/5.*(5/9.)**0.5*psi*(1/psi)*14.4/520.*0.6**0.5*520**0.5/inch**2.5
    c1 = 84.587176139918568651410168968141078948974609375000
    c2 = 0.2091519350460528670065940559652517549694 # 1/(30.*0.0254**0.5)
    if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:
        return c1*(D**2.5 + c2*D**3)*Ts/Ps*sqrt((P1**2-P2**2)/(L*SG*Tavg))
    elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:
        return secant(_to_solve_Oliphant, 0.5, args=(Q, SG, Tavg, L, P1, P2, Ts, Ps, Zavg, E))
    elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:
        return sqrt(L*Ps**2*Q**2*SG*Tavg/(Ts**2*c1**2*(D**3*c2 + D**2.5)**2) + P2**2)
    elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:
        return sqrt(-L*Ps**2*Q**2*SG*Tavg/(Ts**2*c1**2*(D**3*c2 + D**2.5)**2) + P1**2)
    elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:
        return Ts**2*c1**2*(P1**2 - P2**2)*(D**3*c2 + D**2.5)**2/(Ps**2*Q**2*SG*Tavg)
    else:
        raise ValueError('This function solves for either flow, upstream \
pressure, downstream pressure, diameter, or length; all other inputs \
must be provided.')


def Fritzsche(SG, Tavg, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
              Ps=101325., Zavg=1.0, E=1.0):
    r'''Calculation function for dealing with flow of a compressible gas in a
    pipeline with the Fritzsche formula. Can calculate any of the following,
    given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe
    * Length of pipe

    A variety of different constants and expressions have been presented
    for the Fritzsche formula. Here, the form as in [1]_
    is used but with all inputs in base SI units.

    .. math::
        Q = 93.500 \frac{T_s}{P_s}\left(\frac{P_1^2 - P_2^2}
        {L\cdot {SG}^{0.8587} \cdot T_{avg}}\right)^{0.538}D^{2.69}

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    This model is also presented in [1]_ with a leading constant of 2.827,
    the same exponents as used here, units of mm  (diameter), kPa, km (length),
    and flow in m^3/hour.

    This model is shown in base SI units in [2]_, and with a leading constant
    of 94.2565, a diameter power of 2.6911, main group power of 0.5382
    and a specific gravity power of 0.858. The difference is very small.

    Examples
    --------
    >>> Fritzsche(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, Tavg=277.15)
    39.421535157535565

    References
    ----------
    .. [1] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,
       FL: CRC Press, 2005.
    .. [2] Coelho, Paulo M., and Carlos Pinho. "Considerations about Equations
       for Steady State Flow in Natural Gas Pipelines." Journal of the
       Brazilian Society of Mechanical Sciences and Engineering 29, no. 3
       (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.
    '''
    # Rational('2.827E-3')/(3600*24)*(1000)**Rational('2.69')*(1000)**Rational('0.538')*1000/(1000**2)**Rational('0.538')
    c5 = 93.50009798751128188757518688244137811221 # 14135*10**(57/125)/432
    c2 = 0.8587
    c3 = 0.538
    c4 = 2.69
    if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:
        return c5*E*(Ts/Ps)*((P1**2 - P2**2)/(SG**c2*Tavg*L*Zavg))**c3*D**c4
    elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:
        return (Ps*Q*(SG**(-c2)*(P1**2 - P2**2)/(L*Tavg*Zavg))**(-c3)/(E*Ts*c5))**(1./c4)
    elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:
        return sqrt(L*SG**c2*Tavg*Zavg*(D**(-c4)*Ps*Q/(E*Ts*c5))**(1./c3) + P2**2)
    elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:
        return sqrt(-L*SG**c2*Tavg*Zavg*(D**(-c4)*Ps*Q/(E*Ts*c5))**(1./c3) + P1**2)
    elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:
        return SG**(-c2)*(D**(-c4)*Ps*Q/(E*Ts*c5))**(-1./c3)*(P1**2 - P2**2)/(Tavg*Zavg)
    else:
        raise ValueError('This function solves for either flow, upstream pressure, downstream pressure, diameter, or length; all other inputs must be provided.')


def Muller(SG, Tavg, mu, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
           Ps=101325., Zavg=1.0, E=1.0):
    r'''Calculation function for dealing with flow of a compressible gas in a
    pipeline with the Muller formula. Can calculate any of the following,
    given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe
    * Length of pipe

    A variety of different constants and expressions have been presented
    for the Muller formula. Here, the form as in [1]_
    is used but with all inputs in base SI units.

    .. math::
        Q = 15.7743\frac{T_s}{P_s}E\left(\frac{P_1^2 - P_2^2}{L \cdot Z_{avg}
        \cdot T_{avg}}\right)^{0.575} \left(\frac{D^{2.725}}{\mu^{0.15}
        SG^{0.425}}\right)

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    mu : float
        Average viscosity of the fluid in the pipeline, [Pa*s]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    This model is presented in [1]_ with a leading constant of 0.4937, the same
    exponents as used here, units of inches (diameter), psi, feet (length),
    Rankine, pound/(foot*second) for viscosity, and 1000 ft^3/hour.

    This model is also presented in [2]_  in both SI and imperial form. The
    SI form was incorrectly converted and yields much higher flow rates. The
    imperial version has a leading constant of 85.7368, the same powers as
    used here except with rounded values of powers of viscosity (0.2609) and
    specific gravity (0.7391) rearranged to be inside the bracketed group;
    its units are inches (diameter), psi, miles (length),
    Rankine, pound/(foot*second) for viscosity, and ft^3/day.

    This model is shown in base SI units in [3]_, and with a leading constant
    of 15.7650, a diameter power of 2.724, main group power of 0.5747,
    a specific gravity power of 0.74, and a viscosity power of 0.1494.

    Examples
    --------
    >>> Muller(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, mu=1E-5,
    ... Tavg=277.15)
    60.45796698148659

    References
    ----------
    .. [1] Mohitpour, Mo, Golshan, and Allan Murray. Pipeline Design and
       Construction: A Practical Approach. 3rd edition. New York: Amer Soc
       Mechanical Engineers, 2006.
    .. [2] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,
       FL: CRC Press, 2005.
    .. [3] Coelho, Paulo M., and Carlos Pinho. "Considerations about Equations
       for Steady State Flow in Natural Gas Pipelines." Journal of the
       Brazilian Society of Mechanical Sciences and Engineering 29, no. 3
       (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.
    '''
    # 1000*foot**3/hour*0.4937/inch**2.725*foot**0.575*(5/9.)**0.575*9/5.*(pound/foot)**0.15*psi*(1/psi**2)**0.575
    c5 = 15.77439908642077352939746374951659525108 # 5642991*196133**(17/20)*2**(3/5)*3**(11/40)*5**(7/40)/30645781250
    c2 = 0.575 # main power
    c3 = 2.725 # D power
    c4 = 0.425 # SG power
    c1 = 0.15 # mu power
    if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:
        return c5*Ts/Ps*E*((P1**2-P2**2)/Tavg/L/Zavg)**c2*D**c3/SG**c4/mu**c1
    elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:
        return (Ps*Q*SG**c4*mu**c1*((P1**2 - P2**2)/(L*Tavg*Zavg))**(-c2)/(E*Ts*c5))**(1./c3)
    elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:
        return sqrt(L*Tavg*Zavg*(D**(-c3)*Ps*Q*SG**c4*mu**c1/(E*Ts*c5))**(1/c2) + P2**2)
    elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:
        return sqrt(-L*Tavg*Zavg*(D**(-c3)*Ps*Q*SG**c4*mu**c1/(E*Ts*c5))**(1/c2) + P1**2)
    elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:
        return (D**(-c3)*Ps*Q*SG**c4*mu**c1/(E*Ts*c5))**(-1/c2)*(P1**2 - P2**2)/(Tavg*Zavg)
    else:
        raise ValueError('This function solves for either flow, upstream pressure, downstream pressure, diameter, or length; all other inputs must be provided.')


def IGT(SG, Tavg, mu, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
        Ps=101325., Zavg=1.0, E=1.0):
    r'''Calculation function for dealing with flow of a compressible gas in a
    pipeline with the IGT formula. Can calculate any of the following,
    given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe
    * Length of pipe

    A variety of different constants and expressions have been presented
    for the IGT formula. Here, the form as in [1]_
    is used but with all inputs in base SI units.

    .. math::
        Q = 24.6241\frac{T_s}{P_s}E\left(\frac{P_1^2 - P_2^2}{L \cdot Z_{avg}
        \cdot T_{avg}}\right)^{5/9} \left(\frac{D^{8/3}}{\mu^{1/9}
        SG^{4/9}}\right)

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    mu : float
        Average viscosity of the fluid in the pipeline, [Pa*s]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    This model is presented in [1]_ with a leading constant of 0.6643, the same
    exponents as used here, units of inches (diameter), psi, feet (length),
    Rankine, pound/(foot*second) for viscosity, and 1000 ft^3/hour.

    This model is also presented in [2]_  in both SI and imperial form. Both
    forms are correct. The imperial version has a leading constant of 136.9,
    the same powers as used here except with rounded values of powers of
    viscosity (0.2) and specific gravity (0.8) rearranged to be inside the
    bracketed group; its units are inches (diameter), psi, miles (length),
    Rankine, pound/(foot*second) for viscosity, and ft^3/day.

    This model is shown in base SI units in [3]_, and with a leading constant
    of 24.6145, and the same powers as used here.

    Examples
    --------
    >>> IGT(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, mu=1E-5, Tavg=277.15)
    48.92351786788815

    References
    ----------
    .. [1] Mohitpour, Mo, Golshan, and Allan Murray. Pipeline Design and
       Construction: A Practical Approach. 3rd edition. New York: Amer Soc
       Mechanical Engineers, 2006.
    .. [2] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,
       FL: CRC Press, 2005.
    .. [3] Coelho, Paulo M., and Carlos Pinho. "Considerations about Equations
       for Steady State Flow in Natural Gas Pipelines." Journal of the
       Brazilian Society of Mechanical Sciences and Engineering 29, no. 3
       (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.
    '''
    # 1000*foot**3/hour*0.6643/inch**(8/3.)*foot**(5/9.)*(5/9.)**(5/9.)*9/5.*(pound/foot)**(1/9.)*psi*(1/psi**2)**(5/9.)
    c5 = 24.62412451461407054875301709443930350550 # 1084707*196133**(8/9)*2**(1/9)*6**(1/3)/4377968750
    c2 = 5/9. # main power
    c3 = 8/3. # D power
    c4 = 4/9. # SG power
    c1 = 1/9. # mu power
    if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:
        return c5*Ts/Ps*E*((P1**2-P2**2)/Tavg/L/Zavg)**c2*D**c3/SG**c4/mu**c1
    elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:
        return (Ps*Q*SG**c4*mu**c1*((P1**2 - P2**2)/(L*Tavg*Zavg))**(-c2)/(E*Ts*c5))**(1./c3)
    elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:
        return sqrt(L*Tavg*Zavg*(D**(-c3)*Ps*Q*SG**c4*mu**c1/(E*Ts*c5))**(1/c2) + P2**2)
    elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:
        return sqrt(-L*Tavg*Zavg*(D**(-c3)*Ps*Q*SG**c4*mu**c1/(E*Ts*c5))**(1/c2) + P1**2)
    elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:
        return (D**(-c3)*Ps*Q*SG**c4*mu**c1/(E*Ts*c5))**(-1/c2)*(P1**2 - P2**2)/(Tavg*Zavg)
    else:
        raise ValueError('This function solves for either flow, upstream pressure, downstream pressure, diameter, or length; all other inputs must be provided.')