hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
qsc_code_num_words_quality_signal
int64
qsc_code_num_chars_quality_signal
float64
qsc_code_mean_word_length_quality_signal
float64
qsc_code_frac_words_unique_quality_signal
float64
qsc_code_frac_chars_top_2grams_quality_signal
float64
qsc_code_frac_chars_top_3grams_quality_signal
float64
qsc_code_frac_chars_top_4grams_quality_signal
float64
qsc_code_frac_chars_dupe_5grams_quality_signal
float64
qsc_code_frac_chars_dupe_6grams_quality_signal
float64
qsc_code_frac_chars_dupe_7grams_quality_signal
float64
qsc_code_frac_chars_dupe_8grams_quality_signal
float64
qsc_code_frac_chars_dupe_9grams_quality_signal
float64
qsc_code_frac_chars_dupe_10grams_quality_signal
float64
qsc_code_frac_chars_replacement_symbols_quality_signal
float64
qsc_code_frac_chars_digital_quality_signal
float64
qsc_code_frac_chars_whitespace_quality_signal
float64
qsc_code_size_file_byte_quality_signal
float64
qsc_code_num_lines_quality_signal
float64
qsc_code_num_chars_line_max_quality_signal
float64
qsc_code_num_chars_line_mean_quality_signal
float64
qsc_code_frac_chars_alphabet_quality_signal
float64
qsc_code_frac_chars_comments_quality_signal
float64
qsc_code_cate_xml_start_quality_signal
float64
qsc_code_frac_lines_dupe_lines_quality_signal
float64
qsc_code_cate_autogen_quality_signal
float64
qsc_code_frac_lines_long_string_quality_signal
float64
qsc_code_frac_chars_string_length_quality_signal
float64
qsc_code_frac_chars_long_word_length_quality_signal
float64
qsc_code_frac_lines_string_concat_quality_signal
float64
qsc_code_cate_encoded_data_quality_signal
float64
qsc_code_frac_chars_hex_words_quality_signal
float64
qsc_code_frac_lines_prompt_comments_quality_signal
float64
qsc_code_frac_lines_assert_quality_signal
float64
qsc_codepython_cate_ast_quality_signal
float64
qsc_codepython_frac_lines_func_ratio_quality_signal
float64
qsc_codepython_cate_var_zero_quality_signal
bool
qsc_codepython_frac_lines_pass_quality_signal
float64
qsc_codepython_frac_lines_import_quality_signal
float64
qsc_codepython_frac_lines_simplefunc_quality_signal
float64
qsc_codepython_score_lines_no_logic_quality_signal
float64
qsc_codepython_frac_lines_print_quality_signal
float64
qsc_code_num_words
int64
qsc_code_num_chars
int64
qsc_code_mean_word_length
int64
qsc_code_frac_words_unique
null
qsc_code_frac_chars_top_2grams
int64
qsc_code_frac_chars_top_3grams
int64
qsc_code_frac_chars_top_4grams
int64
qsc_code_frac_chars_dupe_5grams
int64
qsc_code_frac_chars_dupe_6grams
int64
qsc_code_frac_chars_dupe_7grams
int64
qsc_code_frac_chars_dupe_8grams
int64
qsc_code_frac_chars_dupe_9grams
int64
qsc_code_frac_chars_dupe_10grams
int64
qsc_code_frac_chars_replacement_symbols
int64
qsc_code_frac_chars_digital
int64
qsc_code_frac_chars_whitespace
int64
qsc_code_size_file_byte
int64
qsc_code_num_lines
int64
qsc_code_num_chars_line_max
int64
qsc_code_num_chars_line_mean
int64
qsc_code_frac_chars_alphabet
int64
qsc_code_frac_chars_comments
int64
qsc_code_cate_xml_start
int64
qsc_code_frac_lines_dupe_lines
int64
qsc_code_cate_autogen
int64
qsc_code_frac_lines_long_string
int64
qsc_code_frac_chars_string_length
int64
qsc_code_frac_chars_long_word_length
int64
qsc_code_frac_lines_string_concat
null
qsc_code_cate_encoded_data
int64
qsc_code_frac_chars_hex_words
int64
qsc_code_frac_lines_prompt_comments
int64
qsc_code_frac_lines_assert
int64
qsc_codepython_cate_ast
int64
qsc_codepython_frac_lines_func_ratio
int64
qsc_codepython_cate_var_zero
int64
qsc_codepython_frac_lines_pass
int64
qsc_codepython_frac_lines_import
int64
qsc_codepython_frac_lines_simplefunc
int64
qsc_codepython_score_lines_no_logic
int64
qsc_codepython_frac_lines_print
int64
effective
string
hits
int64
bec5d3ada4f4a6b1fe7adcf9aaa6db5701f3ee3e
374
py
Python
aliexpress/api/rest/SolutionProductSchemaGet.py
bayborodin/aliexpress-sdk
89935adf46412d8d054fa80a19153971279c4106
[ "MIT" ]
3
2021-03-10T16:46:43.000Z
2022-03-29T15:28:50.000Z
aliexpress/api/rest/SolutionProductSchemaGet.py
bayborodin/aliexpress-sdk
89935adf46412d8d054fa80a19153971279c4106
[ "MIT" ]
null
null
null
aliexpress/api/rest/SolutionProductSchemaGet.py
bayborodin/aliexpress-sdk
89935adf46412d8d054fa80a19153971279c4106
[ "MIT" ]
2
2021-10-30T17:09:34.000Z
2021-11-25T11:50:52.000Z
""" Created by auto_sdk on 2019.05.06 """ from aliexpress.api.base import RestApi class AliexpressSolutionProductSchemaGetRequest(RestApi): def __init__(self, domain="gw.api.taobao.com", port=80): RestApi.__init__(self, domain, port) self.aliexpress_category_id = None def getapiname(self): return "aliexpress.solution.product.schema.get"
26.714286
60
0.724599
46
374
5.652174
0.73913
0.061538
0.107692
0
0
0
0
0
0
0
0
0.032051
0.165775
374
13
61
28.769231
0.801282
0.088235
0
0
0
0
0.165165
0.114114
0
0
0
0
0
1
0.285714
false
0
0.142857
0.142857
0.714286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
fe221dbd381e1bdb931cdf2e35dcf8463b545c3d
195
py
Python
Multidimensional lists - Lab/Primary diagonal.py
DiyanKalaydzhiev23/Advanced---Python
ed2c60bb887c49e5a87624719633e2b8432f6f6b
[ "MIT" ]
null
null
null
Multidimensional lists - Lab/Primary diagonal.py
DiyanKalaydzhiev23/Advanced---Python
ed2c60bb887c49e5a87624719633e2b8432f6f6b
[ "MIT" ]
null
null
null
Multidimensional lists - Lab/Primary diagonal.py
DiyanKalaydzhiev23/Advanced---Python
ed2c60bb887c49e5a87624719633e2b8432f6f6b
[ "MIT" ]
null
null
null
matrix = [input().split() for row in range(int(input()))] primary_diagonal_sum = 0 for i in range(len(matrix)): primary_diagonal_sum += int(matrix[i][i]) print(primary_diagonal_sum)
24.375
58
0.687179
30
195
4.266667
0.5
0.351563
0.421875
0
0
0
0
0
0
0
0
0.006098
0.158974
195
7
59
27.857143
0.77439
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.2
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
fe2f8c4e0d2735afbdc9c29715a4f26b32a87e38
1,033
py
Python
qiskit/dagcircuit/__init__.py
ajavadia/qiskit-sdk-py
a59e8e6be1793197e19998c1f7dcfc45e6f2f3af
[ "Apache-2.0" ]
15
2020-06-29T08:33:39.000Z
2022-02-12T00:28:51.000Z
qiskit/dagcircuit/__init__.py
ajavadia/qiskit-sdk-py
a59e8e6be1793197e19998c1f7dcfc45e6f2f3af
[ "Apache-2.0" ]
35
2019-03-07T02:09:22.000Z
2022-03-22T19:55:15.000Z
qiskit/dagcircuit/__init__.py
ajavadia/qiskit-sdk-py
a59e8e6be1793197e19998c1f7dcfc45e6f2f3af
[ "Apache-2.0" ]
11
2020-06-29T08:40:24.000Z
2022-02-24T17:39:16.000Z
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ ======================================= DAG Circuits (:mod:`qiskit.dagcircuit`) ======================================= .. currentmodule:: qiskit.dagcircuit DAG Circuits ============ .. autosummary:: :toctree: ../stubs/ DAGCircuit DAGNode DAGDepNode DAGDependency Exceptions ========== .. autosummary:: :toctree: ../stubs/ DAGCircuitError """ from .dagcircuit import DAGCircuit from .dagnode import DAGNode from .dagdepnode import DAGDepNode from .exceptions import DAGCircuitError from .dagdependency import DAGDependency
23.477273
77
0.675702
124
1,033
5.629032
0.572581
0.034384
0.028653
0
0
0
0
0
0
0
0
0.009174
0.155857
1,033
43
78
24.023256
0.791284
0.795741
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
3
fe36f01b8e88d06897df80ff6e4e51da76161d39
2,502
py
Python
quadpy/triangle/_taylor_wingate_bos.py
whzup/quadpy
ca8bd2f9c5a4ae30dc85d8fb79217602bd42525e
[ "MIT" ]
null
null
null
quadpy/triangle/_taylor_wingate_bos.py
whzup/quadpy
ca8bd2f9c5a4ae30dc85d8fb79217602bd42525e
[ "MIT" ]
null
null
null
quadpy/triangle/_taylor_wingate_bos.py
whzup/quadpy
ca8bd2f9c5a4ae30dc85d8fb79217602bd42525e
[ "MIT" ]
null
null
null
from sympy import Rational as frac from ..helpers import article from ._helpers import TriangleScheme, concat, s1, s2 citation = article( authors=["Mark A. Taylor", "Beth A. Wingate", "Len P. Bos"], title="Several new quadrature formulas for polynomial integration in the triangle", journal="arXiv Mathematics e-prints", year="2005", month="jan", url="https://arxiv.org/abs/math/0501496", ) # TODO missing Taylor-Wingate-Bos schemes def taylor_wingate_bos_1(): weights, points = s2([frac(2, 3), frac(1, 6)]) weights /= 2 return TriangleScheme("Taylor-Wingate-Bos 1", weights, points, 2, citation) def taylor_wingate_bos_2(): weights, points = s2( [0.2199034873106, 0.0915762135098], [0.4467631793560, 0.4459484909160] ) weights /= 2 return TriangleScheme("Taylor-Wingate-Bos 2", weights, points, 4, citation) def taylor_wingate_bos_4(): weights, points = concat( s2( [0.0102558174092, 0], [0.1679775595335, 0.4743880861752], [0.2652238803946, 0.2385615300181], ), s1([0.1116047046647, 0.7839656651012, 0.0421382841642]), ) weights /= 2 return TriangleScheme("Taylor-Wingate-Bos 4", weights, points, 7, citation) def taylor_wingate_bos_5(): weights, points = concat( s2( [0.0519871420646, 0.0451890097844], [0.1032344051380, 0.4815198347833], [0.1881601469167, 0.4036039798179], ), s1( [0.0707034101784, 0.7475124727339, 0.0304243617288], [0.0909390760952, 0.1369912012649, 0.2182900709714], ), ) weights /= 2 return TriangleScheme("Taylor-Wingate-Bos 5", weights, points, 9, citation) def taylor_wingate_bos_8(): weights, points = concat( s2( [0.0010616711990, 0], [0.0349317947036, 0.4903668903754], [0.0383664533945, 0.0875134669581], [0.0897856524107, 0.2217145894873], [0.1034544533617, 0.3860471669296], ), s1( [0.0131460236101, 0.0573330873026, 0.0151382269814], [0.0242881926949, 0.8159625040711, 0.1659719969565], [0.0316799866332, 0.3165475556378, 0.0186886898773], [0.0578369491210, 0.0935526036219, 0.2079865423167], [0.0725821687394, 0.0974892983467, 0.5380088595149], ), ) weights /= 2 return TriangleScheme("Taylor-Wingate-Bos 8", weights, points, 14, citation)
30.888889
87
0.6247
272
2,502
5.6875
0.419118
0.092437
0.113769
0.061409
0.330317
0.284421
0.142211
0
0
0
0
0.383387
0.2494
2,502
80
88
31.275
0.440362
0.015588
0
0.276923
0
0
0.113775
0
0
0
0
0.0125
0
1
0.076923
false
0
0.046154
0
0.2
0.015385
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
3
fe4cc9a06f77f03802ac2823262a7c606758bc6b
642
py
Python
newnnfw/tools/tflitefile_tool/tflite/DequantizeOptions.py
kosslab-kr/Tizen-NN-Framework
132fc98ed57e4b19ad1f4cb258ad79fa9df1db7a
[ "Apache-2.0" ]
8
2018-09-10T01:32:26.000Z
2020-05-13T06:05:40.000Z
newnnfw/tools/tflitefile_tool/tflite/DequantizeOptions.py
kosslab-kr/Tizen-NN-Framework
132fc98ed57e4b19ad1f4cb258ad79fa9df1db7a
[ "Apache-2.0" ]
28
2018-09-10T05:01:09.000Z
2021-03-04T10:07:12.000Z
newnnfw/tools/tflitefile_tool/tflite/DequantizeOptions.py
kosslab-kr/Tizen-NN-Framework
132fc98ed57e4b19ad1f4cb258ad79fa9df1db7a
[ "Apache-2.0" ]
4
2018-09-13T04:16:08.000Z
2018-12-03T07:34:44.000Z
# automatically generated by the FlatBuffers compiler, do not modify # namespace: tflite import flatbuffers class DequantizeOptions(object): __slots__ = ['_tab'] @classmethod def GetRootAsDequantizeOptions(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = DequantizeOptions() x.Init(buf, n + offset) return x # DequantizeOptions def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) def DequantizeOptionsStart(builder): builder.StartObject(0) def DequantizeOptionsEnd(builder): return builder.EndObject()
22.137931
75
0.697819
67
642
6.597015
0.597015
0.040724
0
0
0
0
0
0
0
0
0
0.001969
0.208723
642
28
76
22.928571
0.86811
0.158879
0
0
1
0
0.007463
0
0
0
0
0
0
1
0.266667
false
0
0.066667
0.066667
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
fe6b127379c7595dedcc3229dc6e63b4743a3f00
141
py
Python
climinteractive/__init__.py
BjoernMayer92/climinteractive
ac60f0f2872987894bbf175724f0b609d13c426f
[ "MIT" ]
null
null
null
climinteractive/__init__.py
BjoernMayer92/climinteractive
ac60f0f2872987894bbf175724f0b609d13c426f
[ "MIT" ]
null
null
null
climinteractive/__init__.py
BjoernMayer92/climinteractive
ac60f0f2872987894bbf175724f0b609d13c426f
[ "MIT" ]
null
null
null
"""Top-level package for climinteractive.""" __author__ = """Bjoern Mayer""" __email__ = 'bjoern.mayer@mpimet.mpg.de' __version__ = '0.1.0'
23.5
44
0.702128
18
141
4.833333
0.833333
0.252874
0
0
0
0
0
0
0
0
0
0.02381
0.106383
141
5
45
28.2
0.666667
0.269504
0
0
0
0
0.443299
0.268041
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
fe9369d78881105a986e1594e9bee03b2de87b2d
246
py
Python
grao_tables_processing/wikidata_interaction/__init__.py
nikolatulechki/GRAO-tables-processing
1ebfab4b77af8ebd31e71d6f60b33c75f3881e98
[ "MIT" ]
1
2020-07-12T16:12:23.000Z
2020-07-12T16:12:23.000Z
grao_tables_processing/wikidata_interaction/__init__.py
data-for-good-bg/GRAO-tables-processing
5e295710b4e42b2ccf9c0d226c8cf0fa380aaa43
[ "MIT" ]
79
2020-07-11T23:11:33.000Z
2022-03-17T10:03:05.000Z
grao_tables_processing/wikidata_interaction/__init__.py
data-for-good-bg/GRAO-tables-processing
5e295710b4e42b2ccf9c0d226c8cf0fa380aaa43
[ "MIT" ]
5
2020-07-12T16:12:34.000Z
2021-12-15T13:38:16.000Z
import grao_tables_processing.wikidata_interaction.wd_update as wdu import grao_tables_processing.wikidata_interaction.matched_data_update as mdu update_all_settlements = wdu.update_all_settlements update_matched_data = mdu.update_matched_data
35.142857
77
0.902439
35
246
5.857143
0.428571
0.160976
0.156098
0.253659
0.439024
0.439024
0
0
0
0
0
0
0.065041
246
6
78
41
0.891304
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
2293f4e59c2a561168acd579f5dd673075840ab9
1,559
py
Python
MDRSREID/Networks/PGFA/__init__.py
nickhuang1996/HJL-re-id
107b25f31c961f360f69560cfddd78dfc0da3291
[ "MIT" ]
43
2020-09-20T09:40:04.000Z
2022-03-29T11:25:22.000Z
MDRSREID/Networks/PGFA/__init__.py
nickhuang1996/HJL-re-id
107b25f31c961f360f69560cfddd78dfc0da3291
[ "MIT" ]
19
2020-10-05T05:35:38.000Z
2021-12-10T03:17:31.000Z
MDRSREID/Networks/PGFA/__init__.py
nickhuang1996/HJL-re-id
107b25f31c961f360f69560cfddd78dfc0da3291
[ "MIT" ]
18
2020-10-01T14:41:53.000Z
2021-09-02T06:57:57.000Z
from torch import nn from .PGFA_backbone import PGFABackbone from .PGFA_pool import PGFAPool from .PGFA_pose_guided_mask_block import PGFAPoseGuidedMaskBlock from .PGFA_reduction import PGFAReduction from .PGFA_classifier import PGFAClassifier class PGFA(nn.Module): def __init__(self, cfg): super(PGFA, self).__init__() self.backbone = PGFABackbone(cfg) self.pool = PGFAPool(cfg) self.pose_guide_mask_block = PGFAPoseGuidedMaskBlock(cfg) self.reduction = PGFAReduction(cfg) if hasattr(cfg.model, 'num_classes') and cfg.model.num_classes > 0: self.classifier = PGFAClassifier(cfg) def backbone_forward(self, in_dict): return self.backbone(in_dict) def pool_forward(self, in_dict, cfg): return self.pool(in_dict, cfg) def pose_guided_mask_block_forward(self, in_dict, out_dict, cfg): return self.pose_guide_mask_block(in_dict, out_dict, cfg) def reduction_forward(self, in_dict, cfg): return self.reduction(in_dict, cfg) def classifier_forward(self, in_dict, cfg): return self.classifier(in_dict, cfg) def forward(self, in_dict, cfg, forward_type='Supervised'): in_dict = self.backbone_forward(in_dict) out_dict = self.pool_forward(in_dict, cfg) out_dict = self.pose_guided_mask_block_forward(in_dict, out_dict, cfg) out_dict = self.reduction_forward(out_dict, cfg) if hasattr(self, 'classifier'): out_dict = self.classifier_forward(out_dict, cfg) return out_dict
37.119048
78
0.712636
212
1,559
4.929245
0.188679
0.086124
0.0689
0.097608
0.289952
0.086124
0.086124
0
0
0
0
0.000803
0.201411
1,559
41
79
38.02439
0.838554
0
0
0
0
0
0.019885
0
0
0
0
0
0
1
0.212121
false
0
0.181818
0.151515
0.606061
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
2297d3ecb9fd5d7d68ae5433f8ddca013fec1ba2
3,170
py
Python
PDA_Transport/multi_period_aam.py
gaufung/LMDI
9f412802cc32adbb9562cab0e028c0057fc36cfa
[ "MIT" ]
4
2020-07-21T03:45:48.000Z
2021-12-20T09:37:10.000Z
PDA_Transport/multi_period_aam.py
gaufung/LMDI
9f412802cc32adbb9562cab0e028c0057fc36cfa
[ "MIT" ]
1
2021-05-27T03:24:38.000Z
2021-05-27T03:24:38.000Z
PDA_Transport/multi_period_aam.py
gaufung/LMDI
9f412802cc32adbb9562cab0e028c0057fc36cfa
[ "MIT" ]
4
2017-04-13T13:53:38.000Z
2022-03-01T13:28:48.000Z
# -*- encoding:utf-8 -*- from single_period_aam import Spaam class Mpaam(object): def __init__(self, dmus_s, name, global_dmus, cefs, years): self._period_count = len(dmus_s) self._dmus_s = dmus_s self._province_count = len(dmus_s[0]) self._province_names = [item.name for item in dmus_s[0]] self._name = name self._cache = {} self._global_dmus = global_dmus self._cefs = cefs self._years = years @property def name(self): return self._name @property def province_names(self): return self._province_names def _get_spaam(self, left, right): assert left != right label = str(left) + '-' + str(right) if label not in self._cache: self._cache[label] = Spaam.build(self._dmus_s[left], self._dmus_s[right], self._years[left] + '-' + self._years[right], self._global_dmus, self._cefs) return self._cache[label] def _index_t(self, t, index_name): result = 1.0 for i in range(1, t + 1): result *= getattr(self._get_spaam(i - 1, i), index_name) return result def _index(self, index_name): result = [] for i in range(self._province_count): value = 0.0 for t in range(1, self._period_count): aggerate_value = self._index_t(t - 1, index_name) spaam_t_1_t = self._get_spaam(t - 1, t) contribution = (getattr(spaam_t_1_t, 'r' + index_name)()[i] * getattr(spaam_t_1_t, index_name + '_ratio')()[i]) value += aggerate_value * contribution result.append(value) return result # emx def emx(self): return self._index('emx') def emx_t(self, t): return self._index_t(t, 'emx') # cef def cef(self): return self._index('cef') def cef_t(self, t): return self._index_t(t, 'cef') # pei def pei_t(self, t): return self._index_t(t, 'pei') def pei(self): return self._index('pei') # est def est_t(self, t): return self._index_t(t, 'est') def est(self): return self._index('est') # eue def eue_t(self, t): return self._index_t(t, 'eue') def eue(self): return self._index('eue') # pti def pti_t(self, t): return self._index_t(t, 'pti') def pti(self): return self._index('pti') # yoe def yoe_t(self, t): return self._index_t(t, 'yoe') def yoe(self): return self._index('yoe') # yct def yct_t(self, t): return self._index_t(t, 'yct') def yct(self): return self._index('yct') # rts def rts_t(self, t): return self._index_t(t, 'rts') def rts(self): return self._index('rts') def indexes(self, t): return [self.cef_t(t), self.emx_t(t), self.pei_t(t), self.est_t(t), self.eue_t(t), self.pti_t(t), self.yoe_t(t), self.yct_t(t), self.rts_t(t)]
26.638655
90
0.540063
443
3,170
3.591422
0.14447
0.138278
0.169705
0.069139
0.148963
0.130107
0.130107
0.130107
0
0
0
0.007551
0.331546
3,170
119
91
26.638655
0.743275
0.018297
0
0.048193
0
0
0.020309
0
0
0
0
0
0.012048
1
0.301205
false
0
0.012048
0.253012
0.614458
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
22a44f59d4600d2104f101cc4884521555b9b03f
929
py
Python
coworker/search/serializers.py
upstar77/spacemap
1babcecabc42b325dc647294599c309d6bda1ad5
[ "MIT" ]
null
null
null
coworker/search/serializers.py
upstar77/spacemap
1babcecabc42b325dc647294599c309d6bda1ad5
[ "MIT" ]
null
null
null
coworker/search/serializers.py
upstar77/spacemap
1babcecabc42b325dc647294599c309d6bda1ad5
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from rest_framework import serializers from rest_framework_elasticsearch.es_serializer import ElasticModelSerializer from coworker.place.models import Place from coworker.cities.models import City class PlaceSerializer(serializers.ModelSerializer): # value = serializers.SerializerMethodField() label = serializers.ReadOnlyField(source='autocomplete_value') # url = serializers.SerializerMethodField() value = serializers.ReadOnlyField(source='autocomplete_value') coworkspace_url = serializers.ReadOnlyField(source='autocomplete_value') class Meta: model = Place fields = ('pk', 'space_name', 'cs_description', 'value', 'label', 'coworkspace_url') class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ('pk', 'name')
29.967742
92
0.750269
92
929
7.380435
0.478261
0.106038
0.132548
0.185567
0.207658
0
0
0
0
0
0
0.001271
0.152853
929
30
93
30.966667
0.861499
0.115178
0
0.125
0
0
0.135697
0
0
0
0
0
0
1
0
false
0
0.3125
0
0.75
0.0625
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
22a7313828ffcd32e8d60d0804e3ee2822b7d4a2
1,137
py
Python
08_Inheritance_and_SubType_Polymorphism/sorted_list.py
MANOJPATRA1991/Python-Beyond-the-Basics
aed7bfd35e33c2b1759b48e1c89314aa149c56d0
[ "MIT" ]
null
null
null
08_Inheritance_and_SubType_Polymorphism/sorted_list.py
MANOJPATRA1991/Python-Beyond-the-Basics
aed7bfd35e33c2b1759b48e1c89314aa149c56d0
[ "MIT" ]
null
null
null
08_Inheritance_and_SubType_Polymorphism/sorted_list.py
MANOJPATRA1991/Python-Beyond-the-Basics
aed7bfd35e33c2b1759b48e1c89314aa149c56d0
[ "MIT" ]
null
null
null
class SimpleList: def __init__(self, items): self._items = list(items) def add(self, item): self._items.append(item) def __getitem__(self, index): return self._items[index] def sort(self): self._items.sort() def __len__(self): return len(self._items) def __repr__(self): return "SimpleList({!r})".format(self._items) class SortedList(SimpleList): def __init__(self, items=()): super().__init__(items) self.sort() def add(self, item): super().add(item) self.sort() def __repr__(self): return "SortedList({!r})".format(list(self)) class IntList(SimpleList): def __init__(self, items=()): print('in intlist') for x in items: self._validate(x) super().__init__(items) @staticmethod def _validate(x): if not isinstance(x, int): raise TypeError('IntList only supports integer values.') def add(self, item): self._validate(item) super().add(item) def __repr__(self): return "IntList({!r})".format(list(self)) class SortedIntList(IntList, SortedList): def __repr__(self): return 'SortedIntList({!r})'.format(list(self))
21.45283
62
0.657872
146
1,137
4.760274
0.260274
0.116547
0.063309
0.097842
0.221583
0
0
0
0
0
0
0
0.185576
1,137
52
63
21.865385
0.75054
0
0
0.384615
0
0
0.097625
0
0
0
0
0
0
1
0.358974
false
0
0
0.153846
0.615385
0.025641
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
22b529f49b7f5c2203a203c71d25873c4b191360
416
py
Python
mythx_cli/payload/bytecode.py
maurelian/mythx-cli
5da00777429a40f30cb2c1b4703f1b1560a91ecb
[ "MIT" ]
null
null
null
mythx_cli/payload/bytecode.py
maurelian/mythx-cli
5da00777429a40f30cb2c1b4703f1b1560a91ecb
[ "MIT" ]
null
null
null
mythx_cli/payload/bytecode.py
maurelian/mythx-cli
5da00777429a40f30cb2c1b4703f1b1560a91ecb
[ "MIT" ]
null
null
null
"""This module contains functions to generate bytecode-only analysis request payloads.""" from typing import Dict def generate_bytecode_payload(code: str) -> Dict[str, str]: """Generate a payload containing only the creation bytecode. :param code: The creation bytecode as hex string starting with :code:`0x` :return: The payload dictionary to be sent to MythX """ return {"bytecode": code}
27.733333
77
0.725962
56
416
5.357143
0.625
0.106667
0.126667
0
0
0
0
0
0
0
0
0.00295
0.185096
416
14
78
29.714286
0.882006
0.644231
0
0
1
0
0.064516
0
0
0
0
0
0
1
0.333333
false
0
0.333333
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
1
0
0
0
0
3
22dfc40437ee479921d2514f5b38b36830b53c57
851
py
Python
game_test.py
jcl696/landers-rock-paper-scissors
88b8d981379b5b6310fcbeeb3004a50d6d7b0696
[ "MIT" ]
null
null
null
game_test.py
jcl696/landers-rock-paper-scissors
88b8d981379b5b6310fcbeeb3004a50d6d7b0696
[ "MIT" ]
null
null
null
game_test.py
jcl696/landers-rock-paper-scissors
88b8d981379b5b6310fcbeeb3004a50d6d7b0696
[ "MIT" ]
null
null
null
#need to have test_ at the beginning of defining a function from game import my_message #game_test.py def test_example(): assert 2 == 2 def test_my_message(): x = my_message() assert x == "HELLO" #def test_determination_of_the_winner(): # assert determine_winner("rock", "rock") == None # represents a tie # assert determine_winner("rock", "paper") == "paper" # assert determine_winner("rock", "scissors") == "rock" # # assert determine_winner("paper", "rock") == "paper" # assert determine_winner("paper", "paper") == None # represents a tie # assert determine_winner("paper", "scissors") == "scissors" # # assert determine_winner("scissors", "rock") == "rock" # assert determine_winner("scissors", "paper") == "scissors" # assert determine_winner("scissors", "scissors") == None # represents a tie #
29.344828
80
0.6698
104
851
5.288462
0.307692
0.245455
0.343636
0.136364
0.276364
0.141818
0.141818
0
0
0
0
0.002857
0.177438
851
28
81
30.392857
0.782857
0.795535
0
0
0
0
0.032258
0
0
0
0
0
0.333333
1
0.333333
false
0
0.166667
0
0.5
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
22e0b04402217885d42fd8acf90b70cc82682b73
344
py
Python
src/simfoni/apps/company/models/raw_company.py
django-stars/simfoni-test
eaca4adc8177505e7c53e708456fd0dbb6be0b71
[ "MIT" ]
null
null
null
src/simfoni/apps/company/models/raw_company.py
django-stars/simfoni-test
eaca4adc8177505e7c53e708456fd0dbb6be0b71
[ "MIT" ]
null
null
null
src/simfoni/apps/company/models/raw_company.py
django-stars/simfoni-test
eaca4adc8177505e7c53e708456fd0dbb6be0b71
[ "MIT" ]
4
2018-04-26T17:43:24.000Z
2018-05-10T14:11:09.000Z
from django.db import models from django.utils.translation import ugettext_lazy as _ from core.models import AbstractBaseModel class RawCompany(AbstractBaseModel): """ Data which should be processed to obtain Company """ name = models.CharField(_('Raw company name'), max_length=255) def __str__(self): return self.name
26.461538
66
0.747093
44
344
5.659091
0.727273
0.080321
0
0
0
0
0
0
0
0
0
0.010563
0.174419
344
12
67
28.666667
0.866197
0.139535
0
0
0
0
0.055556
0
0
0
0
0
0
1
0.142857
false
0
0.428571
0.142857
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
1
1
0
0
3
fe05d81badf0cc25bb2bac6a189a765ab95ece0e
329
py
Python
__init__.py
CCapelini/quandolavar-skill
90fb27efdbca2619c88a54b8ee5f1842a5f32806
[ "Apache-2.0" ]
null
null
null
__init__.py
CCapelini/quandolavar-skill
90fb27efdbca2619c88a54b8ee5f1842a5f32806
[ "Apache-2.0" ]
null
null
null
__init__.py
CCapelini/quandolavar-skill
90fb27efdbca2619c88a54b8ee5f1842a5f32806
[ "Apache-2.0" ]
null
null
null
from mycroft import MycroftSkill, intent_file_handler class Quandolavar(MycroftSkill): def __init__(self): MycroftSkill.__init__(self) @intent_file_handler('quandolavar.intent') def handle_quandolavar(self, message): self.speak_dialog('quandolavar') def create_skill(): return Quandolavar()
20.5625
53
0.735562
35
329
6.485714
0.542857
0.088106
0.14978
0
0
0
0
0
0
0
0
0
0.173252
329
15
54
21.933333
0.834559
0
0
0
0
0
0.088415
0
0
0
0
0
0
1
0.333333
false
0
0.111111
0.111111
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
fe0fb5a1f0bb5129f0c2363d400c0d4736983c83
222
py
Python
cifar10_plotter.py
mpienkosz/cifar10-classification
f6dbc662eb7ed761a5ed02e3d4e5cf028684d076
[ "MIT" ]
null
null
null
cifar10_plotter.py
mpienkosz/cifar10-classification
f6dbc662eb7ed761a5ed02e3d4e5cf028684d076
[ "MIT" ]
null
null
null
cifar10_plotter.py
mpienkosz/cifar10-classification
f6dbc662eb7ed761a5ed02e3d4e5cf028684d076
[ "MIT" ]
null
null
null
from utils.visualization import plot_images from keras.datasets import cifar10 print('Loading cifar10..') (X_train, Y_train), (X_test, Y_test) = cifar10.load_data() print('Plotting..') plot_images(X_train, Y_train, 10)
22.2
58
0.765766
34
222
4.735294
0.558824
0.124224
0.086957
0.149068
0
0
0
0
0
0
0
0.040201
0.103604
222
9
59
24.666667
0.768844
0
0
0
0
0
0.121622
0
0
0
0
0
0
1
0
true
0
0.333333
0
0.333333
0.333333
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
3
a3ace3ff5be222d57af9b72774172b480fb2d452
579
py
Python
Diena_7_functions/uzd3_g1.py
edzya/Python_RTU_08_20
d2921d998c611c18328dd523daf976a27ce858c1
[ "MIT" ]
8
2020-08-31T16:10:54.000Z
2021-11-24T06:37:37.000Z
Diena_7_functions/uzd3_g1.py
edzya/Python_RTU_08_20
d2921d998c611c18328dd523daf976a27ce858c1
[ "MIT" ]
8
2021-06-08T22:30:29.000Z
2022-03-12T00:48:55.000Z
Diena_7_functions/uzd3_g1.py
edzya/Python_RTU_08_20
d2921d998c611c18328dd523daf976a27ce858c1
[ "MIT" ]
12
2020-09-28T17:06:52.000Z
2022-02-17T12:12:46.000Z
# https://github.com/Narusi/Python-Kurss/blob/master/Python_Uzdevums_Funkcijas.ipynb def get_city_year(p0, perc, delta, p): years = 0 while p0 < p and years <= 10_000: p0 += p0 * perc/100 + delta years += 1 if years >= 10_000: years = -1 return years print( f'get_city_year(1000, 2, -50, 5000) -> {get_city_year(1000, 2, -50, 5000)}') print( f'get_city_year(1500, 5, 100, 5000) -> {get_city_year(1500, 5, 100, 5000)}') print( f'get_city_year(1500000, 2.5, 10000, 2000000) -> {get_city_year(1500000, 2.5, 10000, 2000000)}')
28.95
100
0.626943
94
579
3.670213
0.425532
0.142029
0.223188
0.113043
0.498551
0.481159
0.446377
0.185507
0
0
0
0.236842
0.212435
579
19
101
30.473684
0.519737
0.141623
0
0.214286
0
0.214286
0.476768
0.090909
0
0
0
0
0
1
0.071429
false
0
0
0
0.142857
0.214286
0
0
0
null
0
1
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
a3ce8a5c783a78fe1255a72f2d1ccddc67e719a2
395
py
Python
sfdo_template_helpers/crypto.py
oddbird/sfdo-template-helpers
11a95ee64e3f54824d4039e34d0f172aa8d01e4b
[ "BSD-3-Clause" ]
4
2019-05-08T16:11:03.000Z
2021-12-24T19:35:48.000Z
sfdo_template_helpers/crypto.py
oddbird/sfdo-template-helpers
11a95ee64e3f54824d4039e34d0f172aa8d01e4b
[ "BSD-3-Clause" ]
12
2018-11-28T23:29:51.000Z
2020-03-31T21:57:11.000Z
sfdo_template_helpers/crypto.py
oddbird/sfdo-template-helpers
11a95ee64e3f54824d4039e34d0f172aa8d01e4b
[ "BSD-3-Clause" ]
5
2018-11-28T21:19:07.000Z
2021-06-26T17:52:04.000Z
from cryptography.fernet import Fernet from django.conf import settings FERNET = Fernet(settings.DB_ENCRYPTION_KEY) def fernet_encrypt(s): """Encrypt a string using cryptography.fernet""" return FERNET.encrypt(s.encode("utf-8")).decode("utf-8") def fernet_decrypt(s): """Decrypt a string using cryptography.fernet""" return FERNET.decrypt(s.encode("utf-8")).decode("utf-8")
26.333333
60
0.731646
56
395
5.089286
0.392857
0.05614
0.098246
0.168421
0.442105
0.442105
0.442105
0
0
0
0
0.011594
0.126582
395
14
61
28.214286
0.814493
0.21519
0
0
0
0
0.06689
0
0
0
0
0
0
1
0.285714
false
0
0.285714
0
0.857143
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
a3dad6cac5ff059141182ca2ee556fe1ac2b5f33
2,118
py
Python
waterbutler/providers/dataverse/metadata.py
birdbrained/waterbutler
60a6eb7f2dfce88b7a00457034c01b20da0aef23
[ "Apache-2.0" ]
null
null
null
waterbutler/providers/dataverse/metadata.py
birdbrained/waterbutler
60a6eb7f2dfce88b7a00457034c01b20da0aef23
[ "Apache-2.0" ]
null
null
null
waterbutler/providers/dataverse/metadata.py
birdbrained/waterbutler
60a6eb7f2dfce88b7a00457034c01b20da0aef23
[ "Apache-2.0" ]
null
null
null
from waterbutler.core import metadata class BaseDataverseMetadata(metadata.BaseMetadata): @property def provider(self): return 'dataverse' class DataverseFileMetadata(BaseDataverseMetadata, metadata.BaseFileMetadata): def __init__(self, raw, dataset_version): super().__init__(raw) self.dataset_version = dataset_version # Note: If versioning by number is added, this will have to check # all published versions, not just 'latest-published'. self.has_published_version = dataset_version == 'latest-published' @property def file_id(self): return str(self.raw['id']) @property def name(self): return self.raw['name'] @property def path(self): return self.build_path(self.file_id) @property def materialized_path(self): return '/' + self.name @property def size(self): return None @property def content_type(self): return self.raw['contentType'] @property def modified(self): return None @property def etag(self): return '{}::{}'.format(self.dataset_version, self.file_id) @property def extra(self): return { 'fileId': self.file_id, 'datasetVersion': self.dataset_version, 'hasPublishedVersion': self.has_published_version, } class DataverseDatasetMetadata(BaseDataverseMetadata, metadata.BaseFolderMetadata): def __init__(self, raw, name, doi, version): super().__init__(raw) self._name = name self.doi = doi files = self.raw['files'] self.contents = [DataverseFileMetadata(f['datafile'], version) for f in files] @property def name(self): return self._name @property def path(self): return self.build_path(self.doi) class DataverseRevision(metadata.BaseFileRevisionMetadata): @property def version_identifier(self): return 'version' @property def version(self): return self.raw @property def modified(self): return None
22.531915
86
0.640227
225
2,118
5.862222
0.315556
0.125095
0.074299
0.038666
0.276725
0.185747
0.06975
0.06975
0.06975
0.06975
0
0
0.26204
2,118
93
87
22.774194
0.84389
0.054769
0
0.40625
0
0
0.054027
0
0
0
0
0
0
1
0.265625
false
0
0.015625
0.234375
0.578125
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
a3e5a5136c529b647d3ad04436e15368daf4e7b4
26
py
Python
test/__init__.py
mendrugory/torip
4a7acb49824f84979e8aeaac3ead442be9e675e2
[ "MIT" ]
7
2015-10-31T15:17:18.000Z
2017-10-27T07:12:09.000Z
test/__init__.py
mendrugory/torip
4a7acb49824f84979e8aeaac3ead442be9e675e2
[ "MIT" ]
2
2021-09-22T16:20:52.000Z
2021-09-23T10:19:02.000Z
test/__init__.py
mendrugory/torip
4a7acb49824f84979e8aeaac3ead442be9e675e2
[ "MIT" ]
null
null
null
__author__ = 'mendrugory'
13
25
0.769231
2
26
8
1
0
0
0
0
0
0
0
0
0
0
0
0.115385
26
1
26
26
0.695652
0
0
0
0
0
0.384615
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
431738a2ea759101d00dbb58b617f55667b7318a
155
py
Python
examens/urls.py
adrienlachaize/dezede
584ec30cedab95152e2f95595b7691a04e6736e2
[ "BSD-3-Clause" ]
15
2015-02-10T21:16:31.000Z
2021-03-25T16:46:20.000Z
examens/urls.py
adrienlachaize/dezede
584ec30cedab95152e2f95595b7691a04e6736e2
[ "BSD-3-Clause" ]
4
2021-02-10T15:42:08.000Z
2022-03-11T23:20:38.000Z
examens/urls.py
adrienlachaize/dezede
584ec30cedab95152e2f95595b7691a04e6736e2
[ "BSD-3-Clause" ]
6
2016-07-10T14:20:48.000Z
2022-01-19T18:34:02.000Z
from django.conf.urls import url from .views import TakeLevelView urlpatterns = [ url(r'^source$', TakeLevelView.as_view(), name='source_examen'), ]
19.375
68
0.729032
20
155
5.55
0.75
0
0
0
0
0
0
0
0
0
0
0
0.135484
155
7
69
22.142857
0.828358
0
0
0
0
0
0.135484
0
0
0
0
0
0
1
0
false
0
0.4
0
0.4
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
431a29f36a2cb1c4a803344dc4bd7de123556b4d
10,764
py
Python
47/swagger_client/models/wordnet_similarity_response_entity.py
apitore/apitore-sdk-python
c0814c5635ddd09e9a20fcb155b62122bee41d33
[ "Apache-2.0" ]
3
2018-08-21T06:14:33.000Z
2019-10-18T23:05:50.000Z
47/swagger_client/models/wordnet_similarity_response_entity.py
apitore/apitore-sdk-python
c0814c5635ddd09e9a20fcb155b62122bee41d33
[ "Apache-2.0" ]
null
null
null
47/swagger_client/models/wordnet_similarity_response_entity.py
apitore/apitore-sdk-python
c0814c5635ddd09e9a20fcb155b62122bee41d33
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ WordNet Similarity APIs Calculate word similarity.<BR />[Endpoint] https://api.apitore.com/api/47 # noqa: E501 OpenAPI spec version: 0.0.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class WordnetSimilarityResponseEntity(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'end_time': 'str', 'log': 'str', 'method': 'str', 'pos1': 'str', 'pos2': 'str', 'process_time': 'str', 'similarity': 'float', 'start_time': 'str', 'word1': 'str', 'word2': 'str' } attribute_map = { 'end_time': 'endTime', 'log': 'log', 'method': 'method', 'pos1': 'pos1', 'pos2': 'pos2', 'process_time': 'processTime', 'similarity': 'similarity', 'start_time': 'startTime', 'word1': 'word1', 'word2': 'word2' } def __init__(self, end_time=None, log=None, method=None, pos1=None, pos2=None, process_time=None, similarity=None, start_time=None, word1=None, word2=None): # noqa: E501 """WordnetSimilarityResponseEntity - a model defined in Swagger""" # noqa: E501 self._end_time = None self._log = None self._method = None self._pos1 = None self._pos2 = None self._process_time = None self._similarity = None self._start_time = None self._word1 = None self._word2 = None self.discriminator = None self.end_time = end_time self.log = log self.method = method if pos1 is not None: self.pos1 = pos1 if pos2 is not None: self.pos2 = pos2 self.process_time = process_time self.similarity = similarity self.start_time = start_time self.word1 = word1 self.word2 = word2 @property def end_time(self): """Gets the end_time of this WordnetSimilarityResponseEntity. # noqa: E501 End date # noqa: E501 :return: The end_time of this WordnetSimilarityResponseEntity. # noqa: E501 :rtype: str """ return self._end_time @end_time.setter def end_time(self, end_time): """Sets the end_time of this WordnetSimilarityResponseEntity. End date # noqa: E501 :param end_time: The end_time of this WordnetSimilarityResponseEntity. # noqa: E501 :type: str """ if end_time is None: raise ValueError("Invalid value for `end_time`, must not be `None`") # noqa: E501 self._end_time = end_time @property def log(self): """Gets the log of this WordnetSimilarityResponseEntity. # noqa: E501 Log message # noqa: E501 :return: The log of this WordnetSimilarityResponseEntity. # noqa: E501 :rtype: str """ return self._log @log.setter def log(self, log): """Sets the log of this WordnetSimilarityResponseEntity. Log message # noqa: E501 :param log: The log of this WordnetSimilarityResponseEntity. # noqa: E501 :type: str """ if log is None: raise ValueError("Invalid value for `log`, must not be `None`") # noqa: E501 self._log = log @property def method(self): """Gets the method of this WordnetSimilarityResponseEntity. # noqa: E501 Method # noqa: E501 :return: The method of this WordnetSimilarityResponseEntity. # noqa: E501 :rtype: str """ return self._method @method.setter def method(self, method): """Sets the method of this WordnetSimilarityResponseEntity. Method # noqa: E501 :param method: The method of this WordnetSimilarityResponseEntity. # noqa: E501 :type: str """ if method is None: raise ValueError("Invalid value for `method`, must not be `None`") # noqa: E501 self._method = method @property def pos1(self): """Gets the pos1 of this WordnetSimilarityResponseEntity. # noqa: E501 Pos1 # noqa: E501 :return: The pos1 of this WordnetSimilarityResponseEntity. # noqa: E501 :rtype: str """ return self._pos1 @pos1.setter def pos1(self, pos1): """Sets the pos1 of this WordnetSimilarityResponseEntity. Pos1 # noqa: E501 :param pos1: The pos1 of this WordnetSimilarityResponseEntity. # noqa: E501 :type: str """ self._pos1 = pos1 @property def pos2(self): """Gets the pos2 of this WordnetSimilarityResponseEntity. # noqa: E501 Pos2 # noqa: E501 :return: The pos2 of this WordnetSimilarityResponseEntity. # noqa: E501 :rtype: str """ return self._pos2 @pos2.setter def pos2(self, pos2): """Sets the pos2 of this WordnetSimilarityResponseEntity. Pos2 # noqa: E501 :param pos2: The pos2 of this WordnetSimilarityResponseEntity. # noqa: E501 :type: str """ self._pos2 = pos2 @property def process_time(self): """Gets the process_time of this WordnetSimilarityResponseEntity. # noqa: E501 Process time [millisecond] # noqa: E501 :return: The process_time of this WordnetSimilarityResponseEntity. # noqa: E501 :rtype: str """ return self._process_time @process_time.setter def process_time(self, process_time): """Sets the process_time of this WordnetSimilarityResponseEntity. Process time [millisecond] # noqa: E501 :param process_time: The process_time of this WordnetSimilarityResponseEntity. # noqa: E501 :type: str """ if process_time is None: raise ValueError("Invalid value for `process_time`, must not be `None`") # noqa: E501 self._process_time = process_time @property def similarity(self): """Gets the similarity of this WordnetSimilarityResponseEntity. # noqa: E501 Similarity # noqa: E501 :return: The similarity of this WordnetSimilarityResponseEntity. # noqa: E501 :rtype: float """ return self._similarity @similarity.setter def similarity(self, similarity): """Sets the similarity of this WordnetSimilarityResponseEntity. Similarity # noqa: E501 :param similarity: The similarity of this WordnetSimilarityResponseEntity. # noqa: E501 :type: float """ if similarity is None: raise ValueError("Invalid value for `similarity`, must not be `None`") # noqa: E501 self._similarity = similarity @property def start_time(self): """Gets the start_time of this WordnetSimilarityResponseEntity. # noqa: E501 Start date # noqa: E501 :return: The start_time of this WordnetSimilarityResponseEntity. # noqa: E501 :rtype: str """ return self._start_time @start_time.setter def start_time(self, start_time): """Sets the start_time of this WordnetSimilarityResponseEntity. Start date # noqa: E501 :param start_time: The start_time of this WordnetSimilarityResponseEntity. # noqa: E501 :type: str """ if start_time is None: raise ValueError("Invalid value for `start_time`, must not be `None`") # noqa: E501 self._start_time = start_time @property def word1(self): """Gets the word1 of this WordnetSimilarityResponseEntity. # noqa: E501 Word1 # noqa: E501 :return: The word1 of this WordnetSimilarityResponseEntity. # noqa: E501 :rtype: str """ return self._word1 @word1.setter def word1(self, word1): """Sets the word1 of this WordnetSimilarityResponseEntity. Word1 # noqa: E501 :param word1: The word1 of this WordnetSimilarityResponseEntity. # noqa: E501 :type: str """ if word1 is None: raise ValueError("Invalid value for `word1`, must not be `None`") # noqa: E501 self._word1 = word1 @property def word2(self): """Gets the word2 of this WordnetSimilarityResponseEntity. # noqa: E501 Word2 # noqa: E501 :return: The word2 of this WordnetSimilarityResponseEntity. # noqa: E501 :rtype: str """ return self._word2 @word2.setter def word2(self, word2): """Sets the word2 of this WordnetSimilarityResponseEntity. Word2 # noqa: E501 :param word2: The word2 of this WordnetSimilarityResponseEntity. # noqa: E501 :type: str """ if word2 is None: raise ValueError("Invalid value for `word2`, must not be `None`") # noqa: E501 self._word2 = word2 def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, WordnetSimilarityResponseEntity): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
28.704
174
0.591323
1,167
10,764
5.342759
0.113967
0.078268
0.23737
0.197273
0.529431
0.432237
0.407217
0.265437
0.132959
0.044427
0
0.038744
0.316611
10,764
374
175
28.780749
0.808864
0.40236
0
0.075949
1
0
0.11831
0
0
0
0
0
0
1
0.164557
false
0
0.018987
0
0.303797
0.012658
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
431aee2a6aa3aceaa5db46007332158ec5a9f952
84
py
Python
lesson-05/05/join.py
minimum-hsu/tutorial-python
667692e7cd13a8a4d061a4da530dc2dfe25ac1de
[ "MIT" ]
null
null
null
lesson-05/05/join.py
minimum-hsu/tutorial-python
667692e7cd13a8a4d061a4da530dc2dfe25ac1de
[ "MIT" ]
null
null
null
lesson-05/05/join.py
minimum-hsu/tutorial-python
667692e7cd13a8a4d061a4da530dc2dfe25ac1de
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 names = ['Alice', 'Bob', 'Charlie'] print(', '.join(names))
16.8
35
0.595238
11
84
4.545455
0.909091
0
0
0
0
0
0
0
0
0
0
0.013514
0.119048
84
4
36
21
0.662162
0.25
0
0
0
0
0.274194
0
0
0
0
0
0
1
0
false
0
0
0
0
0.5
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
3
43232360e8a44da575a0dd62395f791880d04c3d
334
py
Python
tests/compat.py
lucasalves747/requests
bb30a9de93e1594f37e0ab2037329912b1091d89
[ "Apache-2.0" ]
null
null
null
tests/compat.py
lucasalves747/requests
bb30a9de93e1594f37e0ab2037329912b1091d89
[ "Apache-2.0" ]
null
null
null
tests/compat.py
lucasalves747/requests
bb30a9de93e1594f37e0ab2037329912b1091d89
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from requests.compat import is_py3 try: import StringIO except ImportError: import io as StringIO try: from cStringIO import StringIO as cStringIO except ImportError: cStringIO = None if is_py3: def u(s): return s else: def u(s): return s.decode('unicode-escape')
14.521739
47
0.652695
46
334
4.695652
0.565217
0.046296
0.046296
0.101852
0.111111
0
0
0
0
0
0
0.012146
0.260479
334
22
48
15.181818
0.862348
0.062874
0
0.4
0
0
0.045016
0
0
0
0
0
0
1
0.133333
false
0
0.4
0.133333
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
1
1
0
0
3
432c0d94bcce3675a7e64cb732c12535d0bb8570
416
py
Python
backend/tests/test_bcrypt_hash.py
fjacob21/mididecweb
b65f28eb6fdeafa265796b6190a4264a5eac54ce
[ "MIT" ]
null
null
null
backend/tests/test_bcrypt_hash.py
fjacob21/mididecweb
b65f28eb6fdeafa265796b6190a4264a5eac54ce
[ "MIT" ]
88
2016-11-12T14:54:38.000Z
2018-08-02T00:25:07.000Z
backend/tests/test_bcrypt_hash.py
mididecouverte/mididecweb
b65f28eb6fdeafa265796b6190a4264a5eac54ce
[ "MIT" ]
null
null
null
from src.bcrypt_hash import BcryptHash def test_bcrypt_encrypt(): password = BcryptHash('password').encrypt() assert password assert type(password) == str password2 = BcryptHash('password', password.encode()).encrypt() assert password2 assert password2 == password password3 = BcryptHash('badpassword', password.encode()).encrypt() assert password3 assert password3 != password
29.714286
70
0.71875
42
416
7.047619
0.404762
0.131757
0.141892
0.182432
0
0
0
0
0
0
0
0.017493
0.175481
416
13
71
32
0.845481
0
0
0
0
0
0.064904
0
0
0
0
0
0.545455
1
0.090909
false
0.818182
0.090909
0
0.181818
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
1
0
0
0
0
0
3
4a37f7650d7ed5321be2fcb0b93ef029fa22c65d
2,436
py
Python
python/old/resources.py
BenOsborn/Cerci
5785ae0c9db8a88a5ac8d91aed29cdf0c0c7854a
[ "Apache-2.0" ]
null
null
null
python/old/resources.py
BenOsborn/Cerci
5785ae0c9db8a88a5ac8d91aed29cdf0c0c7854a
[ "Apache-2.0" ]
null
null
null
python/old/resources.py
BenOsborn/Cerci
5785ae0c9db8a88a5ac8d91aed29cdf0c0c7854a
[ "Apache-2.0" ]
null
null
null
from random import random from math import exp, tanh def dot(arr1, arr2): if (len(arr1) != len(arr2)): raise Exception(f"Arrays are not of same length! Arr1 Length: {len(arr1)} | Arr2 Length: {len(arr2)}") return sum([one*two for one, two in zip(arr1, arr2)]) def error(arr1, arr2): if (len(arr1) != len(arr2)): raise Exception(f"Arrays are not of same length! Arr1 Length: {len(arr1)} | Arr2 Length: {len(arr2)}") return sum([abs(one - two) for one, two in zip(arr1, arr2)]) def relu(x, deriv=False): if not deriv: return x if x > 0 else 0.1*x # This is because we pass through the eigmoid value, and therefore the value is not raw and does not need to be parsed as a eigmoid value as it already is one return 1 if x > 0 else 0.1 def sigmoid(x, deriv=False): if not deriv: return 1/(1+exp(-x)) return x*(1-x) def learnFunc(x): return 0.5*abs(tanh(4*x)) # One thing to remember is that the values can have multiple outputs but they just have to be put into array values # For a single layer network def trainData(): # For a single layer networ weightsSingle = [ [[random(), random(), random()], [random(), random(), random()], [random(), random(), random()]] ] biasSingle = [ random() ] # For a double layer network weightsDouble = [ [[random(), random(), random()], [random(), random(), random()], [random(), random(), random()], [random(), random(), random()], [random(), random(), random()]], [[random(), random(), random(), random(), random()], [random(), random(), random(), random(), random()], [random(), random(), random(), random(), random()]] ] biasDouble = [ random(), random() ] # For a multi layer network weightsMulti = [ [[random(), random(), random()], [random(), random(), random()], [random(), random(), random()]], [[random(), random(), random()], [random(), random(), random()], [random(), random(), random()]], [[random(), random(), random()], [random(), random(), random()], [random(), random(), random()]] ] biasMulti = [ random(), random(), random() ] return { "weightsSingle": weightsSingle, "biasSingle": biasSingle, "weightsDouble": weightsDouble, "biasDouble": biasDouble, "weightsMulti": weightsMulti, "biasMulti": biasMulti }
37.476923
169
0.585386
303
2,436
4.706271
0.293729
0.5554
0.769986
0.959327
0.521739
0.521739
0.507714
0.469846
0.469846
0.431978
0
0.017761
0.237274
2,436
65
170
37.476923
0.749731
0.154351
0
0.291667
0
0.041667
0.112463
0
0
0
0
0
0
1
0.125
false
0
0.041667
0.020833
0.333333
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
4a59ba98dc0ab3d8ab04bcdff14e2a82ef1859f4
3,095
py
Python
tests/unit/bokeh/models/test_tools.py
dkapitan/bokeh
d518cecd1d9919db49e3c0033e8c1b89db9965bf
[ "BSD-3-Clause" ]
1
2020-02-07T16:57:56.000Z
2020-02-07T16:57:56.000Z
tests/unit/bokeh/models/test_tools.py
dkapitan/bokeh
d518cecd1d9919db49e3c0033e8c1b89db9965bf
[ "BSD-3-Clause" ]
1
2021-05-11T23:19:27.000Z
2021-05-11T23:19:27.000Z
tests/unit/bokeh/models/test_tools.py
dkapitan/bokeh
d518cecd1d9919db49e3c0033e8c1b89db9965bf
[ "BSD-3-Clause" ]
1
2020-03-06T07:38:50.000Z
2020-03-06T07:38:50.000Z
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- # TODO (bev) validate entire list of props #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # External imports import mock # Bokeh imports from bokeh.core.validation import check_integrity from bokeh.models import LayoutDOM # Module under test from bokeh.models.tools import Toolbar, ToolbarBox # isort:skip #----------------------------------------------------------------------------- # Setup #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def test_Toolbar() -> None: tb = Toolbar() assert tb.active_drag == 'auto' assert tb.active_inspect == 'auto' assert tb.active_scroll == 'auto' assert tb.active_tap == 'auto' assert tb.autohide is False def test_Toolbar_with_autohide() -> None: tb = Toolbar(autohide=True) assert tb.active_drag == 'auto' assert tb.active_inspect == 'auto' assert tb.active_scroll == 'auto' assert tb.active_tap == 'auto' assert tb.autohide is True # # ToolbarBox # def test_toolbar_box_is_instance_of_LayoutDOM() -> None: tb_box = ToolbarBox() assert isinstance(tb_box, LayoutDOM) def test_toolbar_box_properties() -> None: tb_box = ToolbarBox() assert tb_box.toolbar_location == "right" @mock.patch('bokeh.io.showing._show_with_state') def test_toolbar_box_with_no_children_does_not_raise_a_bokeh_warning(mock__show_with_state) -> None: # This is the normal way a ToolbarBox would be instantiated for example in # a gridplot. So we don't want to worry people with warnings. The children # for the ToolbarBox are created on the JS side. tb_box = ToolbarBox() with mock.patch('bokeh.core.validation.check.log') as mock_logger: check_integrity([tb_box]) assert mock_logger.warning.call_count == 0 #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
34.775281
100
0.428433
261
3,095
4.885057
0.444444
0.06902
0.087843
0.084706
0.211765
0.172549
0.172549
0.172549
0.172549
0.172549
0
0.003285
0.114701
3,095
88
101
35.170455
0.462044
0.570275
0
0.354839
0
0
0.078173
0.049536
0
0
0
0.011364
0.419355
1
0.16129
false
0
0.16129
0
0.322581
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
1
1
0
0
0
0
0
0
0
0
0
3
4a5eaaeef9380ab39354446a06f177452cfcbd76
613
py
Python
test/jpypetest/test_zzz.py
baztian/jpype
034d44e6c719995c25e9cd61348ebc1860030a9b
[ "Apache-2.0" ]
null
null
null
test/jpypetest/test_zzz.py
baztian/jpype
034d44e6c719995c25e9cd61348ebc1860030a9b
[ "Apache-2.0" ]
null
null
null
test/jpypetest/test_zzz.py
baztian/jpype
034d44e6c719995c25e9cd61348ebc1860030a9b
[ "Apache-2.0" ]
null
null
null
import sys import _jpype import jpype from jpype.types import * from jpype import JPackage, java import common import pytest try: import numpy as np except ImportError: pass class ZZZTestCase(common.JPypeTestCase): def setUp(self): common.JPypeTestCase.setUp(self) def testShutdown(self): # Install a coverage hook instance = JClass("org.jpype.JPypeContext").getInstance() JClass("jpype.common.OnShutdown").addCoverageHook(instance) # Shutdown jpype.shutdownJVM() # Check that shutdown does not raise jpype._core._JTerminate()
21.137931
67
0.693312
69
613
6.115942
0.623188
0.052133
0
0
0
0
0
0
0
0
0
0
0.228385
613
28
68
21.892857
0.892178
0.109299
0
0
0
0
0.083026
0.083026
0
0
0
0
0
1
0.105263
false
0.052632
0.473684
0
0.631579
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
1
0
1
0
0
3
4a73282304dbc1c6887a9d363c48ab9b4e0a647d
545
py
Python
TestScripts/test_encodeCategoricalFeaturesInDF.py
VigneshBaskar/team_darts
a2b5f2b5e79661b05b4e85a602ced1f264745a8c
[ "Apache-2.0" ]
null
null
null
TestScripts/test_encodeCategoricalFeaturesInDF.py
VigneshBaskar/team_darts
a2b5f2b5e79661b05b4e85a602ced1f264745a8c
[ "Apache-2.0" ]
null
null
null
TestScripts/test_encodeCategoricalFeaturesInDF.py
VigneshBaskar/team_darts
a2b5f2b5e79661b05b4e85a602ced1f264745a8c
[ "Apache-2.0" ]
null
null
null
import os import pandas as pd from unittest import TestCase from Scripts.EncodeCategoricalFeaturesInDF import EncodeCategoricalFeaturesInDF class TestEncodeCategoricalFeaturesInDF(TestCase): def test_encode_features(self): encoding_object = EncodeCategoricalFeaturesInDF() application_test = pd.read_csv(os.path.join('Data', 'application_test.csv')) application_test_encoded_df = encoding_object.encode_features(application_test) self.assertEqual(application_test.shape, application_test_encoded_df.shape)
38.928571
87
0.811009
58
545
7.344828
0.5
0.211268
0.103286
0.112676
0
0
0
0
0
0
0
0
0.126606
545
13
88
41.923077
0.894958
0
0
0
0
0
0.044037
0
0
0
0
0
0.1
1
0.1
false
0
0.4
0
0.6
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
4a75988f5c8e5c2eea6c0da4cb3930f19505c23e
71
py
Python
launcher.py
InFTord/updated-discord.py-tutorial
7e4363a1b10c03722382be0f1b0af6adcab95aa7
[ "BSD-3-Clause" ]
null
null
null
launcher.py
InFTord/updated-discord.py-tutorial
7e4363a1b10c03722382be0f1b0af6adcab95aa7
[ "BSD-3-Clause" ]
null
null
null
launcher.py
InFTord/updated-discord.py-tutorial
7e4363a1b10c03722382be0f1b0af6adcab95aa7
[ "BSD-3-Clause" ]
null
null
null
from lib.bot import bot VERSION = "0.0.27" # Part 31 bot.run(VERSION)
14.2
28
0.690141
14
71
3.5
0.714286
0
0
0
0
0
0
0
0
0
0
0.101695
0.169014
71
5
29
14.2
0.728814
0.098592
0
0
0
0
0.095238
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
4a86307da2c62e070c21f58f6258d6652a94b3e0
353
py
Python
misago/misago/conf/migrations/0002_cache_version.py
vascoalramos/misago-deployment
20226072138403108046c0afad9d99eb4163cedc
[ "MIT" ]
2
2021-03-06T21:06:13.000Z
2021-03-09T15:05:12.000Z
misago/misago/conf/migrations/0002_cache_version.py
vascoalramos/misago-deployment
20226072138403108046c0afad9d99eb4163cedc
[ "MIT" ]
null
null
null
misago/misago/conf/migrations/0002_cache_version.py
vascoalramos/misago-deployment
20226072138403108046c0afad9d99eb4163cedc
[ "MIT" ]
null
null
null
# Generated by Django 1.11.16 on 2018-12-02 15:54 from django.db import migrations from .. import SETTINGS_CACHE from ...cache.operations import StartCacheVersioning class Migration(migrations.Migration): dependencies = [("misago_conf", "0001_initial"), ("misago_cache", "0001_initial")] operations = [StartCacheVersioning(SETTINGS_CACHE)]
27.153846
86
0.76204
43
353
6.116279
0.627907
0.098859
0
0
0
0
0
0
0
0
0
0.080906
0.124646
353
12
87
29.416667
0.770227
0.133144
0
0
1
0
0.154605
0
0
0
0
0
0
1
0
false
0
0.5
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
4a8a52337576785a05bde6c25e7fb97a1675bf12
503
py
Python
lib/sqlalchemy/events.py
petit87/sqlalchemy
67d674bd63ca36ac32b23f96e2b19e9dac6b0863
[ "MIT" ]
null
null
null
lib/sqlalchemy/events.py
petit87/sqlalchemy
67d674bd63ca36ac32b23f96e2b19e9dac6b0863
[ "MIT" ]
null
null
null
lib/sqlalchemy/events.py
petit87/sqlalchemy
67d674bd63ca36ac32b23f96e2b19e9dac6b0863
[ "MIT" ]
1
2022-02-28T20:16:29.000Z
2022-02-28T20:16:29.000Z
# sqlalchemy/events.py # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php """Core event interfaces.""" from __future__ import annotations from .engine.events import ConnectionEvents from .engine.events import DialectEvents from .pool.events import PoolEvents from .sql.base import SchemaEventTarget from .sql.events import DDLEvents
29.588235
70
0.797217
68
503
5.838235
0.647059
0.120907
0.080605
0.110831
0
0
0
0
0
0
0
0.018141
0.12326
503
16
71
31.4375
0.882086
0.500994
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
3
4a96b46c731f39a74078d3ebae9f8fd83cd2b908
1,355
py
Python
flowcelltool/flowcells/tests/test_templatetags.py
bihealth/flowcelltool
6e16190fc34c54d834ecd23888a462f3af47611d
[ "MIT" ]
7
2016-10-12T12:56:09.000Z
2020-10-27T17:08:09.000Z
flowcelltool/flowcells/tests/test_templatetags.py
iamh2o/flowcelltool
6e16190fc34c54d834ecd23888a462f3af47611d
[ "MIT" ]
94
2016-10-24T06:28:31.000Z
2018-08-06T10:35:13.000Z
flowcelltool/flowcells/tests/test_templatetags.py
iamh2o/flowcelltool
6e16190fc34c54d834ecd23888a462f3af47611d
[ "MIT" ]
1
2022-03-23T15:57:16.000Z
2022-03-23T15:57:16.000Z
# -*- coding: utf-8 -*- """Tests for template tags """ from test_plus.test import TestCase from ..templatetags import flowcells_tags class TestSizify(TestCase): def test_kb(self): self.assertEquals( flowcells_tags.sizify(100), '0.1 kb') self.assertEquals( flowcells_tags.sizify(512000 - 1), '500.0 kb') def test_mb(self): self.assertEquals( flowcells_tags.sizify(512000), '0.49 mb') self.assertEquals( flowcells_tags.sizify(4194304000 - 1), '4000.0 mb') def test_gb(self): self.assertEquals( flowcells_tags.sizify(4194304000), '3.91 gb') self.assertEquals( flowcells_tags.sizify(1000 * 1000 * 1000 * 1000), '931.32 gb') class TestFAMimeType(TestCase): def test_pdf(self): self.assertEquals( flowcells_tags.fa_mime_type('application/pdf'), 'file-pdf-o') def test_xls(self): self.assertEquals(flowcells_tags.fa_mime_type( 'application/vnd.openxmlformats-officedocument.' 'spreadsheetml.sheet'), 'file-excel-o') def test_html(self): self.assertEquals( flowcells_tags.fa_mime_type('text/html'), 'file-text-o') def test_other(self): self.assertEquals( flowcells_tags.fa_mime_type(''), 'file-o')
27.1
74
0.617712
160
1,355
5.0625
0.3375
0.176543
0.308642
0.358025
0.553086
0.509877
0.239506
0.239506
0.133333
0
0
0.075472
0.256827
1,355
49
75
27.653061
0.728898
0.033948
0
0.272727
0
0
0.133641
0.03533
0
0
0
0
0.30303
1
0.212121
false
0
0.060606
0
0.333333
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
4a9ffd59087b2b9d8af238ab3e08cfeae1392678
223
py
Python
AtCoder/ABC078/D.py
takaaki82/Java-Lessons
c4f11462bf84c091527dde5f25068498bfb2cc49
[ "MIT" ]
1
2018-11-25T04:15:45.000Z
2018-11-25T04:15:45.000Z
AtCoder/ABC078/D.py
takaaki82/Java-Lessons
c4f11462bf84c091527dde5f25068498bfb2cc49
[ "MIT" ]
null
null
null
AtCoder/ABC078/D.py
takaaki82/Java-Lessons
c4f11462bf84c091527dde5f25068498bfb2cc49
[ "MIT" ]
2
2018-08-08T13:01:14.000Z
2018-11-25T12:38:36.000Z
N, Z, W = map(int, input().split()) a_list = [i for i in map(int, input().split())] if N == 1: print(abs(W-a_list[0])) exit() max_a = max(a_list) print(max(abs(a_list[-1]-W), abs(a_list[-2]-a_list[-1])))
20.272727
57
0.547085
46
223
2.5
0.434783
0.26087
0.191304
0.278261
0
0
0
0
0
0
0
0.027933
0.197309
223
10
58
22.3
0.614525
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.285714
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
4aae16dd02d2967193af057bd6dc401a1468e5c8
4,257
py
Python
static/data/db_artifacts.py
gentimouton/shop-heroes
778e46f7a148812be804ca714dd48b49749055fe
[ "MIT" ]
null
null
null
static/data/db_artifacts.py
gentimouton/shop-heroes
778e46f7a148812be804ca714dd48b49749055fe
[ "MIT" ]
null
null
null
static/data/db_artifacts.py
gentimouton/shop-heroes
778e46f7a148812be804ca714dd48b49749055fe
[ "MIT" ]
null
null
null
artifact_db = \ { 'adamantium': { 'level': 40, 'name': 'Adamantium', 'origin': 'Quest', 'tier': 3}, 'ancient-essence': { 'level': 42, 'name': 'Ancient Essence', 'origin': 'Quest', 'tier': 3}, 'burning-ember': { 'level': 8, 'name': 'Burning Ember', 'origin': 'Quest', 'tier': 1}, 'dark-energy': { 'level': 34, 'name': 'Dark Energy', 'origin': 'Quest', 'tier': 3}, 'demon-heart': { 'level': 32, 'name': 'Demon Heart', 'origin': 'Quest', 'tier': 3}, 'dragon-scale': { 'level': 38, 'name': 'Dragon Scale', 'origin': 'Quest', 'tier': 3}, 'elven-dew': { 'level': 3, 'name': 'Elven Dew', 'origin': 'Quest', 'tier': 1}, 'frostfire-crystal': { 'level': 44, 'name': 'Frostfire Crystal', 'origin': 'Quest', 'tier': 3}, 'frozen-core': { 'level': 18, 'name': 'Frozen Core', 'origin': 'Quest', 'tier': 2}, 'golden-thread': { 'level': 30, 'name': 'Golden Thread', 'origin': 'Quest', 'tier': 2}, 'iron-carapace': { 'level': 14, 'name': 'Iron Carapace', 'origin': 'Quest', 'tier': 1}, 'iron-wood': { 'level': 6, 'name': 'Iron Wood', 'origin': 'Quest', 'tier': 1}, 'liquid-fire': { 'level': 22, 'name': 'Liquid Fire', 'origin': 'Quest', 'tier': 2}, 'moon-shard': { 'level': 12, 'name': 'Moon Shard', 'origin': 'Quest', 'tier': 1}, 'obsidian-coral': { 'level': 46, 'name': 'Obsidian Coral', 'origin': 'Quest', 'tier': 3}, 'phoenix-feather': { 'level': 28, 'name': 'Phoenix Feather', 'origin': 'Quest', 'tier': 2}, 'primal-horn': { 'level': 50, 'name': 'Primal Horn', 'origin': 'City Raid', 'tier': 0}, 'rainbow-dust': { 'level': 10, 'name': 'Rainbow Dust', 'origin': 'Quest', 'tier': 1}, 'royal-bone': { 'level': 20, 'name': 'Royal Bone', 'origin': 'Quest', 'tier': 2}, 'shard-of-gaia': { 'level': 48, 'name': 'Shard Of Gaia', 'origin': 'City Raid', 'tier': 0}, 'shiny-gem': { 'level': 2, 'name': 'Shiny Gem', 'origin': 'Quest', 'tier': 1}, 'silver-steel': { 'level': 26, 'name': 'Silver Steel', 'origin': 'Quest', 'tier': 2}, 'sun-tear': { 'level': 36, 'name': 'Sun Tear', 'origin': 'Quest', 'tier': 3}, 'viper-essence': { 'level': 4, 'name': 'Viper Essence', 'origin': 'Quest', 'tier': 1}, 'wyvern-wing': { 'level': 16, 'name': 'Wyvern Wing', 'origin': 'Quest', 'tier': 1}, 'yggdrasil-leaf': { 'level': 24, 'name': 'Yggdrasil Leaf', 'origin': 'Quest', 'tier': 2}}
40.542857
57
0.299742
290
4,257
4.396552
0.296552
0.207059
0.282353
0.112941
0.029804
0
0
0
0
0
0
0.03734
0.540756
4,257
105
58
40.542857
0.614834
0
0
0.485714
0
0
0.292626
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
4ab6999ff0b444d9dc7f3f9f7f12fcb5ea41f3ca
831
py
Python
featureflags/rest/models/__init__.py
enverbisevac/ff-python-server-sdk
e7c809229d13517e0bf4b28fc0a556e693c9034e
[ "Apache-2.0" ]
null
null
null
featureflags/rest/models/__init__.py
enverbisevac/ff-python-server-sdk
e7c809229d13517e0bf4b28fc0a556e693c9034e
[ "Apache-2.0" ]
null
null
null
featureflags/rest/models/__init__.py
enverbisevac/ff-python-server-sdk
e7c809229d13517e0bf4b28fc0a556e693c9034e
[ "Apache-2.0" ]
null
null
null
""" Contains all the data models used in inputs/outputs """ from .authentication_request import AuthenticationRequest from .authentication_response import AuthenticationResponse from .clause import Clause from .distribution import Distribution from .error import Error from .evaluation import Evaluation from .evaluation_value import EvaluationValue from .evaluations import Evaluations from .feature_config import FeatureConfig from .feature_config_kind import FeatureConfigKind from .feature_state import FeatureState from .pagination import Pagination from .prerequisite import Prerequisite from .segment import Segment from .serve import Serve from .serving_rule import ServingRule from .tag import Tag from .variation import Variation from .variation_map import VariationMap from .weighted_variation import WeightedVariation
36.130435
59
0.858002
99
831
7.10101
0.434343
0.046942
0.048364
0
0
0
0
0
0
0
0
0
0.109507
831
22
60
37.772727
0.95
0.061372
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
3
435e327e69d8578a6ab012abeee69d684e47fd17
4,681
py
Python
tests/test_usfirst_legacy_event_details_parser.py
tervay/the-blue-alliance
e14c15cb04b455f90a2fcfdf4c1cdbf8454e17f8
[ "MIT" ]
1
2016-03-19T20:29:35.000Z
2016-03-19T20:29:35.000Z
tests/test_usfirst_legacy_event_details_parser.py
gregmarra/the-blue-alliance
5bedaf5c80b4623984760d3da3289640639112f9
[ "MIT" ]
11
2020-10-10T03:05:29.000Z
2022-02-27T09:57:22.000Z
tests/test_usfirst_legacy_event_details_parser.py
gregmarra/the-blue-alliance
5bedaf5c80b4623984760d3da3289640639112f9
[ "MIT" ]
null
null
null
import unittest2 import datetime from consts.event_type import EventType from datafeeds.usfirst_legacy_event_details_parser import UsfirstLegacyEventDetailsParser @unittest2.skip class TestUsfirstLegacyEventDetailsParser(unittest2.TestCase): def test_parse2012ct(self): with open('test_data/usfirst_legacy_html/usfirst_event_details_2012ct.html', 'r') as f: event, _ = UsfirstLegacyEventDetailsParser.parse(f.read()) self.assertEqual(event["name"], "Northeast Utilities FIRST Connecticut Regional") self.assertEqual(event["short_name"], "Northeast Utilities FIRST Connecticut") self.assertEqual(event["event_type_enum"], EventType.REGIONAL) self.assertEqual(event["start_date"], datetime.datetime(2012, 3, 29, 0, 0)) self.assertEqual(event["end_date"], datetime.datetime(2012, 3, 31, 0, 0)) self.assertEqual(event["year"], 2012) self.assertEqual(event["venue_address"], "Connecticut Convention Center\r\n100 Columbus Blvd\r\nHartford, CT 06103\r\nUSA") self.assertEqual(event["location"], "Hartford, CT, USA") self.assertEqual(event["website"], "http://www.ctfirst.org/ctr") self.assertEqual(event["event_short"], "ct") def test_parse2013flbr(self): with open('test_data/usfirst_legacy_html/usfirst_event_details_2013flbr.html', 'r') as f: event, _ = UsfirstLegacyEventDetailsParser.parse(f.read()) self.assertEqual(event["name"], "South Florida Regional") self.assertEqual(event["short_name"], "South Florida") self.assertEqual(event["event_type_enum"], EventType.REGIONAL) self.assertEqual(event["start_date"], datetime.datetime(2013, 3, 28, 0, 0)) self.assertEqual(event["end_date"], datetime.datetime(2013, 3, 30, 0, 0)) self.assertEqual(event["year"], 2013) self.assertEqual(event["venue_address"], "Great Fort Lauderdale & Broward County Convention Center\r\n1950 Eisenhower Boulevard\r\nFort Lauderdale, FL 33316\r\nUSA") self.assertEqual(event["location"], "Fort Lauderdale, FL, USA") self.assertEqual(event["website"], "http://firstinflorida.org") self.assertEqual(event["event_short"], "flbr") def test_parse2014casj(self): with open('test_data/usfirst_legacy_html/usfirst_event_details_2014casj.html', 'r') as f: event, _ = UsfirstLegacyEventDetailsParser.parse(f.read()) self.assertEqual(event["name"], "Silicon Valley Regional") self.assertEqual(event["short_name"], "Silicon Valley") self.assertEqual(event["event_type_enum"], EventType.REGIONAL) self.assertEqual(event["start_date"], datetime.datetime(2014, 4, 3, 0, 0)) self.assertEqual(event["end_date"], datetime.datetime(2014, 4, 5, 0, 0)) self.assertEqual(event["year"], 2014) self.assertEqual(event["venue_address"], "San Jose State University\r\nThe Event Center\r\nOne Washington Square\r\nSan Jose, CA 95112\r\nUSA") self.assertEqual(event["location"], "San Jose, CA, USA") self.assertEqual(event["website"], "http://www.firstsv.org") self.assertEqual(event["event_short"], "casj") def test_parse2014lake(self): with open('test_data/usfirst_legacy_html/usfirst_event_details_2014lake.html', 'r') as f: event, _ = UsfirstLegacyEventDetailsParser.parse(f.read()) self.assertEqual(event["name"], "Bayou Regional") self.assertEqual(event["short_name"], "Bayou") self.assertEqual(event["event_type_enum"], EventType.REGIONAL) self.assertEqual(event["start_date"], datetime.datetime(2014, 4, 3, 0, 0)) self.assertEqual(event["end_date"], datetime.datetime(2014, 4, 5, 0, 0)) self.assertEqual(event["year"], 2014) self.assertEqual(event["website"], "http://www.frcbayouregional.com") self.assertEqual(event["event_short"], "lake") def test_parse2014nvlv_preliminary(self): with open('test_data/usfirst_legacy_html/usfirst_event_details_2014nvlv_preliminary.html', 'r') as f: event, _ = UsfirstLegacyEventDetailsParser.parse(f.read()) self.assertEqual(event["name"], "Las Vegas Regional - Preliminary") self.assertEqual(event["short_name"], "Las Vegas") self.assertEqual(event["event_type_enum"], EventType.REGIONAL) self.assertEqual(event["start_date"], datetime.datetime(2014, 12, 31, 0, 0)) self.assertEqual(event["end_date"], datetime.datetime(2014, 12, 31, 0, 0)) self.assertEqual(event["year"], 2014) self.assertEqual(event["website"], "http://www.firstnv.org") self.assertEqual(event["event_short"], "nvlv")
58.5125
173
0.695364
563
4,681
5.639432
0.220249
0.217323
0.289764
0.07874
0.739843
0.660157
0.532283
0.500157
0.500157
0.471811
0
0.044088
0.161718
4,681
79
174
59.253165
0.765036
0
0
0.253731
0
0.029851
0.312754
0.071566
0
0
0
0
0.686567
1
0.074627
false
0
0.059701
0
0.149254
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
0
0
0
0
0
0
3
4370e6292e579802e4f244bc22438eaa4c21caac
339
py
Python
codewars/8kyu/doha22/kata8/playing_banjo/playing_banjo.py
doha22/Training_one
0cd7cf86c7da0f6175834146296b763d1841766b
[ "MIT" ]
null
null
null
codewars/8kyu/doha22/kata8/playing_banjo/playing_banjo.py
doha22/Training_one
0cd7cf86c7da0f6175834146296b763d1841766b
[ "MIT" ]
2
2019-01-22T10:53:42.000Z
2019-01-31T08:02:48.000Z
codewars/8kyu/doha22/kata8/playing_banjo/playing_banjo.py
doha22/Training_one
0cd7cf86c7da0f6175834146296b763d1841766b
[ "MIT" ]
13
2019-01-22T10:37:42.000Z
2019-01-25T13:30:43.000Z
def areYouPlayingBanjo(name): # Implement me! if (name.startswith("R") |name.startswith("r") ): return name + " "+"plays banjo" else: return name +" "+ "does not play banjo" # return name def areYouPlayingBanjo2(name): return name + (' plays' if name[0].lower() == 'r' else ' does not play') + " banjo";
33.9
88
0.59587
41
339
4.926829
0.439024
0.19802
0.148515
0.158416
0
0
0
0
0
0
0
0.007752
0.238938
339
10
88
33.9
0.775194
0.073746
0
0
0
0
0.195513
0
0
0
0
0
0
1
0.285714
false
0
0
0.142857
0.714286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
43766a2ff5183015b70d35d96509021c774f2992
136
py
Python
dataf/tests/__init__.py
BenjaminBoumendil/dataf
0579c65b10b5b48424d64cc6c007dbf68ad7e64d
[ "MIT" ]
null
null
null
dataf/tests/__init__.py
BenjaminBoumendil/dataf
0579c65b10b5b48424d64cc6c007dbf68ad7e64d
[ "MIT" ]
null
null
null
dataf/tests/__init__.py
BenjaminBoumendil/dataf
0579c65b10b5b48424d64cc6c007dbf68ad7e64d
[ "MIT" ]
null
null
null
class settings: DATABASE = { 'test': { 'url': 'postgresql://admin:password@localhost:5432/test' } }
19.428571
68
0.5
11
136
6.181818
0.909091
0
0
0
0
0
0
0
0
0
0
0.044944
0.345588
136
6
69
22.666667
0.719101
0
0
0
0
0
0.397059
0.345588
0
0
0
0
0
1
0
false
0.166667
0
0
0.333333
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
3
437a9de6f0887cef3b0a7abd049cf2d22c170040
279
py
Python
blueprints/aws/tenancy/diagram.py
micronode/bedrock
5dc6c1ab7e6e0801e2a2c3b556d565b36a567113
[ "MIT" ]
null
null
null
blueprints/aws/tenancy/diagram.py
micronode/bedrock
5dc6c1ab7e6e0801e2a2c3b556d565b36a567113
[ "MIT" ]
48
2015-12-07T02:12:09.000Z
2020-11-05T03:27:21.000Z
blueprints/aws/tenancy/diagram.py
micronode/bedrock
5dc6c1ab7e6e0801e2a2c3b556d565b36a567113
[ "MIT" ]
1
2020-05-05T05:19:25.000Z
2020-05-05T05:19:25.000Z
# diagram.py from diagrams import Diagram, Cluster from diagrams.aws.network import CloudMap, VPC with Diagram("AWS Tenancy", show=False, direction="RL"): with Cluster("dns"): CloudMap("private dns namespace") << VPC("vpc") CloudMap("public dns namespace")
27.9
56
0.695341
35
279
5.542857
0.571429
0.123711
0
0
0
0
0
0
0
0
0
0
0.175627
279
9
57
31
0.843478
0.035842
0
0
0
0
0.224719
0
0
0
0
0
0
1
0
true
0
0.333333
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
3
43859292910a325435a452907759586a392f2abf
422,590
py
Python
thermo/eos_mix.py
RoryKurek/thermo
985279467faa028234ab422a19b69385e5100149
[ "MIT" ]
380
2016-07-04T09:45:20.000Z
2022-03-20T18:09:45.000Z
thermo/eos_mix.py
RoryKurek/thermo
985279467faa028234ab422a19b69385e5100149
[ "MIT" ]
104
2016-07-10T20:47:12.000Z
2022-03-22T20:43:39.000Z
thermo/eos_mix.py
RoryKurek/thermo
985279467faa028234ab422a19b69385e5100149
[ "MIT" ]
96
2016-07-05T20:54:05.000Z
2022-02-23T03:06:02.000Z
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2016, 2017, 2018, 2019, 2020, 2021 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 implementations of most cubic equations of state for mixtures. This includes Peng-Robinson, SRK, Van der Waals, PRSV, TWU and many other variants. For reporting bugs, adding feature requests, or submitting pull requests, please use the `GitHub issue tracker <https://github.com/CalebBell/thermo/>`_. .. contents:: :local: Base Class ========== .. autoclass:: thermo.eos_mix.GCEOSMIX :members: :undoc-members: :show-inheritance: :exclude-members: a_alpha_and_derivatives_numpy, a_alpha_and_derivatives_py, main_derivatives_and_departures, derivatives_and_departures, sequential_substitution_3P, sequential_substitution_VL, stability_Michelsen, stability_iteration_Michelsen, newton_VL, broyden2_VL, d2A_dep_dninjs, d2A_dep_dninjs_Vt, d2A_dninjs_Vt, d2A_dninjs_Vt_another, d2P_dninjs_Vt, d2nA_dninjs_Vt, d3P_dninjnks_Vt, dScomp_dns, d2Scomp_dninjs, dA_dep_dns_Vt, dP_dns_Vt Peng-Robinson Family EOSs ========================= Standard Peng Robinson ---------------------- .. autoclass:: thermo.eos_mix.PRMIX :show-inheritance: :members: eos_pure, a_alphas_vectorized, a_alpha_and_derivatives_vectorized, d3a_alpha_dT3, d3a_alpha_dT3_vectorized, fugacity_coefficients, dlnphis_dT, dlnphis_dP, dlnphis_dzs, ddelta_dzs, ddelta_dns, d2delta_dzizjs, d2delta_dninjs, d3delta_dninjnks, depsilon_dzs, depsilon_dns, d2epsilon_dzizjs, d2epsilon_dninjs, d3epsilon_dninjnks Peng Robinson (1978) -------------------- .. autoclass:: thermo.eos_mix.PR78MIX :show-inheritance: :members: eos_pure Peng Robinson Stryjek-Vera -------------------------- .. autoclass:: thermo.eos_mix.PRSVMIX :show-inheritance: :members: eos_pure, a_alphas_vectorized, a_alpha_and_derivatives_vectorized Peng Robinson Stryjek-Vera 2 ---------------------------- .. autoclass:: thermo.eos_mix.PRSV2MIX :show-inheritance: :members: eos_pure, a_alphas_vectorized, a_alpha_and_derivatives_vectorized Peng Robinson Twu (1995) ------------------------ .. autoclass:: thermo.eos_mix.TWUPRMIX :show-inheritance: :members: eos_pure Peng Robinson Translated ------------------------ .. autoclass:: thermo.eos_mix.PRMIXTranslated :show-inheritance: :members: eos_pure, ddelta_dzs, d2delta_dzizjs, d3delta_dzizjzks, ddelta_dns, d2delta_dninjs, d3delta_dninjnks, depsilon_dzs, depsilon_dns, d2epsilon_dzizjs, d3epsilon_dzizjzks, d2epsilon_dninjs, d3epsilon_dninjnks Peng Robinson Translated-Consistent ----------------------------------- .. autoclass:: thermo.eos_mix.PRMIXTranslatedConsistent :show-inheritance: :members: eos_pure Peng Robinson Translated (Pina-Martinez, Privat, and Jaubert Variant) --------------------------------------------------------------------- .. autoclass:: thermo.eos_mix.PRMIXTranslatedPPJP :show-inheritance: :members: eos_pure SRK Family EOSs =============== Standard SRK ------------ .. autoclass:: thermo.eos_mix.SRKMIX :show-inheritance: :members: eos_pure, dlnphis_dT, dlnphis_dP, a_alphas_vectorized, a_alpha_and_derivatives_vectorized, fugacity_coefficients :exclude-members: Twu SRK (1995) -------------- .. autoclass:: thermo.eos_mix.TWUSRKMIX :show-inheritance: :members: eos_pure API SRK ------- .. autoclass:: thermo.eos_mix.APISRKMIX :show-inheritance: :members: eos_pure SRK Translated -------------- .. autoclass:: thermo.eos_mix.SRKMIXTranslated :show-inheritance: :members: eos_pure, ddelta_dzs, d2delta_dzizjs, d3delta_dzizjzks, ddelta_dns, d2delta_dninjs, d3delta_dninjnks, depsilon_dzs, depsilon_dns, d2epsilon_dzizjs, d3epsilon_dzizjzks, d2epsilon_dninjs, d3epsilon_dninjnks SRK Translated-Consistent ------------------------- .. autoclass:: thermo.eos_mix.SRKMIXTranslatedConsistent :show-inheritance: :members: eos_pure MSRK Translated --------------- .. autoclass:: thermo.eos_mix.MSRKMIXTranslated :show-inheritance: :members: eos_pure Cubic Equation of State with Activity Coefficients ================================================== .. autoclass:: thermo.eos_mix.PSRK :show-inheritance: :members: eos_pure Van der Waals Equation of State =============================== .. autoclass:: thermo.eos_mix.VDWMIX :show-inheritance: :members: eos_pure, dlnphis_dT, dlnphis_dP, a_alphas_vectorized, a_alpha_and_derivatives_vectorized, fugacity_coefficients, ddelta_dzs, ddelta_dns, d2delta_dzizjs, d2delta_dninjs, d3delta_dninjnks Redlich-Kwong Equation of State =============================== .. autoclass:: thermo.eos_mix.RKMIX :show-inheritance: :members: eos_pure, a_alphas_vectorized, a_alpha_and_derivatives_vectorized, ddelta_dzs, ddelta_dns, d2delta_dzizjs, d2delta_dninjs, d3delta_dninjnks Ideal Gas Equation of State =========================== .. autoclass:: thermo.eos_mix.IGMIX :show-inheritance: :members: eos_pure, a_alphas_vectorized, a_alpha_and_derivatives_vectorized Different Mixing Rules ====================== .. autoclass:: thermo.eos_mix.EpsilonZeroMixingRules .. autoclass:: thermo.eos_mix.PSRKMixingRules :members: u, A, a_alpha_and_derivatives :undoc-members: :show-inheritance: Lists of Equations of State =========================== .. autodata:: thermo.eos_mix.eos_mix_list .. autodata:: thermo.eos_mix.eos_mix_no_coeffs_list ''' from __future__ import division __all__ = ['GCEOSMIX', 'PRMIX', 'SRKMIX', 'PR78MIX', 'VDWMIX', 'PRSVMIX', 'PRSV2MIX', 'TWUPRMIX', 'TWUSRKMIX', 'APISRKMIX', 'IGMIX', 'RKMIX', 'PRMIXTranslatedConsistent', 'PRMIXTranslatedPPJP', 'PRMIXTranslated', 'SRKMIXTranslatedConsistent', 'PSRK', 'MSRKMIXTranslated', 'eos_mix_list', 'eos_mix_no_coeffs_list', 'SRKMIXTranslated'] import sys from cmath import log as clog from fluids.numerics import numpy as np, IS_PYPY, newton_system, broyden2, UnconvergedError, trunc_exp, solve_2_direct, catanh from fluids.numerics.arrays import det, subset_matrix from fluids.constants import R from chemicals.utils import normalize, dxs_to_dn_partials, dxs_to_dns, dns_to_dn_partials, d2xs_to_dxdn_partials, d2ns_to_dn2_partials from chemicals.utils import log, exp, sqrt from chemicals.rachford_rice import flash_inner_loop, Rachford_Rice_flash_error, Rachford_Rice_solution2 from chemicals.flash_basic import K_value, Wilson_K_value from thermo import serialize from thermo.eos_mix_methods import (a_alpha_aijs_composition_independent, a_alpha_aijs_composition_independent_support_zeros, a_alpha_and_derivatives, a_alpha_and_derivatives_full, a_alpha_quadratic_terms, a_alpha_and_derivatives_quadratic_terms, G_dep_lnphi_d_helper, eos_mix_dV_dzs, VDW_lnphis, SRK_lnphis, eos_mix_db_dns, PR_translated_ddelta_dns, PR_translated_depsilon_dns, PR_depsilon_dns, PR_translated_d2epsilon_dzizjs, PR_d2epsilon_dninjs, PR_d3epsilon_dninjnks, PR_d2delta_dninjs, PR_d3delta_dninjnks, PR_ddelta_dzs, PR_ddelta_dns, PR_d2epsilon_dzizjs, PR_depsilon_dzs, RK_d3delta_dninjnks, SRK_translated_d2epsilon_dzizjs, SRK_translated_depsilon_dzs, PR_translated_ddelta_dzs, PR_translated_depsilon_dzs, PR_translated_d2epsilon_dninjs, PR_translated_d2delta_dninjs, PR_translated_d3delta_dninjnks, PR_translated_d3epsilon_dninjnks, SRK_translated_ddelta_dns, SRK_translated_depsilon_dns, SRK_translated_d2delta_dninjs, SRK_translated_d2epsilon_dninjs, SRK_translated_d3epsilon_dninjnks, SRK_translated_d3delta_dninjnks) from thermo.eos_alpha_functions import (TwuPR95_a_alpha, TwuSRK95_a_alpha, Twu91_a_alpha, Mathias_Copeman_poly_a_alpha, Soave_1979_a_alpha, PR_a_alpha_and_derivatives_vectorized, PR_a_alphas_vectorized, RK_a_alpha_and_derivatives_vectorized, RK_a_alphas_vectorized, SRK_a_alpha_and_derivatives_vectorized, SRK_a_alphas_vectorized, PRSV_a_alphas_vectorized, PRSV_a_alpha_and_derivatives_vectorized, PRSV2_a_alphas_vectorized, PRSV2_a_alpha_and_derivatives_vectorized, APISRK_a_alphas_vectorized, APISRK_a_alpha_and_derivatives_vectorized) from thermo.eos import * try: (zeros, array, npexp, npsqrt, empty, full, npwhere, npmin, npmax) = ( np.zeros, np.array, np.exp, np.sqrt, np.empty, np.full, np.where, np.min, np.max) except: pass R2 = R*R R_inv = 1.0/R R2_inv = R_inv*R_inv two_root_two = 2*2**0.5 root_two = sqrt(2.) root_two_m1 = root_two - 1.0 root_two_p1 = root_two + 1.0 c1R2_PR = PR.c1R2 c2R_PR = PR.c2R class GCEOSMIX(GCEOS): r'''Class for solving a generic pressure-explicit three-parameter cubic equation of state for a mixture. Does not implement any parameters itself; must be subclassed by a mixture equation of state class which subclasses it. .. math:: P=\frac{RT}{V-b}-\frac{a\alpha(T)}{V^2 + \delta V + \epsilon} ''' nonstate_constants = ('N', 'cmps', 'Tcs', 'Pcs', 'omegas', 'kijs', 'kwargs', 'ais', 'bs') mix_kwargs_to_pure = {} kwargs_square = ('kijs',) '''Tuple of 2D arguments used by the specific EOS. ''' kwargs_linear = tuple() '''Tuple of 1D arguments used by the specific EOS in addition to the conventional ones. ''' multicomponent = True '''All inherited classes of GCEOSMIX are multicomponent. ''' scalar = True '''Whether the model is implemented using pure-Python lists of floats, or numpy arrays of float64. ''' translated = False '''Whether or not the model implements volume translation. ''' def subset(self, idxs, **state_specs): r'''Method to construct a new :obj:`GCEOSMIX` that removes all components not specified in the `idxs` argument. Parameters ---------- idxs : list[int] or Slice Indexes of components that should be included, [-] Returns ------- subset_eos : :obj:`GCEOSMIX` Multicomponent :obj:`GCEOSMIX` at the same specified specs but with a composition normalized to 1 and with fewer components, [-] state_specs : float Keyword arguments which can be any of `T`, `P`, `V`, `zs`; `zs` is optional, as are (`T`, `P`, `V`), but if any of (`T`, `P`, `V`) are specified, a second one is required as well, [various] Notes ----- Subclassing equations of state require their :obj:`kwargs_linear <GCEOSMIX.kwargs_linear>` and :obj:`kwargs_square <GCEOSMIX.kwargs_square>` attributes to be correct for this to work. `Tcs`, `Pcs`, and `omegas` are always assumed to be used. Examples -------- >>> kijs = [[0.0, 0.00076, 0.00171], [0.00076, 0.0, 0.00061], [0.00171, 0.00061, 0.0]] >>> PR3 = PRMIX(Tcs=[469.7, 507.4, 540.3], zs=[0.8168, 0.1501, 0.0331], omegas=[0.249, 0.305, 0.349], Pcs=[3.369E6, 3.012E6, 2.736E6], T=322.29, P=101325.0, kijs=kijs) >>> PR3.subset([1,2]) PRMIX(Tcs=[507.4, 540.3], Pcs=[3012000.0, 2736000.0], omegas=[0.305, 0.349], kijs=[[0.0, 0.00061], [0.00061, 0.0]], zs=[0.8193231441048036, 0.1806768558951965], T=322.29, P=101325.0) >>> PR3.subset([1,2], T=500.0, P=1e5, zs=[.2, .8]) PRMIX(Tcs=[507.4, 540.3], Pcs=[3012000.0, 2736000.0], omegas=[0.305, 0.349], kijs=[[0.0, 0.00061], [0.00061, 0.0]], zs=[0.2, 0.8], T=500.0, P=100000.0) >>> PR3.subset([1,2], zs=[.2, .8]) PRMIX(Tcs=[507.4, 540.3], Pcs=[3012000.0, 2736000.0], omegas=[0.305, 0.349], kijs=[[0.0, 0.00061], [0.00061, 0.0]], zs=[0.2, 0.8], T=322.29, P=101325.0) ''' is_slice = isinstance(idxs, slice) if is_slice: def atindexes(values): return values[idxs] else: def atindexes(values): return [values[i] for i in idxs] if state_specs: kwargs = state_specs if len(kwargs) == 1 and 'zs' in kwargs: kwargs.update(self.state_specs) else: kwargs = self.state_specs if 'zs' not in kwargs: zs = atindexes(self.zs) if not zs: raise ValueError("Cannot create an EOS without any components selected") zs_tot_inv = 1.0/sum(zs) for i in range(len(zs)): zs[i] *= zs_tot_inv kwargs['zs'] = zs kwargs['Tcs'] = atindexes(self.Tcs) kwargs['Pcs'] = atindexes(self.Pcs) kwargs['omegas'] = atindexes(self.omegas) local_kwargs = self.kwargs for k in self.kwargs_linear: kwargs[k] = atindexes(local_kwargs[k]) for k in self.kwargs_square: kwargs[k] = subset_matrix(local_kwargs[k], idxs) return self.__class__(**kwargs) def __repr__(self): s = '%s(Tcs=%s, Pcs=%s, omegas=%s, ' %(self.__class__.__name__, repr(self.Tcs), repr(self.Pcs), repr(self.omegas)) for k, v in self.kwargs.items(): s += '%s=%s, ' %(k, repr(v)) s += 'zs=%s, ' %(repr(self.zs)) if hasattr(self, 'no_T_spec') and self.no_T_spec: s += 'P=%s, V=%s' %(repr(self.P), repr(self.V)) elif self.V is not None: s += 'T=%s, V=%s' %(repr(self.T), repr(self.V)) else: s += 'T=%s, P=%s' %(repr(self.T), repr(self.P)) s += ')' return s @classmethod def from_json(cls, json_repr): r'''Method to create a mixture cubic equation of state from a JSON friendly serialization of another mixture cubic equation of state. Parameters ---------- json_repr : dict Json representation, [-] Returns ------- eos_mix : :obj:`GCEOSMIX` Newly created object from the json serialization, [-] Notes ----- It is important that the input string be in the same format as that created by :obj:`GCEOS.as_json`. Examples -------- >>> import pickle >>> eos = PRSV2MIX(Tcs=[507.6], Pcs=[3025000], omegas=[0.2975], zs=[1], T=299., P=1E6, kappa1s=[0.05104], kappa2s=[0.8634], kappa3s=[0.460]) >>> json_stuff = pickle.dumps(eos.as_json()) >>> new_eos = GCEOSMIX.from_json(pickle.loads(json_stuff)) >>> assert new_eos == eos ''' d = json_repr eos_name = d['py/object'] del d['py/object'] del d['json_version'] if not d['scalar']: d = serialize.naive_lists_to_arrays(d) try: d['raw_volumes'] = tuple(d['raw_volumes']) except: pass try: alpha_coeffs = [tuple(v) for v in d['alpha_coeffs']] d['alpha_coeffs'] = alpha_coeffs except: pass eos = eos_mix_full_path_dict[eos_name] if eos.kwargs_keys: d['kwargs'] = {k: d[k] for k in eos.kwargs_keys} try: d['kwargs']['alpha_coeffs'] = alpha_coeffs except: pass new = eos.__new__(eos) new.__dict__ = d return new def to_TP_zs_fast(self, T, P, zs, only_l=False, only_g=False, full_alphas=True): r'''Method to construct a new :obj:`GCEOSMIX` instance with the same parameters as the existing object. If both instances are at the same temperature, `a_alphas` and `da_alpha_dTs` and `d2a_alpha_dT2s` are shared between the instances. It is always assumed the new object has a differet composition. Optionally, only one set of phase properties can be solved for, increasing speed. Additionally, if `full_alphas` is set to False no temperature derivatives of `a_alpha` will be computed. Those derivatives are not needed in the context of a PT or PVF flash. Parameters ---------- T : float Temperature, [K] P : float Pressure, [Pa] zs : list[float] Mole fractions of each component, [-] only_l : bool When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set. only_g : bool When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set. Returns ------- eos : :obj:`GCEOSMIX` Multicomponent :obj:`GCEOSMIX` at the specified conditions [-] Notes ----- Examples -------- >>> base = RKMIX(T=500.0, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> base.to_TP_zs_fast(T=300, P=1e5, zs=base.zs) RKMIX(Tcs=[126.1, 190.6], Pcs=[3394000.0, 4604000.0], omegas=[0.04, 0.011], kijs=[[0.0, 0.0], [0.0, 0.0]], zs=[0.6, 0.4], T=300, P=100000.0) ''' copy_alphas = T == self.T new = self.__class__.__new__(self.__class__) new.N = self.N new.Tcs = self.Tcs new.Pcs = self.Pcs new.omegas = self.omegas new.kijs = self.kijs new.kwargs = self.kwargs new.ais = self.ais new.bs = self.bs new.scalar = self.scalar if copy_alphas: new.a_alphas = self.a_alphas try: new.da_alpha_dTs = self.da_alpha_dTs new.d2a_alpha_dT2s = self.d2a_alpha_dT2s except: pass new.zs = zs new.T = T new.P = P new.V = None new._fast_init_specific(self) new.solve(pure_a_alphas=(not copy_alphas), only_l=only_l, only_g=only_g, full_alphas=full_alphas) return new def to_TP_zs(self, T, P, zs, fugacities=True, only_l=False, only_g=False): r'''Method to construct a new :obj:`GCEOSMIX` instance at `T`, `P`, and `zs` with the same parameters as the existing object. Optionally, only one set of phase properties can be solved for, increasing speed. The fugacities calculation can be be skipped by by setting `fugacities` to False. Parameters ---------- T : float Temperature, [K] P : float Pressure, [Pa] zs : list[float] Mole fractions of each component, [-] fugacities : bool Whether or not to calculate and set the fugacities of each component, [-] only_l : bool When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set. only_g : bool When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set. Returns ------- eos : :obj:`GCEOSMIX` Multicomponent :obj:`GCEOSMIX` at the specified conditions [-] Notes ----- A check for whether or not `T`, `P`, and `zs` are the same as the existing instance is performed; if it is, the existing object is returned. Examples -------- >>> base = RKMIX(T=500.0, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> base.to_TP_zs(T=300, P=1e5, zs=[.1, 0.9]) RKMIX(Tcs=[126.1, 190.6], Pcs=[3394000.0, 4604000.0], omegas=[0.04, 0.011], kijs=[[0.0, 0.0], [0.0, 0.0]], zs=[0.1, 0.9], T=300, P=100000.0) ''' if T != self.T or P != self.P or zs != self.zs: return self.__class__(T=T, P=P, zs=zs, Tcs=self.Tcs, Pcs=self.Pcs, omegas=self.omegas, only_l=only_l, only_g=only_g, fugacities=fugacities, **self.kwargs) else: return self def to_PV_zs(self, P, V, zs, fugacities=True, only_l=False, only_g=False): r'''Method to construct a new :obj:`GCEOSMIX` instance at `P`, `V`, and `zs` with the same parameters as the existing object. Optionally, only one set of phase properties can be solved for, increasing speed. The fugacities calculation can be be skipped by by setting `fugacities` to False. Parameters ---------- P : float Pressure, [Pa] V : float Molar volume, [m^3/mol] zs : list[float] Mole fractions of each component, [-] fugacities : bool Whether or not to calculate and set the fugacities of each component, [-] only_l : bool When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set. only_g : bool When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set. Returns ------- eos : :obj:`GCEOSMIX` Multicomponent :obj:`GCEOSMIX` at the specified conditions [-] Notes ----- A check for whether or not `P`, `V`, and `zs` are the same as the existing instance is performed; if it is, the existing object is returned. Examples -------- >>> base = RKMIX(T=500.0, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> base.to_PV_zs(V=0.004162, P=1e5, zs=[.1, 0.9]) RKMIX(Tcs=[126.1, 190.6], Pcs=[3394000.0, 4604000.0], omegas=[0.04, 0.011], kijs=[[0.0, 0.0], [0.0, 0.0]], zs=[0.1, 0.9], P=100000.0, V=0.004162) ''' if P == self.P and V == self.V and zs == self.zs: return self return self.__class__(P=P, V=V, zs=zs, Tcs=self.Tcs, Pcs=self.Pcs, omegas=self.omegas, only_l=only_l, only_g=only_g, fugacities=fugacities, **self.kwargs) def to(self, zs=None, T=None, P=None, V=None, fugacities=True): r'''Method to construct a new :obj:`GCEOSMIX` object at two of `T`, `P` or `V` with the specified composition. In the event the specs match those of the current object, it will be returned unchanged. Parameters ---------- zs : list[float], optional Mole fractions of EOS, [-] T : float or None, optional Temperature, [K] P : float or None, optional Pressure, [Pa] V : float or None, optional Molar volume, [m^3/mol] fugacities : bool Whether or not to calculate fugacities, [-] Returns ------- obj : :obj:`GCEOSMIX` Pure component :obj:`GCEOSMIX` at the two specified specs, [-] Notes ----- Constructs the object with parameters `Tcs`, `Pcs`, `omegas`, and `kwargs`. Examples -------- >>> base = PRMIX(T=500.0, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> base.to(T=300.0, P=1e9).state_specs {'T': 300.0, 'P': 1000000000.0} >>> base.to(T=300.0, V=1.0).state_specs {'T': 300.0, 'V': 1.0} >>> base.to(P=1e5, V=1.0).state_specs {'P': 100000.0, 'V': 1.0} ''' if zs is None: zs = self.zs if T is not None and P is not None: try: sln = self.to_TP_zs_fast(T, P, zs) if fugacities: sln.fugacities() return sln except: return self.to_TP_zs(T, P, zs, fugacities) elif T is not None and V is not None: if T == self.T and V == self.V and zs == self.zs: return self return self.__class__(T=T, V=V, zs=zs, Tcs=self.Tcs, Pcs=self.Pcs, omegas=self.omegas, fugacities=fugacities, **self.kwargs) elif P is not None and V is not None: return self.to_PV_zs(P, V, zs, fugacities) else: return self.__class__(T=T, P=P, V=V, zs=zs, Tcs=self.Tcs, Pcs=self.Pcs, omegas=self.omegas, fugacities=fugacities, **self.kwargs) def to_TP(self, T, P): r'''Method to construct a new :obj:`GCEOSMIX` object at the spcified `T` and `P` with the current composition. In the event the `T` and `P` match the current object's `T` and `P`, it will be returned unchanged. Parameters ---------- T : float Temperature, [K] P : float Pressure, [Pa] Returns ------- obj : :obj:`GCEOSMIX` Pure component :obj:`GCEOSMIX` at specified `T` and `P`, [-] Notes ----- Constructs the object with parameters `Tcs`, `Pcs`, `omegas`, and `kwargs`. Examples -------- >>> base = RKMIX(T=500.0, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> new = base.to_TP(T=10.0, P=2000.0) >>> base.state_specs, new.state_specs ({'T': 500.0, 'P': 1000000.0}, {'T': 10.0, 'P': 2000.0}) ''' return self.to_TP_zs(T, P, zs=self.zs) def to_TV(self, T, V): r'''Method to construct a new :obj:`GCEOSMIX` object at the spcified `T` and `V` with the current composition. In the event the `T` and `V` match the current object's `T` and `V`, it will be returned unchanged. Parameters ---------- T : float Temperature, [K] V : float Molar volume, [m^3/mol] Returns ------- obj : :obj:`GCEOSMIX` Pure component :obj:`GCEOSMIX` at specified `T` and `V`, [-] Notes ----- Constructs the object with parameters `Tcs`, `Pcs`, `omegas`, and `kwargs`. Examples -------- >>> base = RKMIX(T=500.0, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> new = base.to_TV(T=1000000.0, V=1.0) >>> base.state_specs, new.state_specs ({'T': 500.0, 'P': 1000000.0}, {'T': 1000000.0, 'V': 1.0}) ''' if T == self.T and V == self.V: return self return self.__class__(T=T, V=V, zs=self.zs, Tcs=self.Tcs, Pcs=self.Pcs, omegas=self.omegas, fugacities=True, **self.kwargs) def to_PV(self, P, V): r'''Method to construct a new :obj:`GCEOSMIX` object at the spcified `P` and `V` with the current composition. In the event the `P` and `V` match the current object's `P` and `V`, it will be returned unchanged. Parameters ---------- P : float Pressure, [Pa] V : float Molar volume, [m^3/mol] Returns ------- obj : :obj:`GCEOSMIX` Pure component :obj:`GCEOSMIX` at specified `P` and `V`, [-] Notes ----- Constructs the object with parameters `Tcs`, `Pcs`, `omegas`, and `kwargs`. Examples -------- >>> base = RKMIX(T=500.0, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> new = base.to_PV(P=1000000.0, V=1.0) >>> base.state_specs, new.state_specs ({'T': 500.0, 'P': 1000000.0}, {'P': 1000000.0, 'V': 1.0}) ''' if V == self.V and P == self.P: return self return self.__class__(V=V, P=P, zs=self.zs, Tcs=self.Tcs, Pcs=self.Pcs, omegas=self.omegas, fugacities=True, **self.kwargs) def to_mechanical_critical_point(self): r'''Method to construct a new :obj:`GCEOSMIX` object at the current object's properties and composition, but which is at the mechanical critical point. Returns ------- obj : :obj:`GCEOSMIX` Pure component :obj:`GCEOSMIX` at mechanical critical point [-] Examples -------- >>> base = RKMIX(T=500.0, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> base.to_mechanical_critical_point() RKMIX(Tcs=[126.1, 190.6], Pcs=[3394000.0, 4604000.0], omegas=[0.04, 0.011], kijs=[[0.0, 0.0], [0.0, 0.0]], zs=[0.6, 0.4], T=151.861, P=3908737.9) ''' T, P = self.mechanical_critical_point() return self.to_TP_zs(T=T, P=P, zs=self.zs) def to_TPV_pure(self, i, T=None, P=None, V=None): r'''Helper method which returns a pure `EOSs` at the specs (two of `T`, `P` and `V`) and base EOS as the mixture for a particular index. Parameters ---------- i : int Index of specified compound, [-] T : float or None, optional Specified temperature, [K] P : float or None, optional Specified pressure, [Pa] V : float or None, optional Specified volume, [m^3/mol] Returns ------- eos_pure : eos A pure-species EOSs at the two specified `T`, `P`, and `V` for component `i`, [-] Notes ----- ''' kwargs = {} mix_kwargs_to_pure = self.mix_kwargs_to_pure for k, v in self.kwargs.items(): if k in mix_kwargs_to_pure: kwargs[mix_kwargs_to_pure[k]] = v[i] return self.eos_pure(T=T, P=P, V=V, Tc=self.Tcs[i], Pc=self.Pcs[i], omega=self.omegas[i], **kwargs) def pures(self): r'''Helper method which returns a list of pure `EOSs` at the same `T` and `P` and base EOS as the mixture. Returns ------- eos_pures : list[eos] A list of pure-species EOSs at the same `T` and `P` as the system, [-] Notes ----- This is useful for i.e. comparing mixture fugacities with the Lewis-Randall rule or when using an activity coefficient model which require pure component fugacities. ''' T, P, N = self.T, self.P, self.N return [self.to_TPV_pure(T=T, P=P, V=None, i=i) for i in range(N)] @property def pseudo_Tc(self): '''Apply a linear mole-fraction mixing rule to compute the average critical temperature, [K]. Examples -------- >>> base = RKMIX(T=150.0, P=4e6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> base.pseudo_Tc 151.9 ''' zs = self.zs Tcs = self.Tcs Tc = 0.0 for i in range(self.N): Tc += zs[i]*Tcs[i] return Tc @property def pseudo_Pc(self): '''Apply a linear mole-fraction mixing rule to compute the average critical pressure, [Pa]. Examples -------- >>> base = RKMIX(T=150.0, P=4e6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> base.pseudo_Pc 3878000.0 ''' zs = self.zs Pcs = self.Pcs Pc = 0.0 for i in range(self.N): Pc += zs[i]*Pcs[i] return Pc @property def pseudo_omega(self): '''Apply a linear mole-fraction mixing rule to compute the average `omega`, [-]. Examples -------- >>> base = RKMIX(T=150.0, P=4e6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> base.pseudo_omega 0.0284 ''' zs = self.zs omegas = self.omegas omega = 0.0 for i in range(self.N): omega += zs[i]*omegas[i] return omega @property def pseudo_a(self): '''Apply a linear mole-fraction mixing rule to compute the average `a` coefficient, [-]. Examples -------- >>> base = RKMIX(T=150.0, P=4e6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.6, 0.4]) >>> base.pseudo_a 0.17634464184 ''' zs = self.zs ais = self.ais a = 0.0 for i in range(self.N): a += zs[i]*ais[i] return a def Psat(self, T, polish=False): r'''Generic method to calculate vapor pressure of a pure-component equation of state for a specified `T`. An explicit solution is used unless `polish` is True. The result of this function has no physical meaning for multicomponent mixtures, and does not represent either a dew point or a bubble point! Parameters ---------- T : float Temperature, [K] polish : bool, optional Whether to attempt to use a numerical solver to make the solution more precise or not Returns ------- Psat : float Vapor pressure using the pure-component approach, [Pa] Notes ----- For multicomponent mixtures this may serve as a useful guess for the dew and the bubble pressure. ''' if self.N == 1: Tc, Pc, omega, a = self.Tcs[0], self.Pcs[0], self.omegas[0], self.ais[0] else: zs = self.zs Tcs, Pcs, omegas, ais = self.Tcs, self.Pcs, self.omegas, self.ais Tc, Pc, omega, a = 0.0, 0.0, 0.0, 0.0 for i in range(self.N): Tc += Tcs[i]*zs[i] Pc += Pcs[i]*zs[i] omega += omegas[i]*zs[i] a += ais[i]*zs[i] self.Tc, self.Pc, self.omega = Tc, Pc, omega self.a = a Psat = GCEOS.Psat(self, T, polish=False) del self.Tc, self.Pc, self.omega return Psat def a_alpha_and_derivatives(self, T, full=True, quick=True, pure_a_alphas=True): r'''Method to calculate `a_alpha` and its first and second derivatives for an EOS with the Van der Waals mixing rules. Uses the parent class's interface to compute pure component values. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. For use in :obj:`solve_T <GCEOSMIX.solve_T>` this returns only `a_alpha` if `full` is False. .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} Parameters ---------- T : float Temperature, [K] full : bool, optional If False, calculates and returns only `a_alpha` quick : bool, optional Only the quick variant is implemented; it is little faster anyhow pure_a_alphas : bool, optional Whether or not to recalculate the a_alpha terms of pure components (for the case of mixtures only) which stay the same as the composition changes (i.e in a PT flash), [-] Returns ------- a_alpha : float Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dT : float Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2 : float Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] Notes ----- The exact expressions can be obtained with the following SymPy expression below, commented out for brevity. >>> from sympy import * # doctest:+SKIP >>> kij, T = symbols('kij, T ') # doctest:+SKIP >>> a_alpha_i, a_alpha_j = symbols('a_alpha_i, a_alpha_j', cls=Function) # doctest:+SKIP >>> a_alpha_ij = (1-kij)*sqrt(a_alpha_i(T)*a_alpha_j(T)) # doctest:+SKIP >>> diff(a_alpha_ij, T) # doctest:+SKIP >>> diff(a_alpha_ij, T, T) # doctest:+SKIP ''' if pure_a_alphas: if full: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = self.a_alpha_and_derivatives_vectorized(T) self.a_alphas, self.da_alpha_dTs, self.d2a_alpha_dT2s = a_alphas, da_alpha_dTs, d2a_alpha_dT2s else: self.a_alphas = a_alphas = self.a_alphas_vectorized(T) da_alpha_dTs = d2a_alpha_dT2s = None else: try: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = self.a_alphas, self.da_alpha_dTs, self.d2a_alpha_dT2s except: if full: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = self.a_alpha_and_derivatives_vectorized(T) self.a_alphas, self.da_alpha_dTs, self.d2a_alpha_dT2s = a_alphas, da_alpha_dTs, d2a_alpha_dT2s else: self.a_alphas = a_alphas = self.a_alphas_vectorized(T) da_alpha_dTs = d2a_alpha_dT2s = None if not IS_PYPY and self.N > 2000: return self.a_alpha_and_derivatives_numpy(a_alphas, da_alpha_dTs, d2a_alpha_dT2s, T, full=full, quick=quick) return self.a_alpha_and_derivatives_py(a_alphas, da_alpha_dTs, d2a_alpha_dT2s, T, full=full, quick=quick) def a_alpha_and_derivatives_py(self, a_alphas, da_alpha_dTs, d2a_alpha_dT2s, T, full=True, quick=True): # For 44 components, takes 150 us in PyPy.; 95 in pythran. Much of that is type conversions. # 4 ms pypy for 44*4, 1.3 ms for pythran, 10 ms python with numpy # 2 components 1.89 pypy, pythran 1.75 us, regular python 12.7 us. # 10 components - regular python 148 us, 9.81 us PyPy, 8.37 pythran in PyPy (flags have no effect; 14.3 us in regular python) zs, kijs, N = self.zs, self.kijs, self.N same_T = T == self.T if quick: try: assert same_T a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv = self.a_alpha_ijs, self.a_alpha_roots, self.a_alpha_ij_roots_inv except (AttributeError, AssertionError): try: a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv = a_alpha_aijs_composition_independent(a_alphas, kijs) except ZeroDivisionError: a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv = a_alpha_aijs_composition_independent_support_zeros(a_alphas, kijs) self.a_alpha_ijs, self.a_alpha_roots, self.a_alpha_ij_roots_inv = a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv else: try: a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv = a_alpha_aijs_composition_independent(a_alphas, kijs) except: a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv = a_alpha_aijs_composition_independent_support_zeros(a_alphas, kijs) if same_T: self.a_alpha_ijs, self.a_alpha_roots, self.a_alpha_ij_roots_inv = a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv if full: try: a_alpha, da_alpha_dT, d2a_alpha_dT2, a_alpha_ijs, da_alpha_dT_ijs, d2a_alpha_dT2_ijs = a_alpha_and_derivatives_full(a_alphas, da_alpha_dTs, d2a_alpha_dT2s, T, zs, kijs, a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv) except: if self.N == 1: a_alpha, da_alpha_dT, d2a_alpha_dT2 = a_alphas[0], da_alpha_dTs[0], d2a_alpha_dT2s[0] d2a_alpha_dT2_ijs, da_alpha_dT_ijs, a_alpha_ijs = [[d2a_alpha_dT2s[0]]], [[da_alpha_dTs[0]]], [[a_alphas[0]]] self.d2a_alpha_dT2_ijs = d2a_alpha_dT2_ijs self.da_alpha_dT_ijs = da_alpha_dT_ijs self.a_alpha_ijs = a_alpha_ijs return a_alpha, da_alpha_dT, d2a_alpha_dT2 else: # Priority - test, fix, and validate a_alpha, _, a_alpha_ijs = a_alpha_and_derivatives(a_alphas, T, zs, kijs, a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv) self.da_alpha_dT_ijs = [] self.a_alpha_ijs = a_alpha_ijs return a_alpha # # DO NOT REMOVE THIS CODE! IT MAKES TIHNGS SLOWER IN PYPY, even though it never runs # cmps = self.cmps # da_alpha_dT, d2a_alpha_dT2 = 0.0, 0.0 # # a_alpha_ijs = [[None]*N for _ in cmps] # a_alpha_roots = [a_alpha_i**0.5 for a_alpha_i in a_alphas] # # if full: # a_alpha_ij_roots = [[None]*N for _ in cmps] # for i in cmps: # kijs_i = kijs[i] # a_alpha_i = a_alphas[i] # a_alpha_ijs_is = a_alpha_ijs[i] # a_alpha_ij_roots_i = a_alpha_ij_roots[i] # for j in cmps: # if j < i: # continue # a_alpha_ij_roots_i[j] = a_alpha_roots[i]*a_alpha_roots[j]#(a_alpha_i*a_alphas[j])**0.5 # a_alpha_ijs_is[j] = a_alpha_ijs[j][i] = (1. - kijs_i[j])*a_alpha_ij_roots_i[j] # else: # for i in cmps: # kijs_i = kijs[i] # a_alpha_i = a_alphas[i] # a_alpha_ijs_is = a_alpha_ijs[i] # for j in cmps: # if j < i: # continue # a_alpha_ijs_is[j] = a_alpha_ijs[j][i] = (1. - kijs_i[j])*a_alpha_roots[i]*a_alpha_roots[j] # # # Faster than an optimized loop in pypy even # z_products = [[zs[i]*zs[j] for j in cmps] for i in cmps] # # a_alpha = 0.0 # for i in cmps: # a_alpha_ijs_i = a_alpha_ijs[i] # z_products_i = z_products[i] # for j in cmps: # if j < i: # continue # elif i != j: # a_alpha += 2.0*a_alpha_ijs_i[j]*z_products_i[j] # else: # a_alpha += a_alpha_ijs_i[j]*z_products_i[j] # # # List comprehension tested to be faster in CPython not pypy ## a_alpha = sum([a_alpha_ijs[i][j]*z_products[i][j] ## for j in self.cmps for i in self.cmps]) # self.a_alpha_ijs = a_alpha_ijs # # da_alpha_dT_ijs = self.da_alpha_dT_ijs = [[None]*N for _ in cmps] # # if full: # for i in cmps: # kijs_i = kijs[i] # a_alphai = a_alphas[i] # z_products_i = z_products[i] # da_alpha_dT_i = da_alpha_dTs[i] # d2a_alpha_dT2_i = d2a_alpha_dT2s[i] # a_alpha_ij_roots_i = a_alpha_ij_roots[i] # for j in cmps: # if j < i: # # skip the duplicates # continue # a_alphaj = a_alphas[j] # x0 = a_alphai*a_alphaj # x0_05 = a_alpha_ij_roots_i[j] # zi_zj = z_products_i[j] # # x1 = a_alphai*da_alpha_dTs[j] # x2 = a_alphaj*da_alpha_dT_i # x1_x2 = x1 + x2 # x3 = 2.0*x1_x2 # # kij_m1 = kijs_i[j] - 1.0 # # da_alpha_dT_ij = -0.5*kij_m1*x1_x2/x0_05 # # # For temperature derivatives of fugacities # da_alpha_dT_ijs[i][j] = da_alpha_dT_ijs[j][i] = da_alpha_dT_ij # # da_alpha_dT_ij *= zi_zj # # d2a_alpha_dT2_ij = zi_zj*kij_m1*(-0.25*x0_05*(x0*( # 2.0*(a_alphai*d2a_alpha_dT2s[j] + a_alphaj*d2a_alpha_dT2_i) # + 4.*da_alpha_dT_i*da_alpha_dTs[j]) - x1*x3 - x2*x3 + x1_x2*x1_x2)/(x0*x0)) # # if i != j: # da_alpha_dT += da_alpha_dT_ij + da_alpha_dT_ij # d2a_alpha_dT2 += d2a_alpha_dT2_ij + d2a_alpha_dT2_ij # else: # da_alpha_dT += da_alpha_dT_ij # d2a_alpha_dT2 += d2a_alpha_dT2_ij # # return a_alpha, da_alpha_dT, d2a_alpha_dT2 # else: # return a_alpha def a_alpha_and_derivatives_py(self, a_alphas, da_alpha_dTs, d2a_alpha_dT2s, T, full=True, quick=True): zs, kijs, scalar, N = self.zs, self.kijs, self.scalar, self.N if scalar: self.a_alpha_roots = a_alpha_roots = [sqrt(i) for i in a_alphas] else: self.a_alpha_roots = a_alpha_roots = npsqrt(a_alphas) if full: # Converting kijs into a matrix kills the performance! 5x slower than the performance of the functions. # converting the 1d arrays also takes as long as the function. # a_alpha, da_alpha_dT, d2a_alpha_dT2, self.a_alpha_j_rows, self.da_alpha_dT_j_rows = ( # a_alpha_and_derivatives_quadratic_terms(np.array(a_alphas), np.array(a_alpha_roots), np.array(da_alpha_dTs), # np.array(d2a_alpha_dT2s), T, np.array(zs), np.array(kijs))) if scalar: a_alpha_j_rows, da_alpha_dT_j_rows = [0.0]*N, [0.0]*N else: a_alpha_j_rows, da_alpha_dT_j_rows = zeros(N), zeros(N) a_alpha, da_alpha_dT, d2a_alpha_dT2, self.a_alpha_j_rows, self.da_alpha_dT_j_rows = ( a_alpha_and_derivatives_quadratic_terms(a_alphas, a_alpha_roots, da_alpha_dTs, d2a_alpha_dT2s, T, zs, kijs, a_alpha_j_rows=a_alpha_j_rows, da_alpha_dT_j_rows=da_alpha_dT_j_rows)) return a_alpha, da_alpha_dT, d2a_alpha_dT2 else: # a_alpha, self.a_alpha_j_rows = a_alpha_quadratic_terms(np.array(a_alphas), np.array(a_alpha_roots), T, np.array(zs), np.array(kijs)) a_alpha_j_rows = [0.0]*N if scalar else zeros(N) a_alpha, self.a_alpha_j_rows = a_alpha_quadratic_terms(a_alphas, a_alpha_roots, T, zs, kijs, a_alpha_j_rows=a_alpha_j_rows) return a_alpha def a_alpha_and_derivatives_numpy(self, a_alphas, da_alpha_dTs, d2a_alpha_dT2s, T, full=True, quick=True): zs, kijs = self.zs, np.array(self.kijs) a_alphas = np.array(a_alphas) da_alpha_dTs = np.array(da_alpha_dTs) one_minus_kijs = 1.0 - kijs x0 = np.einsum('i,j', a_alphas, a_alphas) x0_05 = npsqrt(x0) a_alpha_ijs = (one_minus_kijs)*x0_05 z_products = np.einsum('i,j', zs, zs) a_alpha = np.einsum('ij,ji', a_alpha_ijs, z_products) if self.scalar: self.a_alpha_ijs = a_alpha_ijs.tolist() else: self.a_alpha_ijs = a_alpha_ijs if full: term0 = np.einsum('j,i', a_alphas, da_alpha_dTs) term7 = (one_minus_kijs)/(x0_05) da_alpha_dT = (z_products*term7*(term0)).sum() term1 = -x0_05/x0*(one_minus_kijs) term2 = np.einsum('i, j', a_alphas, da_alpha_dTs) main3 = da_alpha_dTs/(2.0*a_alphas)*term2 main4 = -np.einsum('i, j', a_alphas, d2a_alpha_dT2s) main6 = -0.5*np.einsum('i, j', da_alpha_dTs, da_alpha_dTs) # Needed for fugacity temperature derivative self.da_alpha_dT_ijs = (0.5*(term7)*(term2 + term0)).tolist() d2a_alpha_dT2 = (z_products*(term1*(main3 + main4 + main6))).sum() return float(a_alpha), float(da_alpha_dT), float(d2a_alpha_dT2) else: return float(a_alpha) def _spinodal_f(self, TPV): # TODO - use `self`, do not create new instance # Work to do - ethane', 'heptane # Specify V, solve P; increase V and keep going # After Effective utilization of equations of state for thermodynamic properties in process simulation '''eos = PRMIX(P=6e6, T=500, Tcs=[305.32, 540.2], Pcs=[4872000.0, 2740000.0], omegas=[0.098, 0.3457], zs=[.5, .5]) def to_solve(T): return eos.to(T=T, P=eos.P, zs=eos.zs)._spinodal_f([T, eos.P]) # Very well could be right eos.to(T=secant(to_solve, eos.T), P=eos.P, zs=eos.zs).rho_l # 3004.715984610371 ''' T, P, V = TPV eos_instance = self.to(T=T, P=P, V=V, zs=self.zs) RT_inv = 1.0/(R*eos_instance.T) if eos_instance.phase == 'l/g': if eos_instance.G_dep_l < eos_instance.G_dep_g: v = eos_instance.d2nA_dninjs_Vt('l') else: v = eos_instance.d2nA_dninjs_Vt('g') elif eos_instance.phase == 'g': v = eos_instance.d2nA_dninjs_Vt('g') else: v = eos_instance.d2nA_dninjs_Vt('l') dGs = [[i*RT_inv for i in row] for row in v] return det(dGs) def _spinodal_at(self, T=None, P=None, V=None): # TODO finish if T is not None: def to_solve(V): return self._spinodal_f((T, None, V)) if 1: from fluids.numerics import linspace Vs = linspace(self.b*(1+1e-7), self.b*1000, 1000) errs = [] for Vi in Vs: try: errs.append(abs(to_solve(Vi))) except: errs.append(1e5) import matplotlib.pyplot as plt plt.semilogy(Vs, errs) plt.show() a = 1 elif P is not None: def to_solve(V): return self._spinodal_f((None, P, V)) elif V is not None: def to_solve(T): return self._spinodal_f((T, None, V)) def _mechanical_critical_point_f_jac(self, TP): '''The criteria for c_goal and d_goal come from a cubic 'roots_cubic', which uses a `f`, `g`, and `h` parameter. When all of them are zero, all three roots are equal. For the eos (a=1), this results in the following system of equations: from sympy import * a = 1 b, c, d = symbols('b, c, d') f = ((3* c / a) - ((b ** 2) / (a ** 2))) / 3 g = (((2 * (b ** 3)) / (a ** 3)) - ((9* b * c) / (a **2)) + (27 * d / a)) /27 h = ((g ** 2) / 4 + (f ** 3) / 27)z solve([Eq(f, 0), Eq(g, 0), Eq(h, 0)], [b, c, d]) The solution (sympy struggled) is: c = b^2/3 d = b^3/27 These two variables switch sign at the criteria, so they work well with a root finding approach. Derived with: from sympy import * P, T, V, R, b_eos, alpha = symbols('P, T, V, R, b_eos, alpha') Tc, Pc, omega = symbols('Tc, Pc, omega') delta, epsilon = symbols('delta, epsilon') a_alpha = alpha(T) eta = b_eos B = b_eos*P/(R*T) deltas = delta*P/(R*T) thetas = a_alpha*P/(R*T)**2 epsilons = epsilon*(P/(R*T))**2 etas = eta*P/(R*T) b = (deltas - B - 1) c = (thetas + epsilons - deltas*(B + 1)) d = -(epsilons*(B + 1) + thetas*etas) c_goal = b*b/3 d_goal = b*b*b/27 F1 = c - c_goal F2 = d - d_goal cse([F1, F2, diff(F1, T), diff(F1, P), diff(F2, T), diff(F2, P)], optimizations='basic') Performance analysis: 77% of this is getting a_alpha and da_alpha_dT. 71% of the outer solver is getting f and this Jacobian. Limited results from optimizing the below code, which was derived with sympy. ''' T, P = float(TP[0]), float(TP[1]) b_eos, delta, epsilon = self.b, self.delta, self.epsilon eta = b_eos try: del self.a_alpha_ijs del self.a_alpha_roots del self.a_alpha_ij_roots_inv except: pass a_alpha, da_alpha_dT, _ = self.a_alpha_and_derivatives(T, full=True) x6 = R_inv x7 = 1.0/T x0 = a_alpha x1 = R_inv*R_inv x2 = x7*x7 x3 = x1*x2 x4 = P*P x5 = epsilon*x3*x4 x8 = P*x6*x7 x9 = delta*x8 x10 = b_eos*x8 x11 = x10 + 1.0 x12 = x11 - x9 x13 = x12*x12 x14 = P*x2*x6 x15 = da_alpha_dT x16 = x6*x7 x17 = x0*x16 x18 = 2.0*epsilon*x8 x19 = delta*x10 x20 = delta*x11 x21 = b_eos - delta x22 = 2.0/3.0*x12*x21 x23 = P*b_eos*x0*x1*x2 x24 = b_eos*x5 x25 = x11*x18 x26 = x13*x21/9.0 F1 = P*x0*x3 - x11*x9 - x13/3.0 + x5 F2 = -x11*x5 + x13*x12/27.0 - b_eos*x0*x4*x6*x1*x7*x2 dF1_dT = x14*(x15*x6 - 2.0*x17 - x18 + x19 + x20 + x22) dF1_dP = x16*(x17 + x18 - x19 - x20 - x22) dF2_dT = x14*(-P*b_eos*x1*x15*x7 + 3.0*x23 + x24 + x25 - x26) dF2_dP = x16*(-2.0*x23 - x24 - x25 + x26) return [F1, F2], [[dF1_dT, dF1_dP], [dF2_dT, dF2_dP]] def mechanical_critical_point(self): r'''Method to calculate the mechanical critical point of a mixture of defined composition. The mechanical critical point is where: .. math:: \frac{\partial P}{\partial \rho}|_T = \frac{\partial^2 P}{\partial \rho^2}|_T = 0 Returns ------- T : float Mechanical critical temperature, [K] P : float Mechanical critical temperature, [Pa] Notes ----- One useful application of the mechanical critical temperature is that the phase identification approach of Venkatarathnam is valid only up to it. Note that the equation of state, when solved at these conditions, will have fairly large (1e-3 - 1e-6) results for the derivatives; but they are the minimum. This is just from floating point precision. It can also be checked looking at the calculated molar volumes - all three (available with :obj:`sorted_volumes <GCEOSMIX.sorted_volumes>`) will be very close (1e-5 difference in practice), again differing because of floating point error. The algorithm here is a custom implementation, using Newton-Raphson's method with the initial guesses described in [1] (mole-weighted critical pressure average, critical temperature average using a quadratic mixing rule). Normally ~4 iterations are needed to solve the system. It is relatively fast, as only one evaluation of `a_alpha` and `da_alpha_dT` are needed per call to function and its jacobian. References ---------- .. [1] Watson, Harry A. J., and Paul I. Barton. "Reliable Flash Calculations: Part 3. A Nonsmooth Approach to Density Extrapolation and Pseudoproperty Evaluation." Industrial & Engineering Chemistry Research, November 11, 2017. https://doi.org/10.1021/acs.iecr.7b03233. .. [2] Mathias P. M., Boston J. F., and Watanasiri S. "Effective Utilization of Equations of State for Thermodynamic Properties in Process Simulation." AIChE Journal 30, no. 2 (June 17, 2004): 182-86. https://doi.org/10.1002/aic.690300203. ''' zs, Tcs, Pcs, N = self.zs, self.Tcs, self.Pcs, self.N Pmc = sum([Pcs[i]*zs[i] for i in range(N)]) Tmc = sum([sqrt(Tcs[i]*Tcs[j])*zs[j]*zs[i] for i in range(N) for j in range(N)]) TP, iterations = newton_system(self._mechanical_critical_point_f_jac, x0=[Tmc, Pmc], jac=True, ytol=1e-10, xtol=1e-12, solve_func=solve_2_direct) T, P = float(TP[0]), float(TP[1]) return T, P def fugacities(self, only_l=False, only_g=False): r'''Helper method for calculating fugacity coefficients for any phases present, using either the overall mole fractions for both phases or using specified mole fractions for each phase. Requires :obj:`fugacity_coefficients <GCEOSMIX.fugacity_coefficients>` to be implemented by each subclassing EOS. In addition to setting `fugacities_l` and/or `fugacities_g`, this also sets the fugacity coefficients `phis_l` and/or `phis_g`. .. math:: \hat \phi_i^g = \frac{\hat f_i^g}{y_i P} .. math:: \hat \phi_i^l = \frac{\hat f_i^l}{x_i P} Note that in a flash calculation, each phase requires their own EOS object. Parameters ---------- only_l : bool When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set. only_g : bool When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set. Notes ----- It is helpful to check that :obj:`fugacity_coefficients <GCEOSMIX.fugacity_coefficients>` has been implemented correctly using the following expression, from [1]_. .. math:: \ln \hat \phi_i = \left[\frac{\partial (n\ln \phi)}{\partial n_i}\right]_{T,P,n_j,V_t} For reference, several expressions for fugacity of a component are as follows, shown in [1]_ and [2]_. .. math:: \ln \hat \phi_i = \int_{0}^P\left(\frac{\hat V_i} {RT} - \frac{1}{P}\right)dP .. math:: \ln \hat \phi_i = \int_V^\infty \left[ \frac{1}{RT}\frac{\partial P}{ \partial n_i} - \frac{1}{V}\right] d V - \ln Z References ---------- .. [1] Hu, Jiawen, Rong Wang, and Shide Mao. "Some Useful Expressions for Deriving Component Fugacity Coefficients from Mixture Fugacity Coefficient." Fluid Phase Equilibria 268, no. 1-2 (June 25, 2008): 7-13. doi:10.1016/j.fluid.2008.03.007. .. [2] Walas, Stanley M. Phase Equilibria in Chemical Engineering. Butterworth-Heinemann, 1985. ''' P, zs, scalar = self.P, self.zs, self.scalar if not only_g and hasattr(self, 'V_l'): self.lnphis_l = lnphis_l = self.fugacity_coefficients(self.Z_l) if scalar: try: self.phis_l = [exp(i) for i in lnphis_l] except: self.phis_l = [trunc_exp(i, trunc=1e308) for i in lnphis_l] self.fugacities_l = [phi*x*P for phi, x in zip(self.phis_l, zs)] else: self.phis_l = phis_l = npexp(lnphis_l) self.fugacities_l = zs*P*phis_l if not only_l and hasattr(self, 'V_g'): self.lnphis_g = lnphis_g = self.fugacity_coefficients(self.Z_g) if scalar: try: self.phis_g = phis_g = [exp(i) for i in lnphis_g] except: self.phis_g = phis_g = [trunc_exp(i, trunc=1e308) for i in lnphis_g] self.fugacities_g = [phi*y*P for phi, y in zip(phis_g, zs)] else: self.phis_g = phis_g = npexp(lnphis_g) self.fugacities_g = zs*P*phis_g def _eos_lnphis_lowest_Gibbs(self): try: try: if self.G_dep_l < self.G_dep_g: return self.lnphis_l, 'l' else: return self.lnphis_g, 'g' except: # Only one root - take it and set the prefered other phase to be a different type return (self.lnphis_g, 'g') if hasattr(self, 'Z_g') else (self.lnphis_l, 'l') except: self.fugacities() return self._eos_fugacities_lowest_Gibbs() def _eos_fugacities_lowest_Gibbs(self): # TODO delete with property_package.py try: try: if self.G_dep_l < self.G_dep_g: return self.fugacities_l, 'l' else: return self.fugacities_g, 'g' except: # Only one root - take it and set the prefered other phase to be a different type return (self.fugacities_g, 'g') if hasattr(self, 'Z_g') else (self.fugacities_l, 'l') except: self.fugacities() return self._eos_fugacities_lowest_Gibbs() def _dphi_dn(self, zi, i, phase): # obsolete, should be deleted z_copy = list(self.zs) z_copy.pop(i) z_sum = sum(z_copy) + zi z_copy = [j/z_sum if j else 0 for j in z_copy] z_copy.insert(i, zi) eos = self.to_TP_zs(self.T, self.P, z_copy) if phase == 'g': return eos.phis_g[i] elif phase == 'l': return eos.phis_l[i] def _dfugacity_dn(self, zi, i, phase): # obsolete, should be deleted z_copy = list(self.zs) z_copy.pop(i) z_sum = sum(z_copy) + zi z_copy = [j/z_sum if j else 0 for j in z_copy] z_copy.insert(i, zi) eos = self.to_TP_zs(self.T, self.P, z_copy) if phase == 'g': return eos.fugacities_g[i] elif phase == 'l': return eos.fugacities_l[i] def _Stateva_Tsvetkov_TPDF_broken(self, Zz, Zy, zs, ys): # TODO: delete z_log_fugacity_coefficients = self.fugacity_coefficients(Zz) y_log_fugacity_coefficients = self.fugacity_coefficients(Zy) kis = [] for yi, phi_yi, zi, phi_zi in zip(ys, y_log_fugacity_coefficients, zs, z_log_fugacity_coefficients): di = log(zi) + phi_zi try: ki = phi_yi + log(yi) - di except ValueError: ki = phi_yi + log(1e-200) - di kis.append(ki) kis.append(kis[0]) tot = 0.0 for i in range(self.N): t = kis[i+1] - kis[i] tot += t*t return tot def _d_TPD_Michelson_modified(self, Zz, Zy, zs, alphas): r'''Modified objective function for locating the minima of the Tangent Plane Distance function according to [1]_, also shown in [2]_ [2]_. The stationary points of a system are all zeros of this function; so once all zeroes have been located, the stability can be evaluated at the stationary points only. It may be required to use multiple guesses to find all stationary points, and there is no method of confirming all points have been found. This method does not alter the state of the object. .. math:: \frac{\partial \; TPD^*}{\partial \alpha_i} = \sqrt{Y_i} \left[ \ln \phi_i(Y) + \ln(Y_i) - h_i\right] .. math:: \alpha_i = 2 \sqrt{Y_i} .. math:: d_i(z) = \ln z_i + \ln \phi_i(z) Parameters ---------- Zz : float Compressibility factor of the phase undergoing stability testing, (`test` phase), [-] Zy : float Compressibility factor of the trial phase, [-] zs : list[float] Mole fraction composition of the phase undergoing stability testing (`test` phase), [-] alphas : list[float] Twice the square root of the mole numbers of each component, [mol^0.5] Returns ------- err : float Error in solving for stationary points according to the modified TPD method in [1]_, [-] Notes ----- This method is particularly useful because it is not a constrained objective function. This has been verified to return the same roots as other stationary point methods. References ---------- .. [1] Michelsen, Michael L. "The Isothermal Flash Problem. Part I. Stability." Fluid Phase Equilibria 9, no. 1 (December 1982): 1-19. .. [2] Qiu, Lu, Yue Wang, Qi Jiao, Hu Wang, and Rolf D. Reitz. "Development of a Thermodynamically Consistent, Robust and Efficient Phase Equilibrium Solver and Its Validations." Fuel 115 (January 1, 2014): 1-16 ''' # TODO: delete Ys = [(alpha/2.)**2 for alpha in alphas] ys = normalize(Ys) z_log_fugacity_coefficients = self.fugacity_coefficients(Zz) y_log_fugacity_coefficients = self.fugacity_coefficients(Zy) tot = 0 for Yi, phi_yi, zi, phi_zi in zip(Ys, y_log_fugacity_coefficients, zs, z_log_fugacity_coefficients): di = log(zi) + phi_zi if Yi != 0: diff = Yi**0.5*(log(Yi) + phi_yi - di) tot += abs(diff) return tot # def TDP_Michelsen(self, phase): # # z_log_fugacity_coefficients = self.fugacity_coefficients(Zz, zs) # y_log_fugacity_coefficients = self.fugacity_coefficients(Zy, ys) # tot = 0 # for yi, phi_yi, zi, phi_zi in zip(ys, y_log_fugacity_coefficients, zs, z_log_fugacity_coefficients): # hi = di = log(zi) + phi_zi # same as di # # k = log(yi) + phi_yi - hi # # Michaelsum doesn't do the exponents. # Yi = exp(-k)*yi # tot += Yi*(log(Yi) + phi_yi - hi - 1.) # # return 1. + tot # def TDP_Michelsen_modified(self, Zz, Zy, zs, Ys): # # https://www.e-education.psu.edu/png520/m17_p7.html # # Might as well continue # Ys = [abs(float(Yi)) for Yi in Ys] # # Ys only need to be positive # ys = normalize(Ys) # # z_log_fugacity_coefficients = self.fugacity_coefficients(Zz, zs) # y_log_fugacity_coefficients = self.fugacity_coefficients(Zy, ys) # # tot = 0 # for Yi, phi_yi, yi, zi, phi_zi in zip(Ys, y_log_fugacity_coefficients, ys, zs, z_log_fugacity_coefficients): # hi = di = log(zi) + phi_zi # same as di # tot += Yi*(log(Yi) + phi_yi - di - 1.) # return (1. + tot) # # Another formulation, returns the same answers. ## tot += yi*(log(sum(Ys)) +log(yi)+ log(phi_yi) - di - 1.) ## return (1. + sum(Ys)*tot)*1e15 def solve_T(self, P, V, quick=True, solution=None): r'''Generic method to calculate `T` from a specified `P` and `V`. Provides SciPy's `newton` solver, and iterates to solve the general equation for `P`, recalculating `a_alpha` as a function of temperature using :obj:`a_alpha_and_derivatives <GCEOSMIX.a_alpha_and_derivatives>` each iteration. Parameters ---------- P : float Pressure, [Pa] V : float Molar volume, [m^3/mol] quick : bool, optional Unimplemented, although it may be possible to derive explicit expressions as done for many pure-component EOS solution : str or None, optional 'l' or 'g' to specify a liquid of vapor solution (if one exists); if None, will select a solution more likely to be real (closer to STP, attempting to avoid temperatures like 60000 K or 0.0001 K). Returns ------- T : float Temperature, [K] ''' # -4 goes back from object, GCEOS return super(type(self).__mro__[-3], self).solve_T(P=P, V=V, solution=solution) def _err_VL_jacobian(self, lnKsVF, T, P, zs, near_critical=False, err_also=False, info=None): if info is None: info = [] N = self.N lnKs = lnKsVF[:-1] Ks = [exp(lnKi) for lnKi in lnKs] VF = float(lnKsVF[-1]) xs = [zi/(1.0 + VF*(Ki - 1.0)) for zi, Ki in zip(zs, Ks)] ys = [Ki*xi for Ki, xi in zip(Ks, xs)] eos_g = self.to_TP_zs_fast(T=T, P=P, zs=ys, only_g=True) # eos_l = self.to_TP_zs_fast(T=T, P=P, zs=xs, only_l=True) # # eos_g = self.to_TP_zs(T=T, P=P, zs=ys) # eos_l = self.to_TP_zs(T=T, P=P, zs=xs) if not near_critical: # lnphis_g = eos_g.lnphis_g # lnphis_l = eos_l.lnphis_l Z_g = eos_g.Z_g Z_l = eos_l.Z_l else: try: # lnphis_g = eos_g.lnphis_g Z_g = eos_g.Z_g except AttributeError: # lnphis_g = eos_g.lnphis_l Z_g = eos_g.Z_l try: # lnphis_l = eos_l.lnphis_l Z_l = eos_l.Z_l except AttributeError: # lnphis_l = eos_l.lnphis_g Z_l = eos_l.Z_g lnphis_g = eos_g.fugacity_coefficients(Z_g) lnphis_l = eos_l.fugacity_coefficients(Z_l) size = N + 1 J = [[None]*size for i in range(size)] # d_lnphi_dzs_basic_num # d_lnphi_dxs = eos_l.d_lnphi_dzs_basic_num(Z_l, xs) # d_lnphi_dys = eos_g.d_lnphi_dzs_basic_num(Z_g, ys) d_lnphi_dxs = eos_l.dlnphis_dzs(Z_l) d_lnphi_dys = eos_g.dlnphis_dzs(Z_g) # # Handle the zeros and the ones # Half of this is probably wrong! Only gets set for one set of variables? # Numerical jacobian not good enough to tell # for i in range(self.N): # J[i][-2] = 0.0 # J[-2][i] = 0.0 J[N][N] = 1.0 # Last column except last value; believed correct # Was not correct when compared to numerical solution Ksm1 = [Ki - 1.0 for Ki in Ks] RR_denoms_inv2 = [] for i in range(N): t = 1.0 + VF*Ksm1[i] RR_denoms_inv2.append(1.0/(t*t)) RR_terms = [zs[k]*Ksm1[k]*RR_denoms_inv2[k] for k in range(N)] for i in range(N): value = 0.0 d_lnphi_dxs_i, d_lnphi_dys_i = d_lnphi_dxs[i], d_lnphi_dys[i] for k in range(N): # pretty sure indexing is right in the below expression value += RR_terms[k]*(d_lnphi_dxs_i[k] - Ks[k]*d_lnphi_dys_i[k]) J[i][-1] = value # print(value) # def delta(k, j): # if k == j: # return 1.0 # return 0.0 # Main body - expensive to compute! Lots of elements # Can flip around the indexing of i, j on the d_lnphi_ds but still no fix # unsure of correct order! # Reveals bugs in d_lnphi_dxs though. zsKsRRinvs2 = [zs[j]*Ks[j]*RR_denoms_inv2[j] for j in range(N)] one_m_VF = 1.0 - VF for i in range(N): # to N is CORRECT/MATCHES JACOBIAN NUMERICALLY Ji = J[i] d_lnphi_dxs_is, d_lnphi_dys_is = d_lnphi_dxs[i], d_lnphi_dys[i] for j in range(N): # to N is CORRECT/MATCHES JACOBIAN NUMERICALLY value = 1.0 if i == j else 0.0 # value = 0.0 # value += delta(i, j) # print(i, j, value) # Maybe if i == j, can skip the bit below? Tried it once and the solver never converged # term = zs[j]*Ks[j]*RR_denoms_inv2[j] value += zsKsRRinvs2[j]*(VF*d_lnphi_dxs_is[j] + one_m_VF*d_lnphi_dys_is[j]) Ji[j] = value # Last row except last value - good, working # Diff of RR w.r.t each log K bottom_row = J[-1] for j in range(N): # value = 0.0 # RR_l = # RR_l = -Ks[j]*zs[j]*VF/(1.0 + VF*(Ks[j] - 1.0))**2.0 # RR_g = Ks[j]*(1.0 - VF)*zs[j]/(1.0 + VF*(Ks[j] - 1.0))**2.0 # value += # -RR_l bottom_row[j] = zsKsRRinvs2[j]*(one_m_VF) + VF*zsKsRRinvs2[j] # Last row except last value - good, working # bottom_row = J[-1] # for j in range(self.N): # value = 0.0 # for k in range(self.N): # if k == j: # RR_l = -Ks[j]*zs[k]*VF/(1.0 + VF*(Ks[k] - 1.0))**2.0 # RR_g = Ks[j]*(1.0 - VF)*zs[k]/(1.0 + VF*(Ks[k] - 1.0))**2.0 # value += RR_g - RR_l # bottom_row[j] = value # # Last value - good, working, being overwritten dF_ncp1_dB = 0.0 for i in range(N): dF_ncp1_dB -= RR_terms[i]*Ksm1[i] J[-1][-1] = dF_ncp1_dB info[:] = VF, xs, ys, eos_l, eos_g if err_also: err_RR = Rachford_Rice_flash_error(VF, zs, Ks) Fs = [lnKi - lnphi_l + lnphi_g for lnphi_l, lnphi_g, lnKi in zip(lnphis_l, lnphis_g, lnKs)] Fs.append(err_RR) return Fs, J return J def _err_VL(self, lnKsVF, T, P, zs, near_critical=False, info=None): # import numpy as np # tried autograd without luck lnKs = lnKsVF[:-1] # if isinstance(lnKs, np.ndarray): # lnKs = lnKs.tolist() # Ks = np.exp(lnKs) Ks = [exp(lnKi) for lnKi in lnKs] VF = float(lnKsVF[-1]) # VF = lnKsVF[-1] if info is None: info = [] xs = [zi/(1.0 + VF*(Ki - 1.0)) for zi, Ki in zip(zs, Ks)] ys = [Ki*xi for Ki, xi in zip(Ks, xs)] err_RR = Rachford_Rice_flash_error(VF, zs, Ks) eos_g = self.to_TP_zs_fast(T=T, P=P, zs=ys, only_g=True) # eos_g.fugacities() eos_l = self.to_TP_zs_fast(T=T, P=P, zs=xs, only_l=True) # eos_l.fugacities() if not near_critical: lnphis_g = eos_g.lnphis_g lnphis_l = eos_l.lnphis_l else: try: lnphis_g = eos_g.lnphis_g except AttributeError: lnphis_g = eos_g.lnphis_l try: lnphis_l = eos_l.lnphis_l except AttributeError: lnphis_l = eos_l.lnphis_g # Fs = [fl/fg-1.0 for fl, fg in zip(fugacities_l, fugacities_g)] Fs = [lnKi - lnphi_l + lnphi_g for lnphi_l, lnphi_g, lnKi in zip(lnphis_l, lnphis_g, lnKs)] Fs.append(err_RR) info[:] = VF, xs, ys, eos_l, eos_g return Fs def sequential_substitution_3P(self, Ks_y, Ks_z, beta_y, beta_z=0.0, maxiter=1000, xtol=1E-13, near_critical=True, xs=None, ys=None, zs=None, trivial_solution_tol=1e-5): print(Ks_y, Ks_z, beta_y, beta_z) beta_y, beta_z, xs_new, ys_new, zs_new = Rachford_Rice_solution2(ns=self.zs, Ks_y=Ks_y, Ks_z=Ks_z, beta_y=beta_y, beta_z=beta_z) print(beta_y, beta_z, xs_new, ys_new, zs_new) Ks_y = [exp(lnphi_x - lnphi_y) for lnphi_x, lnphi_y in zip(lnphis_x, lnphis_y)] Ks_z = [exp(lnphi_x - lnphi_z) for lnphi_x, lnphi_z in zip(lnphis_x, lnphis_z)] def newton_VL(self, Ks_initial=None, maxiter=30, ytol=1E-7, near_critical=True, xs=None, ys=None, V_over_F=None): T, P, zs = self.T, self.P, self.zs if xs is not None and ys is not None and V_over_F is not None: pass else: if Ks_initial is None: Ks = [Wilson_K_value(T, P, Tci, Pci, omega) for Pci, Tci, omega in zip(self.Pcs, self.Tcs, self.omegas)] else: Ks = Ks_initial V_over_F, xs, ys = flash_inner_loop(zs, Ks) lnKs_guess = [log(yi/xi) for yi, xi in zip(ys, xs)] + [V_over_F] info = [] def err_and_jacobian(lnKs_guess): err = self._err_VL_jacobian(lnKs_guess, T, P, zs, near_critical=True, err_also=True, info=info) # print(lnKs_guess[-1], err[0]) return err ans, count = newton_system(err_and_jacobian, jac=True, x0=lnKs_guess, ytol=ytol, maxiter=maxiter) V_over_F, xs, ys, eos_l, eos_g = info return V_over_F, xs, ys, eos_l, eos_g def broyden2_VL(self, Ks_initial=None, maxiter=30, ytol=1E-7, xtol=1e-8, near_critical=True, xs=None, ys=None, V_over_F=None): T, P, zs = self.T, self.P, self.zs if xs is not None and ys is not None and V_over_F is not None: pass else: if Ks_initial is None: Ks = [Wilson_K_value(T, P, Tci, Pci, omega) for Pci, Tci, omega in zip(self.Pcs, self.Tcs, self.omegas)] else: Ks = Ks_initial V_over_F, xs, ys = flash_inner_loop(zs, Ks) lnKs_guess = [log(yi/xi) for yi, xi in zip(ys, xs)] + [V_over_F] info = [] def err_and_jacobian(lnKs_guess): err = self._err_VL_jacobian(lnKs_guess, T, P, zs, near_critical=near_critical, err_also=True, info=info) # print(lnKs_guess[-1], err[0]) return err[0], err[1] def err(lnKs_guess): err = self._err_VL(lnKs_guess, T, P, zs, near_critical=near_critical, info=info) # print(lnKs_guess[-1], err[0]) return err ans, count = broyden2(fun=err, jac=err_and_jacobian, xs=lnKs_guess, xtol=xtol, maxiter=maxiter, jac_has_fun=True, skip_J=True) V_over_F, xs, ys, eos_l, eos_g = info return V_over_F, xs, ys, eos_l, eos_g, count def sequential_substitution_VL(self, Ks_initial=None, maxiter=1000, xtol=1E-13, near_critical=True, Ks_extra=None, xs=None, ys=None, trivial_solution_tol=1e-5, info=None, full_alphas=False): # print(self.zs, Ks) T, P, zs = self.T, self.P, self.zs V_over_F = None if xs is not None and ys is not None: pass else: # TODO use flash_wilson here if Ks_initial is None: Ks = [Wilson_K_value(T, P, Tci, Pci, omega) for Pci, Tci, omega in zip(self.Pcs, self.Tcs, self.omegas)] else: Ks = Ks_initial xs = None try: V_over_F, xs, ys = flash_inner_loop(zs, Ks) except ValueError as e: if Ks_extra is not None: for Ks in Ks_extra: try: V_over_F, xs, ys = flash_inner_loop(zs, Ks) break except ValueError as e: pass if xs is None: raise(e) # print(xs, ys, 'innerloop') # Z_l_prev = None # Z_g_prev = None for i in range(maxiter): if not near_critical: eos_g = self.to_TP_zs_fast(T=T, P=P, zs=ys, only_l=False, only_g=True, full_alphas=full_alphas) eos_l = self.to_TP_zs_fast(T=T, P=P, zs=xs, only_l=True, only_g=False, full_alphas=full_alphas) lnphis_g = eos_g.fugacity_coefficients(eos_g.Z_g) lnphis_l = eos_l.fugacity_coefficients(eos_l.Z_l) else: eos_g = self.to_TP_zs_fast(T=T, P=P, zs=ys, only_l=False, only_g=True, full_alphas=full_alphas) eos_l = self.to_TP_zs_fast(T=T, P=P, zs=xs, only_l=True, only_g=False, full_alphas=full_alphas) try: lnphis_g = eos_g.fugacity_coefficients(eos_g.Z_g) except AttributeError: lnphis_g = eos_g.fugacity_coefficients(eos_g.Z_l) try: lnphis_l = eos_l.fugacity_coefficients(eos_l.Z_l) except AttributeError: lnphis_l = eos_l.fugacity_coefficients(eos_l.Z_g) # eos_g = self.to_TP_zs(T=self.T, P=self.P, zs=ys) # eos_l = self.to_TP_zs(T=self.T, P=self.P, zs=xs) # if 0: # if hasattr(eos_g, 'lnphis_g') and hasattr(eos_g, 'lnphis_l'): # if Z_l_prev is not None and Z_g_prev is not None: # if abs(eos_g.Z_g - Z_g_prev) < abs(eos_g.Z_l - Z_g_prev): # lnphis_g = eos_g.lnphis_g # fugacities_g = eos_g.fugacities_g # Z_g_prev = eos_g.Z_g # else: # lnphis_g = eos_g.lnphis_l # fugacities_g = eos_g.fugacities_l # Z_g_prev = eos_g.Z_l # else: # if eos_g.G_dep_g < eos_g.lnphis_l: # lnphis_g = eos_g.lnphis_g # fugacities_g = eos_g.fugacities_g # Z_g_prev = eos_g.Z_g # else: # lnphis_g = eos_g.lnphis_l # fugacities_g = eos_g.fugacities_l # Z_g_prev = eos_g.Z_l # else: # try: # lnphis_g = eos_g.lnphis_g#fugacity_coefficients(eos_g.Z_g, ys) # fugacities_g = eos_g.fugacities_g # Z_g_prev = eos_g.Z_g # except AttributeError: # lnphis_g = eos_g.lnphis_l#fugacity_coefficients(eos_g.Z_l, ys) # fugacities_g = eos_g.fugacities_l # Z_g_prev = eos_g.Z_l # if hasattr(eos_l, 'lnphis_g') and hasattr(eos_l, 'lnphis_l'): # if Z_l_prev is not None and Z_g_prev is not None: # if abs(eos_l.Z_l - Z_l_prev) < abs(eos_l.Z_g - Z_l_prev): # lnphis_l = eos_l.lnphis_g # fugacities_l = eos_l.fugacities_g # Z_l_prev = eos_l.Z_g # else: # lnphis_l = eos_l.lnphis_l # fugacities_l = eos_l.fugacities_l # Z_l_prev = eos_l.Z_l # else: # if eos_l.G_dep_g < eos_l.lnphis_l: # lnphis_l = eos_l.lnphis_g # fugacities_l = eos_l.fugacities_g # Z_l_prev = eos_l.Z_g # else: # lnphis_l = eos_l.lnphis_l # fugacities_l = eos_l.fugacities_l # Z_l_prev = eos_l.Z_l # else: # try: # lnphis_l = eos_l.lnphis_g#fugacity_coefficients(eos_l.Z_g, ys) # fugacities_l = eos_l.fugacities_g # Z_l_prev = eos_l.Z_g # except AttributeError: # lnphis_l = eos_l.lnphis_l#fugacity_coefficients(eos_l.Z_l, ys) # fugacities_l = eos_l.fugacities_l # Z_l_prev = eos_l.Z_l # elif 0: # if hasattr(eos_g, 'lnphis_g') and hasattr(eos_g, 'lnphis_l'): # if eos_g.G_dep_g < eos_g.lnphis_l: # lnphis_g = eos_g.lnphis_g # fugacities_g = eos_g.fugacities_g # else: # lnphis_g = eos_g.lnphis_l # fugacities_g = eos_g.fugacities_l # else: # try: # lnphis_g = eos_g.lnphis_g#fugacity_coefficients(eos_g.Z_g, ys) # fugacities_g = eos_g.fugacities_g # except AttributeError: # lnphis_g = eos_g.lnphis_l#fugacity_coefficients(eos_g.Z_l, ys) # fugacities_g = eos_g.fugacities_l # # if hasattr(eos_l, 'lnphis_g') and hasattr(eos_l, 'lnphis_l'): # if eos_l.G_dep_g < eos_l.lnphis_l: # lnphis_l = eos_l.lnphis_g # fugacities_l = eos_l.fugacities_g # else: # lnphis_l = eos_l.lnphis_l # fugacities_l = eos_l.fugacities_l # else: # try: # lnphis_l = eos_l.lnphis_g#fugacity_coefficients(eos_l.Z_g, ys) # fugacities_l = eos_l.fugacities_g # except AttributeError: # lnphis_l = eos_l.lnphis_l#fugacity_coefficients(eos_l.Z_l, ys) # fugacities_l = eos_l.fugacities_l # # else: # print(phis_l, phis_g, 'phis') Ks = [exp(l - g) for l, g in zip(lnphis_l, lnphis_g)] # K_value(phi_l=l, phi_g=g) # print(Ks) # Hack - no idea if this will work # maxK = max(Ks) # if maxK < 1: # Ks[Ks.index(maxK)] = 1.1 # minK = min(Ks) # if minK >= 1: # Ks[Ks.index(minK)] = .9 # print(Ks, 'Ks into RR') V_over_F, xs_new, ys_new = flash_inner_loop(zs, Ks, guess=V_over_F) # if any(i < 0 for i in xs_new): # print('hil', xs_new) # # if any(i < 0 for i in ys_new): # print('hig', ys_new) for xi in xs_new: if xi < 0.0: xs_new_sum = sum(abs(i) for i in xs_new) xs_new = [abs(i)/xs_new_sum for i in xs_new] break for yi in ys_new: if yi < 0.0: ys_new_sum = sum(abs(i) for i in ys_new) ys_new = [abs(i)/ys_new_sum for i in ys_new] break # Claimed error function in CONVENTIONAL AND RAPID FLASH CALCULATIONS FOR THE SOAVE-REDLICH-KWONG AND PENG-ROBINSON EQUATIONS OF STATE err3 = 0.0 # Suggested tolerance 1e-15 for Ki, xi, yi in zip(Ks, xs, ys): # equivalent of fugacity ratio # Could divide by the old Ks as well. err_i = Ki*xi/yi - 1.0 err3 += err_i*err_i # or use absolute for tolerance... # err2 = sum([(exp(l-g)-1.0)**2 ]) # err2 = 0.0 # for l, g in zip(fugacities_l, fugacities_g): # err_i = (l/g-1.0) # err2 += err_i*err_i # Suggested tolerance 1e-15 # This is a better metric because it does not involve hysterisis # print(err3, err2) # err = (sum([abs(x_new - x_old) for x_new, x_old in zip(xs_new, xs)]) + # sum([abs(y_new - y_old) for y_new, y_old in zip(ys_new, ys)])) # print(err, err2) xs, ys = xs_new, ys_new # print(i, 'err', err, err2, 'xs, ys', xs, ys, 'VF', V_over_F) if near_critical: comp_difference = sum([abs(xi - yi) for xi, yi in zip(xs, ys)]) if comp_difference < trivial_solution_tol: raise ValueError("Converged to trivial condition, compositions of both phases equal") # print(xs) if err3 < xtol: break if i == maxiter-1: raise ValueError('End of SS without convergence') if info is not None: info[:] = (i, err3) return V_over_F, xs, ys, eos_l, eos_g def stabiliy_iteration_Michelsen(self, T, P, zs, Ks_initial=None, maxiter=20, xtol=1E-12, liq=True): # checks stability vs. the current zs, mole fractions # liq: whether adding a test liquid phase to see if is stable or not eos_ref = self#.to_TP_zs(T=T, P=P, zs=zs) # If one phase is present - use that phase as the reference phase. # Otherwise, consider the phase with the lowest Gibbs excess energy as # the stable phase fugacities_ref, fugacities_ref_phase = eos_ref._eos_fugacities_lowest_Gibbs() # print(fugacities_ref, fugacities_ref_phase, 'fugacities_ref, fugacities_ref_phase') if Ks_initial is None: Ks = [Wilson_K_value(T, P, Tci, Pci, omega) for Pci, Tci, omega in zip(self.Pcs, self.Tcs, self.omegas)] else: Ks = Ks_initial same_phase_count = 0.0 for _ in range(maxiter): if liq: zs_test = [zi/Ki for zi, Ki in zip(zs, Ks)] else: zs_test = [zi*Ki for zi, Ki in zip(zs, Ks)] sum_zs_test = sum(zs_test) zs_test_normalized = [zi/sum_zs_test for zi in zs_test] # if liq: # print(zs_test_normalized, sum_zs_test) # to_TP_zs_fast(self, T, P, zs, only_l=False, only_g=False) # IT IS NOT PERMISSIBLE TO DO ONLY ONE ROOT! 2019-03-20 # Breaks lots of stabilities. eos_test = self.to_TP_zs_fast(T=T, P=P, zs=zs_test_normalized, only_l=False, only_g=False, full_alphas=False) fugacities_test, fugacities_phase = eos_test._eos_fugacities_lowest_Gibbs() if fugacities_ref_phase == fugacities_phase: same_phase_count += 1.0 else: same_phase_count = 0 # if liq: # print(fugacities_test, fugacities_ref_phase, fugacities_phase) if liq: corrections = [fi/f_ref*sum_zs_test for fi, f_ref in zip(fugacities_test, fugacities_ref)] else: corrections = [f_ref/(fi*sum_zs_test) for fi, f_ref in zip(fugacities_test, fugacities_ref)] Ks = [Ki*corr for Ki, corr in zip(Ks, corrections)] corrections_minus_1 = [corr - 1.0 for corr in corrections] err = sum([ci*ci for ci in corrections_minus_1]) # print(err, xtol, Ks, corrections) # print('MM iter Ks =', Ks, 'zs', zs_test_normalized, 'MM err', err, xtol, _) if err < xtol: break # elif same_phase_count > 5: # break # It is possible to break if the trivial solution is being approached here also if _ == maxiter-1 and fugacities_ref_phase != fugacities_phase: raise UnconvergedError('End of stability_iteration_Michelsen without convergence') # Fails directly if fugacities_ref_phase == fugacities_phase # Fugacity error: # no, the fugacities are not supposed to be equal # err_equifugacity = 0 # for fi, fref in zip(fugacities_test, fugacities_ref): # err_equifugacity += abs(fi - fref) # if err_equifugacity/P > 1e-3: # sum_zs_test = 1 return sum_zs_test, Ks, fugacities_ref_phase == fugacities_phase def stability_Michelsen(self, T, P, zs, Ks_initial=None, maxiter=20, xtol=1E-12, trivial_criteria=1E-4, stable_criteria=1E-7): # print('MM starting, Ks=', Ks_initial) if Ks_initial is None: Ks = [Wilson_K_value(T, P, Tci, Pci, omega) for Pci, Tci, omega in zip(self.Pcs, self.Tcs, self.omegas)] else: Ks = Ks_initial zs_sum_g, Ks_g, phase_failure_g = self.stabiliy_iteration_Michelsen(T=T, P=P, zs=zs, Ks_initial=Ks, maxiter=maxiter, xtol=xtol, liq=False) zs_sum_l, Ks_l, phase_failure_l = self.stabiliy_iteration_Michelsen(T=T, P=P, zs=zs, Ks_initial=Ks, maxiter=maxiter, xtol=xtol, liq=True) log_Ks_g = [log(Ki) for Ki in Ks_g] log_Ks_l = [log(Ki) for Ki in Ks_l] lnK_2_tot_g = sum(log_Ki*log_Ki for log_Ki in log_Ks_g) lnK_2_tot_l = sum(log_Ki*log_Ki for log_Ki in log_Ks_l) sum_g_criteria = zs_sum_g - 1.0 sum_l_criteria = zs_sum_l - 1.0 trivial_g, trivial_l = False, False if lnK_2_tot_g < trivial_criteria: trivial_g = True if lnK_2_tot_l < trivial_criteria: trivial_l = True stable = False # print(Ks_l, Ks_g, 'Ks_l, Ks_g') # Table 4.6 Summary of Possible Phase Stability Test Results, # Phase Behavior, Whitson and Brule # There is a typo where Sl appears in the vapor column; this should be # liquid; as shown in https://www.e-education.psu.edu/png520/m17_p7.html g_pass, l_pass = False, False # pass means this phase cannot form another phase if phase_failure_g: g_pass = True if phase_failure_l: l_pass = True if trivial_g: g_pass = True if trivial_l: l_pass = True if sum_g_criteria < stable_criteria: g_pass = True if sum_l_criteria < stable_criteria: l_pass = True # print(l_pass, g_pass, 'l, g test show stable') if phase_failure_g and phase_failure_l: stable = True elif trivial_g and trivial_l: stable = True elif sum_g_criteria < stable_criteria and trivial_l: stable = True elif trivial_g and sum_l_criteria < stable_criteria: stable = True elif sum_g_criteria < stable_criteria and sum_l_criteria < stable_criteria: stable = True # These last two are custom, and it is apparent since they are bad # Also did not document well enough the cases they fail in # Disabled 2018-12-29 # elif trivial_l and sum_l_criteria < stable_criteria: # stable = True # elif trivial_g and sum_g_criteria < stable_criteria: # stable = True # else: # print('lnK_2_tot_g', lnK_2_tot_g , 'lnK_2_tot_l', lnK_2_tot_l, # 'sum_g_criteria', sum_g_criteria, 'sum_l_criteria', sum_l_criteria) # print('stable', stable, 'phase_failure_g', phase_failure_g, 'phase_failure_l', phase_failure_l, # 'sum_g_criteria', sum_g_criteria, 'sum_l_criteria', sum_l_criteria, # 'trivial_g', trivial_g, 'trivial_l', trivial_l) # No need to enumerate unstable results if not stable: # One set may be trivial, which means the other set is approx # the only use used Ks = [K_g*K_l for K_g, K_l in zip(Ks_g, Ks_l)] # print('MM ended', Ks, stable, Ks_g, Ks_l) return stable, Ks, [Ks_g, Ks_l] def _V_over_F_bubble_T_inner(self, T, P, zs, maxiter=20, xtol=1E-3): eos_l = self.to_TP_zs(T=T, P=P, zs=zs) if not hasattr(eos_l, 'V_l'): raise ValueError('At the specified temperature, there is no liquid root') Ks = [Wilson_K_value(T, P, Tci, Pci, omega) for Pci, Tci, omega in zip(self.Pcs, self.Tcs, self.omegas)] V_over_F, xs, ys = flash_inner_loop(zs, Ks) for i in range(maxiter): eos_g = self.to_TP_zs(T=T, P=P, zs=ys) if not hasattr(eos_g, 'V_g'): phis_g = eos_g.phis_l fugacities_g = eos_g.fugacities_l else: phis_g = eos_g.phis_g fugacities_g = eos_g.fugacities_g Ks = [K_value(phi_l=l, phi_g=g) for l, g in zip(eos_l.phis_l, phis_g)] V_over_F, xs, ys = flash_inner_loop(zs, Ks) err = sum([abs(i-j) for i, j in zip(eos_l.fugacities_l, fugacities_g)]) if err < xtol: break if not hasattr(eos_g, 'V_g'): raise ValueError('At the specified temperature, the solver did not converge to a vapor root') return V_over_F # raise Exception('Could not converge to desired tolerance') def _V_over_F_dew_T_inner(self, T, P, zs, maxiter=20, xtol=1E-10): eos_g = self.to_TP_zs(T=T, P=P, zs=zs) if not hasattr(eos_g, 'V_g'): raise ValueError('At the specified temperature, there is no vapor root') Ks = [Wilson_K_value(T, P, Tci, Pci, omega) for Pci, Tci, omega in zip(self.Pcs, self.Tcs, self.omegas)] V_over_F, xs, ys = flash_inner_loop(zs, Ks) for i in range(maxiter): eos_l = self.to_TP_zs(T=T, P=P, zs=xs) if not hasattr(eos_l, 'V_l'): phis_l = eos_l.phis_g fugacities_l = eos_l.fugacities_g else: phis_l = eos_l.phis_l fugacities_l = eos_l.fugacities_l Ks = [K_value(phi_l=l, phi_g=g) for l, g in zip(phis_l, eos_g.phis_g)] V_over_F, xs_new, ys_new = flash_inner_loop(zs, Ks) err = (sum([abs(x_new - x_old) for x_new, x_old in zip(xs_new, xs)]) + sum([abs(y_new - y_old) for y_new, y_old in zip(ys_new, ys)])) xs, ys = xs_new, ys_new if xtol < 1E-10: break if not hasattr(eos_l, 'V_l'): raise ValueError('At the specified temperature, the solver did not converge to a liquid root') return V_over_F-1.0 # return abs(V_over_F-1) def _V_over_F_dew_T_inner_accelerated(self, T, P, zs, maxiter=20, xtol=1E-10): '''This is not working. ''' eos_g = self.to_TP_zs(T=T, P=P, zs=zs) if not hasattr(eos_g, 'V_g'): raise ValueError('At the specified temperature, there is no vapor root') Ks = [Wilson_K_value(T, P, Tci, Pci, omega) for Pci, Tci, omega in zip(self.Pcs, self.Tcs, self.omegas)] V_over_F_new, xs, ys = flash_inner_loop(zs, Ks) for i in range(maxiter): eos_l = self.to_TP_zs(T=T, P=P, zs=xs) if not hasattr(eos_l, 'V_l'): phis_l = eos_l.phis_g fugacities_l = eos_l.fugacities_g else: phis_l = eos_l.phis_l fugacities_l = eos_l.fugacities_l if 0.0 < V_over_F_new < 1.0 and i > 2: Rs = [K_value(phi_l=l, phi_g=g) for l, g in zip(phis_l, eos_g.phis_g)] lambdas = [(Ki - 1.0)/(Ki - Rri) for Rri, Ki in zip(Rs, Ks)] Ks = [Ki*Ri**lambda_i for Ki, Ri, lambda_i in zip(Ks, Rs, lambdas)] else: Ks = [K_value(phi_l=l, phi_g=g) for l, g in zip(phis_l, eos_g.phis_g)] V_over_F_new, xs_new, ys_new = flash_inner_loop(zs, Ks) err_new = (sum([abs(x_new - x_old) for x_new, x_old in zip(xs_new, xs)]) + sum([abs(y_new - y_old) for y_new, y_old in zip(ys_new, ys)])) xs, ys = xs_new, ys_new V_over_F_old = V_over_F_new if i == 0: err_old = err_new err_old = err_new if err_new < xtol: break if not hasattr(eos_l, 'V_l'): raise ValueError('At the specified temperature, the solver did not converge to a liquid root') return V_over_F_new-1.0 # return abs(V_over_F-1) # def _a_alpha_j_rows(self): ## try: ## return self.a_alpha_j_rows ## except: ## pass # zs = self.zs # N = self.N # a_alpha_ijs = self.a_alpha_ijs # a_alpha_j_rows = [] # for i in range(N): # l = a_alpha_ijs[i] # sum_term = 0.0 # for j in range(N): # sum_term += zs[j]*l[j] # a_alpha_j_rows.append(sum_term) # self.a_alpha_j_rows = a_alpha_j_rows # return a_alpha_j_rows @property def _a_alpha_j_rows(self): try: return self.a_alpha_j_rows except: pass zs, N = self.zs, self.N a_alpha_ijs = self.a_alpha_ijs if self.scalar: a_alpha_j_rows = [0.0]*N else: a_alpha_j_rows = zeros(N) for i in range(N): l = a_alpha_ijs[i] for j in range(i): a_alpha_j_rows[j] += zs[i]*l[j] a_alpha_j_rows[i] += zs[j]*l[j] a_alpha_j_rows[i] += zs[i]*l[i] self.a_alpha_j_rows = a_alpha_j_rows return a_alpha_j_rows def _set_alpha_matrices(self): try: a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv = a_alpha_aijs_composition_independent(self.a_alphas, self.kijs) except ZeroDivisionError: a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv = a_alpha_aijs_composition_independent_support_zeros(self.a_alphas, self.kijs) _, _, _, a_alpha_ijs, da_alpha_dT_ijs, d2a_alpha_dT2_ijs = a_alpha_and_derivatives_full( self.a_alphas, self.da_alpha_dTs, self.d2a_alpha_dT2s, self.T, self.zs, self.kijs, a_alpha_ijs, self.a_alpha_roots, a_alpha_ij_roots_inv) self._d2a_alpha_dT2_ijs = d2a_alpha_dT2_ijs self._da_alpha_dT_ijs = da_alpha_dT_ijs self._a_alpha_ijs = a_alpha_ijs @property def a_alpha_ijs(self): r'''Calculate and return the matrix :math:`(a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}}`. Returns ------- a_alpha_ijs : list[list[float]] `a_alpha` terms for each component with every other component, [J^2/mol^2/Pa] Notes ----- In an earlier implementation this matrix was stored each EOS solve; however, allocating that much memory becomes quite expensive for large number of component cases and this is now calculated on-demand only. ''' try: return self._a_alpha_ijs except: self._set_alpha_matrices() return self._a_alpha_ijs @property def da_alpha_dT_ijs(self): r'''Calculate and return the matrix for the temperature derivatives of the alpha terms. .. math:: \frac{\partial (a\alpha)_{ij}}{\partial T} = \frac{\sqrt{\operatorname{a\alpha_{i}}{\left(T \right)} \operatorname{a\alpha_{j}} {\left(T \right)}} \left(1 - k_{ij}\right) \left(\frac{\operatorname{a\alpha_{i}} {\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)}}{2} + \frac{\operatorname{a\alpha_{j}}{\left(T \right)} \frac{d}{d T} \operatorname{ a\alpha_{i}}{\left(T \right)}}{2}\right)}{\operatorname{a\alpha_{i}}{\left(T \right)} \operatorname{a\alpha_{j}}{\left(T \right)}} Returns ------- da_alpha_dT_ijs : list[list[float]] First temperature derivative of `a_alpha` terms for each component with every other component, [J^2/mol^2/Pa/K] Notes ----- In an earlier implementation this matrix was stored each EOS solve; however, allocating that much memory becomes quite expensive for large number of component cases and this is now calculated on-demand only. ''' try: return self._da_alpha_dT_ijs except: self._set_alpha_matrices() return self._da_alpha_dT_ijs @property def d2a_alpha_dT2_ijs(self): r'''Calculate and return the matrix of the second temperature derivatives of the alpha terms. .. math:: \frac{\partial^2 (a\alpha)_{ij}}{\partial T^2} = - \frac{\sqrt{\operatorname{a\alpha_{i}}{\left(T \right)} \operatorname{a\alpha_{j}} {\left(T \right)}} \left(k_{ij} - 1\right) \left(\frac{\left(\operatorname{ a\alpha_{i}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)} + \operatorname{a\alpha_{j}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{i}} {\left(T \right)}\right)^{2}}{4 \operatorname{a\alpha_{i}}{\left(T \right)} \operatorname{a\alpha_{j}}{\left(T \right)}} - \frac{\left(\operatorname{a\alpha_{i}} {\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)} + \operatorname{a\alpha_{j}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{i}}{\left(T \right)}\right) \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)}}{2 \operatorname{a\alpha_{j}} {\left(T \right)}} - \frac{\left(\operatorname{a\alpha_{i}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)} + \operatorname{a\alpha_{j}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{i}}{\left(T \right)}\right) \frac{d}{d T} \operatorname{a\alpha_{i}}{\left(T \right)}}{2 \operatorname{a\alpha_{i}} {\left(T \right)}} + \frac{\operatorname{a\alpha_{i}}{\left(T \right)} \frac{d^{2}}{d T^{2}} \operatorname{a\alpha_{j}}{\left(T \right)}}{2} + \frac{\operatorname{a\alpha_{j}}{\left(T \right)} \frac{d^{2}}{d T^{2}} \operatorname{a\alpha_{i}}{\left(T \right)}}{2} + \frac{d}{d T} \operatorname{a\alpha_{i}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)}\right)} {\operatorname{a\alpha_{i}}{\left(T \right)} \operatorname{a\alpha_{j}} {\left(T \right)}} Returns ------- d2a_alpha_dT2_ijs : list[list[float]] Second temperature derivative of `a_alpha` terms for each component with every other component, [J^2/mol^2/Pa/K^2] Notes ----- In an earlier implementation this matrix was stored each EOS solve; however, allocating that much memory becomes quite expensive for large number of component cases and this is now calculated on-demand only. ''' try: return self._d2a_alpha_dT2_ijs except: self._set_alpha_matrices() return self._d2a_alpha_dT2_ijs @property def _da_alpha_dT_j_rows(self): try: return self.da_alpha_dT_j_rows except: pass zs, N, scalar = self.zs, self.N, self.N da_alpha_dT_ijs = self.da_alpha_dT_ijs # Handle the case of attempting to avoid a full alpha derivative matrix evaluation if not da_alpha_dT_ijs: self.resolve_full_alphas() da_alpha_dT_ijs = self.da_alpha_dT_ijs if scalar: da_alpha_dT_j_rows = [0.0]*N else: da_alpha_dT_j_rows = zeros(N) for i in range(N): l = da_alpha_dT_ijs[i] for j in range(i): da_alpha_dT_j_rows[j] += zs[i]*l[j] da_alpha_dT_j_rows[i] += zs[j]*l[j] da_alpha_dT_j_rows[i] += zs[i]*l[i] self.da_alpha_dT_j_rows = da_alpha_dT_j_rows return da_alpha_dT_j_rows @property def _d2a_alpha_dT2_j_rows(self): try: return self.d2a_alpha_dT2_j_rows except AttributeError: pass d2a_alpha_dT2_ijs, N, scalar = self.d2a_alpha_dT2_ijs, self.N, self.scalar # Handle the case of attempting to avoid a full alpha derivative matrix evaluation if d2a_alpha_dT2_ijs is None: self.resolve_full_alphas() d2a_alpha_dT2_ijs = self.d2a_alpha_dT2_ijs zs = self.zs if scalar: d2a_alpha_dT2_j_rows = [0.0]*N else: d2a_alpha_dT2_j_rows = zeros(N) for i in range(N): l = d2a_alpha_dT2_ijs[i] for j in range(i): d2a_alpha_dT2_j_rows[j] += zs[i]*l[j] d2a_alpha_dT2_j_rows[i] += zs[j]*l[j] d2a_alpha_dT2_j_rows[i] += zs[i]*l[i] self.d2a_alpha_dT2_j_rows = d2a_alpha_dT2_j_rows return d2a_alpha_dT2_j_rows @property def db_dzs(self): r'''Helper method for calculating the composition derivatives of `b`. Note this is independent of the phase. .. math:: \left(\frac{\partial b}{\partial x_i}\right)_{T, P, x_{i\ne j}} = b_i Returns ------- db_dzs : list[float] Composition derivative of `b` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' return self.bs @property def db_dns(self): r'''Helper method for calculating the mole number derivatives of `b`. Note this is independent of the phase. .. math:: \left(\frac{\partial b}{\partial n_i}\right)_{T, P, n_{i\ne j}} = b_i - b Returns ------- db_dns : list[float] Composition derivative of `b` of each component, [m^3/mol^2] Notes ----- This derivative is checked numerically. ''' b = self.b if self.scalar: return [bi - b for bi in self.bs] else: return self.bs - b @property def dnb_dns(self): r'''Helper method for calculating the partial molar derivative of `b`. Note this is independent of the phase. .. math:: \left(\frac{\partial n \cdot b}{\partial n_i}\right)_{T, P, n_{i\ne j}} = b_i Returns ------- dnb_dns : list[float] Partial molar derivative of `b` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' return self.bs @property def d2b_dzizjs(self): r'''Helper method for calculating the second partial mole fraction derivatives of `b`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 b}{\partial x_i \partial x_j} \right)_{T, P, n_{k \ne i,j}} = 0 Returns ------- d2b_dzizjs : list[list[float]] Second mole fraction derivatives of `b` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: return [[0.0]*N for i in range(N)] return zeros((N, N)) @property def d2b_dninjs(self): r'''Helper method for calculating the second partial mole number derivatives of `b`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 b}{\partial n_i \partial n_j}\right)_{T, P, n_{k\ne i,k}} = 2b - b_i - b_j Returns ------- d2b_dninjs : list[list[float]] Second Composition derivative of `b` of each component, [m^3/mol^3] Notes ----- This derivative is checked numerically. ''' bb = 2.0*self.b bs = self.bs if self.scalar: d2b_dninjs = [] for bi in bs: d2b_dninjs.append([bb - bi - bj for bj in bs]) else: N = self.N d2b_dninjs = full((N, N), bb) d2b_dninjs -= bs d2b_dninjs = d2b_dninjs.transpose() d2b_dninjs -= bs return d2b_dninjs @property def d3b_dzizjzks(self): r'''Helper method for calculating the third partial mole fraction derivatives of `b`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 b}{\partial x_i \partial x_j \partial x_k} \right)_{T, P, n_{k \ne i,j,k}} = 0 Returns ------- d3b_dzizjzks : list[list[list[float]]] Third mole fraction derivatives of `b` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: return [[[0.0]*N for _ in range(N)] for _ in range(N)] else: return zeros((N, N, N)) @property def d3b_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `b`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 b}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 2(-3b + b_i + b_j + b_k) Returns ------- d3b_dninjnks : list[list[list[float]]] Third mole number derivative of `b` of each component, [m^3/mol^4] Notes ----- This derivative is checked numerically. ''' bs = self.bs n6b = -6.0*self.b if self.scalar: bs2 = [bi + bi for bi in bs] d3b_dninjnks = [] for bi2 in bs2: d3b_dnjnks = [] for bj2 in bs2: base = n6b + bi2 + bj2 d3b_dnjnks.append([base + bk2 for bk2 in bs2]) d3b_dninjnks.append(d3b_dnjnks) else: bs2 = 2.0*self.bs N = self.N d3b_dninjnks = full((N, N, N), n6b) d3b_dninjnks += bs2 d3b_dninjnks = d3b_dninjnks.transpose((2, 1, 0)) d3b_dninjnks += bs2 d3b_dninjnks = d3b_dninjnks.transpose((0, 2, 1)) d3b_dninjnks += bs2 return d3b_dninjnks @property def d3epsilon_dzizjzks(self): r'''Helper method for calculating the third composition derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \epsilon}{\partial x_i \partial x_j \partial x_k }\right)_{T, P, x_{m\ne i,j,k}} = 0 Returns ------- d2epsilon_dzizjzks : list[list[list[float]]] Composition derivative of `epsilon` of each component, [m^6/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: return [[[0.0]*N for _ in range(N)] for _ in range(N)] else: return zeros((N, N, N)) @property def d3delta_dzizjzks(self): r'''Helper method for calculating the third composition derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \delta}{\partial x_i \partial x_j \partial x_k }\right)_{T, P, x_{m\ne i,j,k}} = 0 Returns ------- d3delta_dzizjzks : list[list[list[float]]] Third composition derivative of `epsilon` of each component, [m^6/mol^5] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: return [[[0.0]*N for _ in range(N)] for _ in range(N)] else: return zeros((N, N, N)) @property def da_alpha_dzs(self): r'''Helper method for calculating the composition derivatives of `a_alpha`. Note this is independent of the phase. .. math:: \left(\frac{\partial a \alpha}{\partial x_i}\right)_{T, P, x_{i\ne j}} = 2 \cdot \sum_j z_{j} (1 - k_{ij}) \sqrt{ (a \alpha)_i (a \alpha)_j} Returns ------- da_alpha_dzs : list[float] Composition derivative of `alpha` of each component, [kg*m^5/(mol^2*s^2)] Notes ----- This derivative is checked numerically. ''' try: a_alpha_j_rows = self.a_alpha_j_rows except: a_alpha_j_rows = self._a_alpha_j_rows if self.scalar: return [i + i for i in a_alpha_j_rows] return 2.0*a_alpha_j_rows @property def da_alpha_dns(self): r'''Helper method for calculating the mole number derivatives of `a_alpha`. Note this is independent of the phase. .. math:: \left(\frac{\partial a \alpha}{\partial n_i}\right)_{T, P, n_{i\ne j}} = 2 (-a\alpha + \sum_j z_{j} (1 - k_{ij}) \sqrt{ (a \alpha)_i (a \alpha)_j}) Returns ------- da_alpha_dns : list[float] Mole number derivative of `alpha` of each component, [kg*m^5/(mol^3*s^2)] Notes ----- This derivative is checked numerically. ''' try: a_alpha_j_rows = self.a_alpha_j_rows except: a_alpha_j_rows = self._a_alpha_j_rows a_alpha_n_2 = -2.0*self.a_alpha if self.scalar: return [2.0*t + a_alpha_n_2 for t in a_alpha_j_rows] return 2.0*a_alpha_j_rows + a_alpha_n_2 @property def dna_alpha_dns(self): r'''Helper method for calculating the partial molar derivatives of `a_alpha`. Note this is independent of the phase. .. math:: \left(\frac{\partial a \alpha}{\partial n_i}\right)_{T, P, n_{i\ne j}} = 2 (-0.5 a\alpha + \sum_j z_{j} (1 - k_{ij}) \sqrt{ (a \alpha)_i (a \alpha)_j}) Returns ------- dna_alpha_dns : list[float] Partial molar derivative of `alpha` of each component, [kg*m^5/(mol^2*s^2)] Notes ----- This derivative is checked numerically. ''' try: a_alpha_j_rows = self.a_alpha_j_rows except: a_alpha_j_rows = self._a_alpha_j_rows a_alpha = self.a_alpha if self.scalar: return [t + t - a_alpha for t in a_alpha_j_rows] return 2.0*a_alpha_j_rows - a_alpha @property def d2a_alpha_dzizjs(self): r'''Helper method for calculating the second composition derivatives of `a_alpha` (hessian). Note this is independent of the phase. .. math:: \left(\frac{\partial^2 a \alpha}{\partial x_i \partial x_j}\right)_{T, P, x_{k\ne i,j}} = 2 (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} Returns ------- d2a_alpha_dzizjs : list[float] Second composition derivative of `alpha` of each component, [kg*m^5/(mol^2*s^2)] Notes ----- This derivative is checked numerically. ''' a_alpha_ijs = self.a_alpha_ijs if self.scalar: return [[i+i for i in row] for row in a_alpha_ijs] else: return 2.0*a_alpha_ijs @property def d2a_alpha_dninjs(self): r'''Helper method for calculating the second partial molar derivatives of `a_alpha` (hessian). Note this is independent of the phase. .. math:: \left(\frac{\partial^2 a \alpha}{\partial n_i \partial n_j }\right)_{T, P, n_{k\ne i,j}} = 2\left[3(a \alpha) + (a\alpha)_{ij} -2 (\text{term}_{i,j}) \right] .. math:: \text{term}_{i,j} = \sum_k z_k\left((a\alpha)_{ik} + (a\alpha)_{jk} \right) .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} Returns ------- d2a_alpha_dninjs : list[float] Second partial molar derivative of `alpha` of each component, [kg*m^5/(mol^4*s^2)] Notes ----- This derivative is checked numerically. ''' try: a_alpha_j_rows = self.a_alpha_j_rows except: a_alpha_j_rows = self._a_alpha_j_rows a_alpha = self.a_alpha a_alpha_ijs = self.a_alpha_ijs N = self.N zs = self.zs a_alpha3 = 3.0*a_alpha if self.scalar: hessian = [[0.0]*N for _ in range(N)] else: hessian = zeros((N, N)) for i in range(N): for j in range(i+1): if i == j: term = 2.0*a_alpha_j_rows[i] else: term = 0.0 for k in range(N): term += zs[k]*(a_alpha_ijs[i][k] + a_alpha_ijs[j][k]) hessian[i][j] = hessian[j][i] = 2.0*(a_alpha3 + a_alpha_ijs[i][j] -2.0*term) # row.append(2.0*(a_alpha3 + a_alpha_ijs[i][j] -2.0*term)) # hessian.append(row) return hessian @property def d3a_alpha_dzizjzks(self): r'''Helper method for calculating the third composition derivatives of `a_alpha`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 a \alpha}{\partial x_i \partial x_j \partial x_k}\right)_{T, P, x_{m\ne i,j,k}} = 0 Returns ------- d3a_alpha_dzizjzks : list[float] Third composition derivative of `alpha` of each component, [kg*m^5/(mol^2*s^2)] Notes ----- This derivative is checked numerically. ''' N = self.N return [[[0.0]*N for _ in range(N)] for _ in range(N)] @property def d3a_alpha_dninjnks(self): r'''Helper method for calculating the third mole number derivatives of `a_alpha`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 a \alpha}{\partial n_i \partial n_j \partial n_k}\right)_{T, P, n_{m\ne i,j,k}} = 4\left(-6 (a \alpha) - [(a \alpha)_{i,j} + (a \alpha)_{i,k} + (a \alpha)_{j,k}] + 3\sum_m z_m[(a \alpha)_{i,m} + (a \alpha)_{j,m} + (a \alpha)_{k,m}]\right) Returns ------- d3a_alpha_dninjnks : list[float] Third mole number derivative of `alpha` of each component, [kg*m^5/(mol^5*s^2)] Notes ----- This derivative is checked numerically. ''' # Seems correct across diagonal # Each term is of similar magnitude, so likely would notice if brokwn a_alpha = self.a_alpha a_alpha_ijs = self.a_alpha_ijs N = self.N zs = self.zs a_alpha6 = -6.0*a_alpha matrix = [] for i in range(N): l = [] for j in range(N): row = [] for k in range(N): mid = a_alpha_ijs[i][j] + a_alpha_ijs[i][k] + a_alpha_ijs[j][k] last = sum(zs[m]*(a_alpha_ijs[i][m] + a_alpha_ijs[j][m] + a_alpha_ijs[k][m]) for m in range(N)) ele = 4.0*(a_alpha6 - mid + 3.0*last) row.append(ele) l.append(row) matrix.append(l) return matrix @property def da_alpha_dT_dzs(self): r'''Helper method for calculating the composition derivatives of `da_alpha_dT`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 a \alpha}{\partial x_i \partial T} \right)_{P, x_{i\ne j}} = 2 \sum_j -z_{j} (k_{ij} - 1) (a \alpha)_i (a \alpha)_j \frac{\partial (a \alpha)_i}{\partial T} \frac{\partial (a \alpha)_j}{\partial T} \left({ (a \alpha)_i (a \alpha)_j}\right)^{-0.5} Returns ------- da_alpha_dT_dzs : list[float] Composition derivative of `da_alpha_dT` of each component, [kg*m^5/(mol^2*s^2*K)] Notes ----- This derivative is checked numerically. ''' try: da_alpha_dT_j_rows = self.da_alpha_dT_j_rows except: da_alpha_dT_j_rows = self._da_alpha_dT_j_rows return [i + i for i in da_alpha_dT_j_rows] @property def da_alpha_dT_dns(self): r'''Helper method for calculating the mole number derivatives of `da_alpha_dT`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 a \alpha}{\partial n_i \partial T} \right)_{P, n_{i\ne j}} = 2 \left[\sum_j -z_{j} (k_{ij} - 1) (a \alpha)_i (a \alpha)_j \frac{\partial (a \alpha)_i}{\partial T} \frac{\partial (a \alpha)_j}{\partial T} \left({ (a \alpha)_i (a \alpha)_j}\right)^{-0.5} - \frac{\partial a \alpha}{\partial T} \right] Returns ------- da_alpha_dT_dns : list[float] Composition derivative of `da_alpha_dT` of each component, [kg*m^5/(mol^3*s^2*K)] Notes ----- This derivative is checked numerically. ''' try: da_alpha_dT_j_rows = self.da_alpha_dT_j_rows except: da_alpha_dT_j_rows = self._da_alpha_dT_j_rows da_alpha_dT = self.da_alpha_dT return [2.0*(t - da_alpha_dT) for t in da_alpha_dT_j_rows] @property def dna_alpha_dT_dns(self): r'''Helper method for calculating the mole number derivatives of `da_alpha_dT`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 n a \alpha}{\partial n_i \partial T} \right)_{P, n_{i\ne j}} = 2 \left[\sum_j -z_{j} (k_{ij} - 1) (a \alpha)_i (a \alpha)_j \frac{\partial (a \alpha)_i}{\partial T} \frac{\partial (a \alpha)_j}{\partial T} \left({ (a \alpha)_i (a \alpha)_j}\right)^{-0.5} - 0.5 \frac{\partial a \alpha}{\partial T} \right] Returns ------- dna_alpha_dT_dns : list[float] Composition derivative of `da_alpha_dT` of each component, [kg*m^5/(mol^2*s^2*K)] Notes ----- This derivative is checked numerically. ''' try: da_alpha_dT_j_rows = self.da_alpha_dT_j_rows except: da_alpha_dT_j_rows = self._da_alpha_dT_j_rows da_alpha_dT = self.da_alpha_dT return [t + t - da_alpha_dT for t in da_alpha_dT_j_rows] @property def d2a_alpha_dT2_dzs(self): r'''Helper method for calculating the mole number derivatives of `d2a_alpha_dT2`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 a \alpha}{\partial z_i \partial T^2} \right)_{P, z_{i\ne j}} = \text{large expression} Returns ------- d2a_alpha_dT2_dzs : list[float] Composition derivative of `d2a_alpha_dT2` of each component, [kg*m^5/(mol^2*s^2*K^2)] Notes ----- This derivative is checked numerically. ''' try: d2a_alpha_dT2_j_rows = self.d2a_alpha_dT2_j_rows except: d2a_alpha_dT2_j_rows = self._d2a_alpha_dT2_j_rows return [i + i for i in d2a_alpha_dT2_j_rows] @property def d2a_alpha_dT2_dns(self): r'''Helper method for calculating the mole number derivatives of `d2a_alpha_dT2`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 a \alpha}{\partial n_i \partial T^2} \right)_{P, n_{i\ne j}} = f\left(\left(\frac{\partial^3 a\alpha}{\partial z_i \partial T^2} \right)_{P, z_{i\ne j}} \right) Returns ------- d2a_alpha_dT2_dns : list[float] Mole number derivative of `d2a_alpha_dT2` of each component, [kg*m^5/(mol^3*s^2*K^2)] Notes ----- This derivative is checked numerically. ''' try: d2a_alpha_dT2_j_rows = self.d2a_alpha_dT2_j_rows except: d2a_alpha_dT2_j_rows = self._d2a_alpha_dT2_j_rows d2a_alpha_dT2 = self.d2a_alpha_dT2 return [2.0*(t - d2a_alpha_dT2) for t in d2a_alpha_dT2_j_rows] def dV_dzs(self, Z): r'''Calculates the molar volume composition derivative (where the mole fractions do not sum to 1). Verified numerically. Used in many other derivatives, and for the molar volume mole number derivative and partial molar volume calculation. .. math:: \left(\frac{\partial V}{\partial x_i}\right)_{T, P, x_{i\ne j}} = \frac{- R T \left(V^{2}{\left(x \right)} + V{\left(x \right)} \delta{\left(x \right)} + \epsilon{\left(x \right)}\right)^{3} \frac{d}{d x} b{\left(x \right)} + \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} \left(V^{2}{\left(x \right)} + V{\left(x \right)} \delta{\left(x \right)} + \epsilon{\left(x \right)}\right)^{2} \frac{d}{d x} \operatorname{a \alpha}{\left(x \right)} - \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} V^{3}{\left(x \right)} \operatorname{a \alpha}{\left(x \right)} \frac{d}{d x} \delta{\left(x \right)} - \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} V^{2}{\left(x \right)} \operatorname{a \alpha}{\left(x \right)} \delta{\left(x \right)} \frac{d}{d x} \delta{\left(x \right)} - \left(V{\left(x \right)} - b{\left(x \right)} \right)^{2} V^{2}{\left(x \right)} \operatorname{a \alpha}{\left(x \right)} \frac{d}{d x} \epsilon{ \left(x \right)} - \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} V{\left(x \right)} \operatorname{a \alpha}{\left(x \right)} \delta{\left(x \right)} \frac{d}{d x} \epsilon{\left(x \right)} - \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} V{\left(x \right)} \operatorname{a \alpha}{\left(x \right)} \epsilon{\left(x \right)} \frac{d}{d x} \delta{\left(x \right)} - \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} \operatorname{a \alpha}{\left(x \right)} \epsilon{\left(x \right)} \frac{d}{d x} \epsilon{\left(x \right)}}{- R T \left(V^{2}{\left(x \right)} + V{\left(x \right)} \delta{\left(x \right)} + \epsilon{\left(x \right)}\right)^{3} + 2 \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} V^{3}{\left(x \right)} \operatorname{a \alpha}{\left(x \right)} + 3 \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} V^{2}{\left(x \right)} \operatorname{a \alpha}{\left(x \right)} \delta{\left(x \right)} + \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} V{\left(x \right)} \operatorname{a \alpha}{\left(x \right)} \delta^{2}{\left(x \right)} + 2 \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} V{\left(x \right)} \operatorname{a \alpha}{\left(x \right)} \epsilon{\left(x \right)} + \left(V{\left(x \right)} - b{\left(x \right)}\right)^{2} \operatorname{a \alpha}{\left(x \right)} \delta{\left(x \right)} \epsilon{\left(x \right)}} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dV_dzs : float Molar volume composition derivatives, [m^3/mol] Notes ----- The derivation for the derivative is performed as follows using SymPy. The function source code is an optimized variant created with the `cse` SymPy function, and hand optimized further. >>> from sympy import * # doctest:+SKIP >>> P, T, R, x = symbols('P, T, R, x') # doctest:+SKIP >>> V, delta, epsilon, a_alpha, b = symbols('V, delta, epsilon, a\ \\alpha, b', cls=Function) # doctest:+SKIP >>> CUBIC = R*T/(V(x) - b(x)) - a_alpha(x)/(V(x)*V(x) + delta(x)*V(x) + epsilon(x)) - P # doctest:+SKIP >>> solve(diff(CUBIC, x), Derivative(V(x), x)) # doctest:+SKIP [(-R*T*(V(x)**2 + V(x)*delta(x) + epsilon(x))**3*Derivative(b(x), x) + (V(x) - b(x))**2*(V(x)**2 + V(x)*delta(x) + epsilon(x))**2*Derivative(a \alpha(x), x) - (V(x) - b(x))**2*V(x)**3*a \alpha(x)*Derivative(delta(x), x) - (V(x) - b(x))**2*V(x)**2*a \alpha(x)*delta(x)*Derivative(delta(x), x) - (V(x) - b(x))**2*V(x)**2*a \alpha(x)*Derivative(epsilon(x), x) - (V(x) - b(x))**2*V(x)*a \alpha(x)*delta(x)*Derivative(epsilon(x), x) - (V(x) - b(x))**2*V(x)*a \alpha(x)*epsilon(x)*Derivative(delta(x), x) - (V(x) - b(x))**2*a \alpha(x)*epsilon(x)*Derivative(epsilon(x), x))/(-R*T*(V(x)**2 + V(x)*delta(x) + epsilon(x))**3 + 2*(V(x) - b(x))**2*V(x)**3*a \alpha(x) + 3*(V(x) - b(x))**2*V(x)**2*a \alpha(x)*delta(x) + (V(x) - b(x))**2*V(x)*a \alpha(x)*delta(x)**2 + 2*(V(x) - b(x))**2*V(x)*a \alpha(x)*epsilon(x) + (V(x) - b(x))**2*a \alpha(x)*delta(x)*epsilon(x))] ''' return eos_mix_dV_dzs(self.T, self.P, Z, self.b, self.delta, self.epsilon, self.a_alpha, self.db_dzs, self.ddelta_dzs, self.depsilon_dzs, self.da_alpha_dzs, self.N) def dV_dns(self, Z): r'''Calculates the molar volume mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative. .. math:: \left(\frac{\partial V}{\partial n_i}\right)_{T, P, n_{i\ne j}} = f\left( \left(\frac{\partial V}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dV_dns : float Molar volume mole number derivatives, [m^3/mol^2] ''' dV_dns = dxs_to_dns(self.dV_dzs(Z), self.zs) if not self.scalar: dV_dns = array(dV_dns) return dV_dns def dnV_dns(self, Z): r'''Calculates the partial molar volume of the specified phase No specific formula is implemented for this property - it is calculated from the molar volume mole fraction derivative. .. math:: \left(\frac{\partial n V}{\partial n_i}\right)_{T, P, n_{i\ne j}} = f\left( \left(\frac{\partial V}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dnV_dns : float Partial molar volume of the mixture of the specified phase, [m^3/mol] ''' V = Z*R*self.T/self.P return dxs_to_dn_partials(self.dV_dzs(Z), self.zs, V) def _d2V_dij_wrapper(self, V, d_Vs, dbs, d2bs, d_epsilons, d2_epsilons, d_deltas, d2_deltas, da_alphas, d2a_alphas): T = self.T x0 = V x3 = self.b x4 = x0 - x3 x5 = self.epsilon x6 = x0*x0 x7 = self.delta x8 = x0*x7 x9 = x5 + x6 + x8 x10 = self.a_alpha x11 = x10*x4*x4 x12 = x0 + x0 x13 = x9*x9 x14 = R*T x17 = x4*x4*x4 x18 = x10*x17 x19 = 2*x18 x22 = 4*x18 x27 = x12*x18 x33 = x14*x13*x9 x34 = x33 + x33 x37 = x19*x8 x38 = x17*x9 x39 = x10*x38 hessian = [] N = self.N for i in range(N): row = [] for j in range(N): # TODO optimize this - symmetric, others x15 = d_epsilons[i] x16 = d_epsilons[j] x20 = x16*x19 x21 = d_Vs[i] x24 = d_Vs[j] x23 = x21*x22 x25 = x15*x24 x26 = d_deltas[i] x28 = d_deltas[j] x29 = x21*x24 x30 = 8*x18*x29 x31 = x28*x6 x32 = x24*x26 x35 = x34*dbs[j] x36 = dbs[i] x40 = x38*da_alphas[i] x41 = x38*da_alphas[j] x42 = x21*x41 x43 = x24*x40 x44 = x21*x39 d1 = d2_deltas[i][j] # Derivative(x7, x1, x2) d2 = d2a_alphas[i][j] # Derivative(x10, x1, x2) d3 = d2bs[i][j] # Derivative(x3, x1, x2) d4 = d2_epsilons[i][j] # Derivative(x5, x1, x2) v = ((x0*x16*x23 + x0*x22*x25 - x0*x26*x41 - x0*x28*x40 - x0*x39*d1 - x12*x42 - x12*x43 + x13*x17*d2 + x15*x20 + x15*x27*x28 - x15*x41 + x16*x26*x27 - x16*x40 + x19*x25*x7 + x19*x26*x31 + x19*x29*x7**2 + x20*x21*x7 + x21*x28*x37 + x21*x35 + x22*x32*x6 + x23*x31 + x24*x34*x36 - 2*x24*x44 - x28*x44 - x29*x34 + x30*x6 + x30*x8 + x32*x37 - x32*x39 - x33*x4*d3 - x35*x36 - x39*d4 - x42*x7 - x43*x7)/(x4*x9*(x11*x12 + x11*x7 - x13*x14))) row.append(v) hessian.append(row) return hessian def d2V_dzizjs(self, Z): r'''Calculates the molar volume second composition derivative (where the mole fractions do not sum to 1). Verified numerically. Used in many other derivatives, and for the molar volume second mole number derivative. .. math:: \left(\frac{\partial^2 V}{\partial x_i \partial x_j}\right)_{T, P, x_{k \ne i,j}} = \text{run SymPy code to obtain - very long!} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- d2V_dzizjs : float Molar volume second composition derivatives, [m^3/mol] Notes ----- The derivation for the derivative is performed as follows using SymPy. The function source code is an optimized variant created with the `cse` SymPy function, and hand optimized further. >>> from sympy import * # doctest:+SKIP >>> P, T, R, x1, x2 = symbols('P, T, R, x1, x2') # doctest:+SKIP >>> V, delta, epsilon, a_alpha, b = symbols('V, delta, epsilon, a\ \\alpha, b', cls=Function) # doctest:+SKIP >>> CUBIC = R*T/(V(x1, x2) - b(x1, x2)) - a_alpha(x1, x2)/(V(x1, x2)*V(x1, x2) + delta(x1, x2)*V(x1, x2) + epsilon(x1, x2)) - P # doctest:+SKIP >>> solve(diff(CUBIC, x1, x2), Derivative(V(x1, x2), x1, x2)) # doctest:+SKIP ''' V = Z*self.T*R/self.P dV_dzs = self.dV_dzs(Z) depsilon_dzs = self.depsilon_dzs d2epsilon_dzizjs = self.d2epsilon_dzizjs ddelta_dzs = self.ddelta_dzs d2delta_dzizjs = self.d2delta_dzizjs db_dzs = self.db_dzs d2bs = self.d2b_dzizjs da_alpha_dzs = self.da_alpha_dzs d2a_alpha_dzizjs = self.d2a_alpha_dzizjs return self._d2V_dij_wrapper(V=V, d_Vs=dV_dzs, dbs=db_dzs, d2bs=d2bs, d_epsilons=depsilon_dzs, d2_epsilons=d2epsilon_dzizjs, d_deltas=ddelta_dzs, d2_deltas=d2delta_dzizjs, da_alphas=da_alpha_dzs, d2a_alphas=d2a_alpha_dzizjs) def d2V_dninjs(self, Z): r'''Calculates the molar volume second mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the second mole fraction derivatives. .. math:: \left(\frac{\partial^2 V}{\partial n_i \partial n_j}\right)_{T, P, n_{k\ne i,j}} = f\left( \left(\frac{\partial^2 V}{\partial x_i\partial x_j}\right)_{T, P, x_{k\ne i,j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- d2V_dninjs : float Molar volume second mole number derivatives, [m^3/mol^3] ''' V = Z*self.T*R/self.P dV_dns = self.dV_dns(Z) depsilon_dns = self.depsilon_dns d2epsilon_dninjs = self.d2epsilon_dninjs ddelta_dns = self.ddelta_dns d2delta_dninjs = self.d2delta_dninjs db_dns = self.db_dns d2bs = self.d2b_dninjs da_alpha_dns = self.da_alpha_dns d2a_alpha_dninjs = self.d2a_alpha_dninjs return self._d2V_dij_wrapper(V=V, d_Vs=dV_dns, dbs=db_dns, d2bs=d2bs, d_epsilons=depsilon_dns, d2_epsilons=d2epsilon_dninjs, d_deltas=ddelta_dns, d2_deltas=d2delta_dninjs, da_alphas=da_alpha_dns, d2a_alphas=d2a_alpha_dninjs) def dZ_dzs(self, Z): r'''Calculates the compressibility composition derivatives (where the mole fractions do not sum to 1). No specific formula is implemented for this property - it is calculated from the composition derivative of molar volume, which does have its formula implemented. .. math:: \left(\frac{\partial Z}{\partial x_i}\right)_{T, P, x_{i\ne j}} = \frac{P }{RT} \left(\frac{\partial V}{\partial x_i}\right)_{T, P, x_{i\ne j}} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dZ_dzs : float Compressibility composition derivative, [-] ''' factor = self.P/(self.T*R) return [dV*factor for dV in self.dV_dzs(Z)] def dZ_dns(self, Z): r'''Calculates the compressibility mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative. .. math:: \left(\frac{\partial Z}{\partial n_i}\right)_{T, P, n_{i\ne j}} = f\left( \left(\frac{\partial Z}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dZ_dns : float Compressibility number derivatives, [1/mol] ''' return dxs_to_dns(self.dZ_dzs(Z), self.zs) def dnZ_dns(self, Z): r'''Calculates the partial compressibility of the specified phase No specific formula is implemented for this property - it is calculated from the compressibility mole fraction derivative. .. math:: \left(\frac{\partial n Z}{\partial n_i}\right)_{T, P, n_{i\ne j}} = f\left( \left(\frac{\partial Z}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dnZ_dns : float Partial compressibility of the mixture of the specified phase, [-] ''' return dxs_to_dn_partials(self.dZ_dzs(Z), self.zs, Z) def dH_dep_dzs(self, Z): r'''Calculates the molar departure enthalpy composition derivative (where the mole fractions do not sum to 1). Verified numerically. Useful in solving for enthalpy specifications in newton-type methods, and forms the basis for the molar departure enthalpy mole number derivative and molar partial departure enthalpy. .. math:: \left(\frac{\partial H_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} = P \frac{d}{d x} V{\left(x \right)} + \frac{2 \left(T \frac{\partial}{\partial T} \operatorname{a \alpha}{\left(T,x \right)} - \operatorname{a \alpha}{\left(x \right)}\right) \left(- \delta{\left(x \right)} \frac{d}{d x} \delta{\left(x \right)} + 2 \frac{d}{d x} \epsilon{\left(x \right)}\right) \operatorname{atanh} {\left(\frac{2 V{\left(x \right)} + \delta{\left(x \right)}}{\sqrt{\delta^{2} {\left(x \right)} - 4 \epsilon{\left(x \right)}}} \right)}}{\left(\delta^{2} {\left(x \right)} - 4 \epsilon{\left(x \right)}\right)^{\frac{3}{2}}} + \frac{2 \left(T \frac{\partial}{\partial T} \operatorname{a \alpha} {\left(T,x \right)} - \operatorname{a \alpha}{\left(x \right)}\right) \left(\frac{\left(- \delta{\left(x \right)} \frac{d}{d x} \delta{\left(x \right)} + 2 \frac{d}{d x} \epsilon{\left(x \right)}\right) \left(2 V{\left(x \right)} + \delta{\left(x \right)}\right)}{\left(\delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}\right)^{\frac{3}{2}}} + \frac{2 \frac{d}{d x} V{\left(x \right)} + \frac{d}{d x} \delta{\left(x \right)}} {\sqrt{\delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}}}\right)}{\left( - \frac{\left(2 V{\left(x \right)} + \delta{\left(x \right)}\right)^{2}}{ \delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}} + 1\right) \sqrt{ \delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}}} + \frac{2 \left(T \frac{\partial^{2}}{\partial x\partial T} \operatorname{a \alpha} {\left(T,x \right)} - \frac{d}{d x} \operatorname{a \alpha}{\left(x \right)} \right) \operatorname{atanh}{\left(\frac{2 V{\left(x \right)} + \delta{\left(x \right)}}{\sqrt{\delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}}} \right)}}{\sqrt{\delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}}} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dH_dep_dzs : float Departure enthalpy composition derivatives, [J/mol] Notes ----- The derivation for the derivative is performed as follows using SymPy. The function source code is an optimized variant created with the `cse` SymPy function, and hand optimized further. >>> from sympy import * # doctest:+SKIP >>> P, T, V, R, b, a, delta, epsilon, x = symbols('P, T, V, R, b, a, delta, epsilon, x') # doctest:+SKIP >>> V, delta, epsilon, a_alpha, b = symbols('V, delta, epsilon, a_alpha, b', cls=Function) # doctest:+SKIP >>> H_dep = (P*V(x) - R*T + 2/sqrt(delta(x)**2 - 4*epsilon(x))*(T*Derivative(a_alpha(T, x), T) # doctest:+SKIP ... - a_alpha(x))*atanh((2*V(x)+delta(x))/sqrt(delta(x)**2-4*epsilon(x)))) >>> diff(H_dep, x) # doctest:+SKIP P*Derivative(V(x), x) + 2*(T*Derivative(a \alpha(T, x), T) - a \alpha(x))*(-delta(x)*Derivative(delta(x), x) + 2*Derivative(epsilon(x), x))*atanh((2*V(x) + delta(x))/sqrt(delta(x)**2 - 4*epsilon(x)))/(delta(x)**2 - 4*epsilon(x))**(3/2) + 2*(T*Derivative(a \alpha(T, x), T) - a \alpha(x))*((-delta(x)*Derivative(delta(x), x) + 2*Derivative(epsilon(x), x))*(2*V(x) + delta(x))/(delta(x)**2 - 4*epsilon(x))**(3/2) + (2*Derivative(V(x), x) + Derivative(delta(x), x))/sqrt(delta(x)**2 - 4*epsilon(x)))/((-(2*V(x) + delta(x))**2/(delta(x)**2 - 4*epsilon(x)) + 1)*sqrt(delta(x)**2 - 4*epsilon(x))) + 2*(T*Derivative(a \alpha(T, x), T, x) - Derivative(a \alpha(x), x))*atanh((2*V(x) + delta(x))/sqrt(delta(x)**2 - 4*epsilon(x)))/sqrt(delta(x)**2 - 4*epsilon(x)) ''' P = self.P T = self.T ddelta_dzs = self.ddelta_dzs depsilon_dzs = self.depsilon_dzs da_alpha_dzs = self.da_alpha_dzs da_alpha_dT_dzs = self.da_alpha_dT_dzs dV_dzs = self.dV_dzs(Z) x0 = V = Z*R*T/P x2 = self.delta x3 = x0 + x0 + x2 x4 = self.epsilon x5 = x2*x2 - 4.0*x4 try: x6 = x5**-0.5 except: # VDW has x5 as zero as delta, epsilon = 0 x6 = 1e50 x7 = 2.0*catanh(x3*x6).real x8 = x9 = self.a_alpha x10 = T*self.da_alpha_dT - x8 x13 = x6*x6# 1.0/x5 t0 = x6*x7 t1 = x10*t0*x13 t2 = 2.0*x10*x13/(x13*x3*x3 - 1.0) x3_x13 = x3*x13 dH_dzs = [] for i in range(self.N): x1 = dV_dzs[i] x11 = ddelta_dzs[i] x12 = x11*x2 - 2.0*depsilon_dzs[i] value = (P*x1 - x12*t1 + t2*(x12*x3_x13 - x1 - x1 - x11) + t0*(T*da_alpha_dT_dzs[i] - da_alpha_dzs[i])) dH_dzs.append(value) return dH_dzs def dS_dep_dzs(self, Z): r'''Calculates the molar departure entropy composition derivative (where the mole fractions do not sum to 1). Verified numerically. Useful in solving for entropy specifications in newton-type methods, and forms the basis for the molar departure entropy mole number derivative and molar partial departure entropy. .. math:: \left(\frac{\partial S_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} = \frac{1}{T}\left( \left(\frac{\partial H_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} - \left(\frac{\partial G_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dS_dep_dzs : float Departure entropy composition derivatives, [J/mol/K] Notes ----- ''' dH_dep_dzs = self.dH_dep_dzs(Z) dG_dep_dzs = self.dG_dep_dzs(Z) T_inv = 1.0/self.T return [T_inv*(dH_dep_dzs[i] - dG_dep_dzs[i]) for i in range(self.N)] def dS_dep_dns(self, Z): r'''Calculates the molar departure entropy mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative. .. math:: \left(\frac{\partial S_{dep}}{\partial n_i}\right)_{T, P, n_{i\ne j}} = f\left( \left(\frac{\partial S_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dS_dep_dns : float Departure entropy mole number derivatives, [J/mol^2/K] ''' return dxs_to_dns(self.dS_dep_dzs(Z), self.zs) def dP_dns_Vt(self, phase): # Checked numerically, working. Evaluated at constant temperature and total volume. r'''from sympy import * Vt, P, T, R, n1, n2, n3, no = symbols('Vt, P, T, R, n1, n2, n3, no') # doctest:+SKIP n, P, V, a_alpha, delta, epsilon, b = symbols('n, P, V, a\ \\alpha, delta, epsilon, b', cls=Function) # doctest:+SKIP da_alpha_dT, d2a_alpha_dT2 = symbols('da_alpha_dT, d2a_alpha_dT2', cls=Function) # doctest:+SKIP n = no + n1 + n2 + n3 P = R*T/(Vt/n-b(n1, n2, n3)) - a_alpha(T, n1, n2, n3)/((Vt/n)**2 + delta(n1, n2, n3)*(Vt/n)+epsilon(n1, n2, n3)) V = Vt/n cse(diff(P, n1)) ''' if phase == 'g': Vt = self.V_g else: Vt = self.V_l T = self.T b = self.b a_alpha = self.a_alpha epsilon = self.epsilon Vt2 = Vt*Vt delta = self.delta x9 = Vt2 + Vt*delta + epsilon depsilon_dns = self.depsilon_dns ddelta_dns = self.ddelta_dns db_dns = self.db_dns da_alpha_dns = self.da_alpha_dns t1 = R*T*1.0/((Vt - b)*(Vt - b)) t2 = 1.0/x9 t3 = a_alpha*t2*t2 t4 = t1*Vt -t3*(Vt*delta + Vt2 + Vt2) dP_dns_Vt = [] for i in range(self.N): v = (t4 + t1*db_dns[i] + t3*(Vt*ddelta_dns[i] + depsilon_dns[i]) - t2*da_alpha_dns[i]) dP_dns_Vt.append(v) return dP_dns_Vt def d2P_dninjs_Vt(self, phase): if phase == 'g': Vt = self.V_g else: Vt = self.V_l T, N = self.T, self.N b = self.b a_alpha = self.a_alpha epsilon = self.epsilon depsilon_dns = self.depsilon_dns ddelta_dns = self.ddelta_dns db_dns = self.db_dns da_alpha_dns = self.da_alpha_dns d2delta_dninjs = self.d2delta_dninjs d2epsilon_dninjs = self.d2epsilon_dninjs d2bs = self.d2b_dninjs d2a_alpha_dninjs = self.d2a_alpha_dninjs x0 = self.a_alpha x1 = self.epsilon x2 = Vt*Vt x5 = self.delta x7 = x1 + x2 + x5*Vt x7_inv = 1.0/x7 x8 = self.b x9 = Vt - x8 x11 = Vt + Vt x12 = R*T x13 = Vt x14 = x7_inv*x7_inv x16 = x2 + x2 + x13*x5 t1 = x0*x14 x9_inv = 1.0/x9 x9_inv2 = x9_inv*x9_inv x9_inv3 = x9_inv*x9_inv2 t2 = t1*(x11*x5 + 6.0*x2) - x12*x11*x9_inv2 t3 = x12*x9_inv2 t4 = 2.0*x12*x9_inv3 t5 = 2.0*x0*x7_inv*x7_inv*x7_inv hess = [[0.0]*N for _ in range(N)] for i in range(N): x15 = ddelta_dns[i] x17 = -x15*Vt + x16 - depsilon_dns[i] t50 = -x13*x15 t51 = t5*x17 t52 = t4*(x13 + db_dns[i]) t53 = x14*x17 t54 = x14*da_alpha_dns[i] t55 = (t51 + t54) iadd = t1*t50 + t52*x13 - x16*t55 for j in range(i+1): x18 = ddelta_dns[j] x19 = x18*Vt + depsilon_dns[j] v = (t2 + iadd + t1*(Vt*d2delta_dninjs[i][j] + d2epsilon_dninjs[i][j] - x13*x18) + t52*db_dns[j] - t53*da_alpha_dns[j] + t55*x19 + t3*d2bs[i][j] - x7_inv*d2a_alpha_dninjs[i][j]) hess[i][j] = hess[j][i] = v return hess def d3P_dninjnks_Vt(self, phase): if phase == 'g': Vt = self.V_g else: Vt = self.V_l T, N = self.T, self.N b = self.b a_alpha = self.a_alpha epsilon = self.epsilon depsilon_dns = self.depsilon_dns ddelta_dns = self.ddelta_dns db_dns = self.db_dns da_alpha_dns = self.da_alpha_dns d2delta_dninjs = self.d2delta_dninjs d2epsilon_dninjs = self.d2epsilon_dninjs d2bs = self.d2b_dninjs d2a_alpha_dninjs = self.d2a_alpha_dninjs d3epsilon_dninjnks = self.d3epsilon_dninjnks d3delta_dninjnks = self.d3delta_dninjnks d3a_alpha_dninjnks = self.d3a_alpha_dninjnks d3b_dninjnks = self.d3b_dninjnks mat = [[[0.0]*N for _ in range(N)] for _ in range(N)] for i in range(N): for j in range(N): for k in range(N): x0 = self.b x1 = 1.0 x2 = Vt/x1 x3 = -x0 + x2 x4 = 6/x1**4 x5 = Vt*x4 x6 = R*T x7 = self.a_alpha x8 = self.epsilon x9 = Vt**2 x10 = x1**(-2) x11 = self.delta x12 = x10*x9 + x11*x2 + x8 x13 = 2/x1**3 x14 = Vt*x13 x15 = Vt*x10 x16 = x6*(x15 + db_dns[k]) x17 = 2/x3**3 x18 = x15 + db_dns[j] x19 = x17*x6 x20 = x15 + db_dns[i] x21 = x12**(-2) x22 = ddelta_dns[i] x23 = x11*x15 + x13*x9 x24 = -x2*x22 + x23 - depsilon_dns[i] x25 = ddelta_dns[j] x26 = -x2*x25 + x23 - depsilon_dns[j] x27 = ddelta_dns[k] x28 = -x2*x27 + x23 - depsilon_dns[j] x29 = da_alpha_dns[k] x30 = d2delta_dninjs[i][j] x31 = -x15*x25 x32 = x4*x9 x33 = x11*x14 x34 = -x15*x22 + x32 + x33 x35 = x2*x30 + x31 + x34 + d2epsilon_dninjs[i][j] x36 = da_alpha_dns[j] x37 = d2delta_dninjs[i][k] x38 = -x15*x27 x39 = x2*x37 + x34 + x38 + d2epsilon_dninjs[i][k] x40 = da_alpha_dns[i] x41 = d2delta_dninjs[j][k] x42 = x2*x41 + x31 + x32 + x33 + x38 + d2epsilon_dninjs[j][k] x43 = 2/x12**3 x44 = x24*x26 x45 = x28*x43 x46 = x43*x7 v = (-x16*x17*(x14 - d2bs[i][j]) + 6*x16*x18*x20/x3**4 - x18*x19*(x14 -d2bs[i][k]) - x19*x20*(x14 - d2bs[j][k]) - x21*x24*d2a_alpha_dninjs[j][k] - x21*x26*d2a_alpha_dninjs[i][k] - x21*x28*d2a_alpha_dninjs[i][j] + x21*x29*x35 + x21*x36*x39 + x21*x40*x42 - x21*x7*(x11*x5 - x14*x22 - x14*x25 - x14*x27 + x15*x30 + x15*x37 + x15*x41 - x2*d3delta_dninjnks[i][j][k] - d3epsilon_dninjnks[i][j][k] + 24*x9/x1**5) - x24*x36*x45 + x24*x42*x46 + x26*x39*x46 - x26*x40*x45 - x29*x43*x44 + x35*x45*x7 + x6*(x5 + d3b_dninjnks[i][j][k])/x3**2 - d3a_alpha_dninjnks[i][j][k]/x12 - 6*x28*x44*x7/x12**4) mat[i][j][k] = v return mat def dH_dep_dns(self, Z): r'''Calculates the molar departure enthalpy mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative. .. math:: \left(\frac{\partial H_{dep}}{\partial n_i}\right)_{T, P, n_{i\ne j}} = f\left( \left(\frac{\partial H_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dH_dep_dns : float Departure enthalpy mole number derivatives, [J/mol^2] ''' return dxs_to_dns(self.dH_dep_dzs(Z), self.zs) def dnH_dep_dns(self, Z): r'''Calculates the partial molar departure enthalpy. No specific formula is implemented for this property - it is calculated from the mole fraction derivative. .. math:: \left(\frac{\partial n H_{dep}}{\partial n_i}\right)_{T, P, n_{i\ne j}} = f\left( \left(\frac{\partial H_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dnH_dep_dns : float Partial molar departure enthalpies of the phase, [J/mol] ''' try: if Z == self.Z_l: F = self.H_dep_l else: F = self.H_dep_g except: F = self.H_dep_g return dxs_to_dn_partials(self.dH_dep_dzs(Z), self.zs, F) def _G_dep_lnphi_d_helper(self, Z, dbs, depsilons, ddelta, dVs, da_alphas, G=True): return G_dep_lnphi_d_helper(self.T, self.P, self.b, self.delta, self.epsilon, self.a_alpha, self.N, Z, dbs, depsilons, ddelta, dVs, da_alphas, G) def dlnphi_dzs(self, Z): r'''Calculates the mixture log *fugacity coefficient* mole fraction derivatives (where the mole fractions do not sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative of Gibbs free energy. .. math:: \left(\frac{\partial \ln \phi }{\partial x_i}\right)_{T, P, x_{i\ne j}} = \frac{1}{RT}\left( \left(\frac{\partial G_{dep}} {\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dlnphi_dzs : float Mixture log fugacity coefficient mole fraction derivatives, [-] ''' return self._G_dep_lnphi_d_helper(Z, dbs=self.db_dzs, depsilons=self.depsilon_dzs, ddelta=self.ddelta_dzs, dVs=self.dV_dzs(Z), da_alphas=self.da_alpha_dzs, G=False) def dlnphi_dns(self, Z): r'''Calculates the mixture log *fugacity coefficient* mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative of Gibbs free energy. .. math:: \left(\frac{\partial \ln \phi }{\partial n_i}\right)_{T, P, n_{i\ne j}} = f\left( \left(\frac{\partial G_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) This property can be converted into a partial molar property to obtain the individual fugacity coefficients. Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dlnphi_dns : float Mixture log fugacity coefficient mole number derivatives, [1/mol] ''' return self._G_dep_lnphi_d_helper(Z, dbs=self.db_dns, depsilons=self.depsilon_dns, ddelta=self.ddelta_dns, dVs=self.dV_dns(Z), da_alphas=self.da_alpha_dns, G=False) def dG_dep_dzs(self, Z): r'''Calculates the molar departure Gibbs energy composition derivative (where the mole fractions do not sum to 1). Verified numerically. Useful in solving for gibbs minimization calculations or for solving for the true critical point. Also forms the basis for the molar departure Gibbs energy mole number derivative and molar partial departure Gibbs energy. .. math:: \left(\frac{\partial G_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} = P \frac{d}{d x} V{\left(x \right)} - \frac{R T \left(\frac{d}{d x} V{\left(x \right)} - \frac{d}{d x} b{\left(x \right)}\right)}{ V{\left(x \right)} - b{\left(x \right)}} - \frac{2 \left(- \delta{ \left(x \right)} \frac{d}{d x} \delta{\left(x \right)} + 2 \frac{d} {d x} \epsilon{\left(x \right)}\right) \operatorname{a \alpha}{ \left(x \right)} \operatorname{atanh}{\left(\frac{2 V{\left(x \right)}}{\sqrt{\delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}}} + \frac{\delta{\left(x \right)}}{\sqrt{\delta^{2}{\left( x \right)} - 4 \epsilon{\left(x \right)}}} \right)}}{\left( \delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}\right)^{ \frac{3}{2}}} - \frac{2 \operatorname{atanh}{\left(\frac{2 V{\left( x \right)}}{\sqrt{\delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}}} + \frac{\delta{\left(x \right)}}{\sqrt{\delta^{2}{\left( x \right)} - 4 \epsilon{\left(x \right)}}} \right)} \frac{d}{d x} \operatorname{a \alpha}{\left(x \right)}}{\sqrt{\delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}}} - \frac{2 \left(\frac{2 \left(- \delta{\left(x \right)} \frac{d}{d x} \delta{\left(x \right)} + 2 \frac{d}{d x} \epsilon{\left(x \right)}\right) V{\left(x \right)}}{\left(\delta^{2}{\left(x \right)} - 4 \epsilon{ \left(x \right)}\right)^{\frac{3}{2}}} + \frac{\left(- \delta{\left (x \right)} \frac{d}{d x} \delta{\left(x \right)} + 2 \frac{d}{d x} \epsilon{\left(x \right)}\right) \delta{\left(x \right)}}{\left( \delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}\right)^{ \frac{3}{2}}} + \frac{2 \frac{d}{d x} V{\left(x \right)}}{\sqrt{ \delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}}} + \frac{\frac{d}{d x} \delta{\left(x \right)}}{\sqrt{\delta^{2}{ \left(x \right)} - 4 \epsilon{\left(x \right)}}}\right) \operatorname{a \alpha}{\left(x \right)}}{\left(1 - \left(\frac{2 V{\left(x \right)}}{\sqrt{\delta^{2}{\left(x \right)} - 4 \epsilon{ \left(x \right)}}} + \frac{\delta{\left(x \right)}}{\sqrt{ \delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}}}\right )^{2}\right) \sqrt{\delta^{2}{\left(x \right)} - 4 \epsilon{\left(x \right)}}} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dG_dep_dzs : float Departure Gibbs free energy composition derivatives, [J/mol] Notes ----- The derivation for the derivative is performed as follows using SymPy. The function source code is an optimized variant created with the `cse` SymPy function, and hand optimized further. >>> from sympy import * # doctest:+SKIP >>> P, T, R, x = symbols('P, T, R, x') # doctest:+SKIP >>> a_alpha, a, delta, epsilon, V, b, da_alpha_dT = symbols('a\ \\alpha, a, delta, epsilon, V, b, da_alpha_dT', cls=Function) # doctest:+SKIP >>> S_dep = R*log(P*V(x)/(R*T)) + R*log(V(x)-b(x))+2*da_alpha_dT(x)*atanh((2*V(x)+delta(x))/sqrt(delta(x)**2-4*epsilon(x)))/sqrt(delta(x)**2-4*epsilon(x))-R*log(V(x)) # doctest:+SKIP >>> H_dep = P*V(x) - R*T + 2*atanh((2*V(x)+delta(x))/sqrt(delta(x)**2-4*epsilon(x)))*(da_alpha_dT(x)*T-a_alpha(x))/sqrt(delta(x)**2-4*epsilon(x)) # doctest:+SKIP >>> G_dep = simplify(H_dep - T*S_dep) # doctest:+SKIP >>> diff(G_dep, x) # doctest:+SKIP P*Derivative(V(x), x) - R*T*(Derivative(V(x), x) - Derivative(b(x), x))/(V(x) - b(x)) - 2*(-delta(x)*Derivative(delta(x), x) + 2*Derivative(epsilon(x), x))*a \alpha(x)*atanh(2*V(x)/sqrt(delta(x)**2 - 4*epsilon(x)) + delta(x)/sqrt(delta(x)**2 - 4*epsilon(x)))/(delta(x)**2 - 4*epsilon(x))**(3/2) - 2*atanh(2*V(x)/sqrt(delta(x)**2 - 4*epsilon(x)) + delta(x)/sqrt(delta(x)**2 - 4*epsilon(x)))*Derivative(a \alpha(x), x)/sqrt(delta(x)**2 - 4*epsilon(x)) - 2*(2*(-delta(x)*Derivative(delta(x), x) + 2*Derivative(epsilon(x), x))*V(x)/(delta(x)**2 - 4*epsilon(x))**(3/2) + (-delta(x)*Derivative(delta(x), x) + 2*Derivative(epsilon(x), x))*delta(x)/(delta(x)**2 - 4*epsilon(x))**(3/2) + 2*Derivative(V(x), x)/sqrt(delta(x)**2 - 4*epsilon(x)) + Derivative(delta(x), x)/sqrt(delta(x)**2 - 4*epsilon(x)))*a \alpha(x)/((1 - (2*V(x)/sqrt(delta(x)**2 - 4*epsilon(x)) + delta(x)/sqrt(delta(x)**2 - 4*epsilon(x)))**2)*sqrt(delta(x)**2 - 4*epsilon(x))) ''' return self._G_dep_lnphi_d_helper(Z, dbs=self.db_dzs, depsilons=self.depsilon_dzs, ddelta=self.ddelta_dzs, dVs=self.dV_dzs(Z), da_alphas=self.da_alpha_dzs, G=True) def dG_dep_dns(self, Z): r'''Calculates the molar departure Gibbs energy mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative. .. math:: \left(\frac{\partial G_{dep}}{\partial n_i}\right)_{T, P, n_{i\ne j}} = f\left( \left(\frac{\partial G_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Apart from the ideal term, this is the formulation for chemical potential. Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dG_dep_dns : float Departure Gibbs energy mole number derivatives, [J/mol^2] ''' return self._G_dep_lnphi_d_helper(Z, dbs=self.db_dns, depsilons=self.depsilon_dns, ddelta=self.ddelta_dns, dVs=self.dV_dns(Z), da_alphas=self.da_alpha_dns, G=True) def dnG_dep_dns(self, Z): r'''Calculates the partial molar departure Gibbs energy. No specific formula is implemented for this property - it is calculated from the mole fraction derivative. .. math:: \left(\frac{\partial n G_{dep}}{\partial n_i}\right)_{T, P, n_{i\ne j}} = f\left( \left(\frac{\partial G_{dep}}{\partial x_i}\right)_{T, P, x_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dnG_dep_dns : float Partial molar departure Gibbs energy of the phase, [J/mol] ''' try: if Z == self.Z_l: F = self.G_dep_l else: F = self.G_dep_g except: F = self.G_dep_g dG_dns = self.dG_dep_dns(Z) return dns_to_dn_partials(dG_dns, F) def fugacity_coefficients(self, Z): r'''Generic formula for calculating log fugacity coefficients for each species in a mixture. Verified numerically. Applicable to all cubic equations of state which can be cast in the form used here. Normally this routine is slower than EOS-specific ones, as it does not make assumptions that certain parameters are zero or equal to other parameters. .. math:: \left(\frac{\partial n \ln \phi}{\partial n_i} \right)_{n_{k \ne i}} = \ln \phi _i = \ln \phi + n \left(\frac{\partial \ln \phi}{\partial n_i} \right)_{n_{k\ne i}} .. math:: \left(\frac{\partial \ln \phi }{\partial n_i}\right)_{T, P, n_{i\ne j}} = \frac{1}{RT}\left( \left(\frac{\partial G_{dep}} {\partial n_i}\right)_{T, P, n_{i\ne j}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- log_phis : float Log fugacity coefficient for each species, [-] ''' zs = self.zs try: if Z == self.Z_l: F = self.phi_l else: F = self.phi_g except: F = self.phi_g # This conversion seems numerically safe anyway try: logF = log(F) except: logF = -690.7755278982137 log_phis = dns_to_dn_partials(self.dlnphi_dns(Z), logF) return log_phis if self.scalar else array(log_phis) def _d2_G_dep_lnphi_d2_helper(self, V, d_Vs, d2Vs, dbs, d2bs, d_epsilons, d2_epsilons, d_deltas, d2_deltas, da_alphas, d2a_alphas, G=True): T, P = self.T, self.P N = self.N RT = T*R RT_inv = 1.0/RT hess = [] for i in range(N): row = [] for j in range(N): # x1: i # x2: j x0 = V# V(x1, x2) x3 = d2Vs[i][j] #Derivative(x0, x1, x2) x4 = self.b#b(x1, x2) x5 = x0 - x4 x6 = R*T x7 = d_Vs[i] #Derivative(x0, x1) x8 = d_Vs[j] #Derivative(x0, x2) x9 = self.delta#delta(x1, x2) x10 = self.epsilon#epsilon(x1, x2) x11 = -4*x10 + x9**2 if x11 == 0.0: x11 = 1e-100 x12 = 1/sqrt(x11) x13 = self.a_alpha#alpha(x1, x2) x14 = 2*x0 x15 = x14 + x9 x16 = catanh(x12*x15).real x17 = 2*x16 x18 = d_deltas[i] #Derivative(x9, x1) x19 = x18*x9 - 2*d_epsilons[i]#Derivative(x10, x1) x20 = da_alphas[j]#Derivative(x13, x2) x21 = x17/x11**(3/2) x22 = d_deltas[j]#Derivative(x9, x2) x23 = x22*x9 - 2*d_epsilons[j]#Derivative(x10, x2) x24 = da_alphas[i]#Derivative(x13, x1) x25 = d2_deltas[i][j]#Derivative(x9, x1, x2) x26 = x18*x22 + x25*x9 - 2*d2_epsilons[i][j]#Derivative(x10, x1, x2) x27 = x13*x23 x28 = 2*x7 x29 = 1/x11 x30 = x29*x9 x31 = x19*x29 x32 = x14*x31 - x18 + x19*x30 - x28 x33 = x15**2*x29 - 1 x34 = 2/x33 x35 = x29*x34 x36 = 2*x8 x37 = x23*x29 x38 = x14*x37 - x22 + x23*x30 - x36 x39 = x11**(-2) x40 = x19*x39 x41 = x13*x38 x42 = x32*x39 x43 = x23*x40 v = (P*x3 - x12*x17*d2a_alphas[i][j] + x13*x21*x26 - x13*x35*(-6*x0*x43 + x14*x26*x29 + x18*x37 + x22*x31 - x25 + x26*x30 + x28*x37 - 2*x3 + x31*x36 - 3*x43*x9) - 4*x15*x41*x42/x33**2 + x19*x20*x21 - x20*x32*x35 + x21*x23*x24 - x24*x35*x38 + x27*x34*x42 + x34*x40*x41 - x6*(x3 - d2bs[i][j])/x5 + x6*(x7 - dbs[i])*(x8 - dbs[j])/x5**2 - 6*x16*x19*x27/x11**(5/2)) if not G: v *= RT_inv row.append(v) hess.append(row) return hess def d2lnphi_dzizjs(self, Z): r'''Calculates the mixture log *fugacity coefficient* second mole fraction derivatives (where the mole fractions do not sum to 1). No specific formula is implemented for this property - it is calculated from the second mole fraction derivative of Gibbs free energy. .. math:: \left(\frac{\partial^2 \ln \phi }{\partial x_i\partial x_j}\right)_{T, P, x_{i,j\ne k}} = \frac{1}{RT}\left( \left(\frac{\partial^2 G_{dep}} {\partial x_j \partial x_i}\right)_{T, P, x_{i,j\ne k}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- d2lnphi_dzizjs : float Mixture log fugacity coefficient second mole fraction derivatives, [-] ''' V = Z*self.T*R/self.P dV_dzs = self.dV_dzs(Z) d2Vs = self.d2V_dzizjs(Z) depsilon_dzs = self.depsilon_dzs d2epsilon_dzizjs = self.d2epsilon_dzizjs ddelta_dzs = self.ddelta_dzs d2delta_dzizjs = self.d2delta_dzizjs db_dzs = self.db_dzs d2bs = self.d2b_dzizjs da_alpha_dzs = self.da_alpha_dzs d2a_alpha_dzizjs = self.d2a_alpha_dzizjs return self._d2_G_dep_lnphi_d2_helper(V=V, d_Vs=dV_dzs, d2Vs=d2Vs, dbs=db_dzs, d2bs=d2bs, d_epsilons=depsilon_dzs, d2_epsilons=d2epsilon_dzizjs, d_deltas=ddelta_dzs, d2_deltas=d2delta_dzizjs, da_alphas=da_alpha_dzs, d2a_alphas=d2a_alpha_dzizjs, G=False) def d2lnphi_dninjs(self, Z): r'''Calculates the mixture log *fugacity coefficient* second mole number derivatives (where the mole fraction sum to 1). No specific formula is implemented for this property - it is calculated from the second mole fraction derivative of Gibbs free energy. .. math:: \left(\frac{\partial^2 \ln \phi }{\partial n_i\partial n_j}\right)_{T, P, n_{i,j\ne k}} f\left( \left(\frac{\partial^2 G_{dep}} {\partial x_j \partial x_i}\right)_{T, P, x_{i,j\ne k}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- d2lnphi_dninjs : float Mixture log fugacity coefficient second mole number derivatives, [-] ''' V = Z*self.T*R/self.P dV_dns = self.dV_dns(Z) d2Vs = self.d2V_dninjs(Z) depsilon_dns = self.depsilon_dns d2epsilon_dninjs = self.d2epsilon_dninjs ddelta_dns = self.ddelta_dns d2delta_dninjs = self.d2delta_dninjs db_dns = self.db_dns d2bs = self.d2b_dninjs da_alpha_dns = self.da_alpha_dns d2a_alpha_dninjs = self.d2a_alpha_dninjs return self._d2_G_dep_lnphi_d2_helper(V=V, d2Vs=d2Vs, d_Vs=dV_dns, dbs=db_dns, d2bs=d2bs, d_epsilons=depsilon_dns, d2_epsilons=d2epsilon_dninjs, d_deltas=ddelta_dns, d2_deltas=d2delta_dninjs, da_alphas=da_alpha_dns, d2a_alphas=d2a_alpha_dninjs, G=False) def d2G_dep_dzizjs(self, Z): r'''Calculates the molar departure Gibbs energy second composition derivative (where the mole fractions do not sum to 1). Verified numerically. Useful in solving for gibbs minimization calculations or for solving for the true critical point. Also forms the basis for the molar departure Gibbs energy mole second number derivative. .. math:: \left(\frac{\partial^2 G_{dep}}{\partial x_j \partial x_i}\right)_{T, P, x_{i,j\ne k}} = \text{run SymPy code to obtain - very long!} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- d2G_dep_dzizjs : float Departure Gibbs free energy second composition derivatives, [J/mol] Notes ----- The derivation for the derivative is performed as follows using SymPy. The function source code is an optimized variant created with the `cse` SymPy function, and hand optimized further. >>> from sympy import * # doctest:+SKIP >>> P, T, R, x1, x2 = symbols('P, T, R, x1, x2') # doctest:+SKIP >>> a_alpha, delta, epsilon, V, b = symbols('a\ \\alpha, delta, epsilon, V, b', cls=Function) # doctest:+SKIP >>> da_alpha_dT, d2a_alpha_dT2 = symbols('da_alpha_dT, d2a_alpha_dT2', cls=Function) # doctest:+SKIP >>> S_dep = R*log(P*V(x1, x2)/(R*T)) + R*log(V(x1, x2)-b(x1, x2))+2*da_alpha_dT(x1, x2)*atanh((2*V(x1, x2)+delta(x1, x2))/sqrt(delta(x1, x2)**2-4*epsilon(x1, x2)))/sqrt(delta(x1, x2)**2-4*epsilon(x1, x2))-R*log(V(x1, x2)) # doctest:+SKIP >>> H_dep = P*V(x1, x2) - R*T + 2*atanh((2*V(x1, x2)+delta(x1, x2))/sqrt(delta(x1, x2)**2-4*epsilon(x1, x2)))*(da_alpha_dT(x1, x2)*T-a_alpha(x1, x2))/sqrt(delta(x1, x2)**2-4*epsilon(x1, x2)) # doctest:+SKIP >>> G_dep = simplify(H_dep - T*S_dep) # doctest:+SKIP >>> diff(G_dep, x1, x2) # doctest:+SKIP ''' V = Z*self.T*R/self.P dV_dzs = self.dV_dzs(Z) d2Vs = self.d2V_dzizjs(Z) depsilon_dzs = self.depsilon_dzs d2epsilon_dzizjs = self.d2epsilon_dzizjs ddelta_dzs = self.ddelta_dzs d2delta_dzizjs = self.d2delta_dzizjs db_dzs = self.db_dzs d2bs = self.d2b_dzizjs da_alpha_dzs = self.da_alpha_dzs d2a_alpha_dzizjs = self.d2a_alpha_dzizjs return self._d2_G_dep_lnphi_d2_helper(V=V, d_Vs=dV_dzs, d2Vs=d2Vs, dbs=db_dzs, d2bs=d2bs, d_epsilons=depsilon_dzs, d2_epsilons=d2epsilon_dzizjs, d_deltas=ddelta_dzs, d2_deltas=d2delta_dzizjs, da_alphas=da_alpha_dzs, d2a_alphas=d2a_alpha_dzizjs, G=True) def dlnphis_dns(self, Z): r'''Generic formula for calculating the mole number derivaitves of log fugacity coefficients for each species in a mixture. Verified numerically. Applicable to all cubic equations of state which can be cast in the form used here. .. math:: \left(\frac{\partial \ln \phi_i}{\partial n_i}\right)_{P, n_{j \ne i}} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dlnphis_dns : list[list[float]] Mole number derivatives of log fugacity coefficient for each species, [-] Notes ----- ''' dns = self.dlnphi_dns(Z) d2ns = self.d2lnphi_dninjs(Z) return d2ns_to_dn2_partials(d2ns, dns) def dlnfugacities_dns(self, phase): r'''Generic formula for calculating the mole number derivaitves of log fugacities for each species in a mixture. Verified numerically. Applicable to all cubic equations of state which can be cast in the form used here. .. math:: \left(\frac{\partial \ln f_i}{\partial n_i}\right)_{P, n_{j \ne i}} Parameters ---------- phase : str One of 'l' or 'g', [-] Returns ------- dlnfugacities_dns : list[list[float]] Mole number derivatives of log fugacities for each species, [-] Notes ----- ''' zs, N = self.zs, self.N if phase == 'l': Z = self.Z_l try: fugacities = self.fugacities_l except AttributeError: self.fugacities() fugacities = self.fugacities_l else: Z = self.Z_g try: fugacities = self.fugacities_g except AttributeError: self.fugacities() fugacities = self.fugacities_g dlnfugacities_dns = [list(i) for i in self.dfugacities_dns(phase)] fugacities_inv = [1.0/fi for fi in fugacities] for i in range(N): r = dlnfugacities_dns[i] for j in range(N): r[j]*= fugacities_inv[i] return dlnfugacities_dns def dfugacities_dns(self, phase): r'''Generic formula for calculating the mole number derivaitves of fugacities for each species in a mixture. Verified numerically. Applicable to all cubic equations of state which can be cast in the form used here. .. math:: \left(\frac{\partial f_i}{\partial n_i}\right)_{P, n_{j \ne i}} Parameters ---------- phase : str One of 'l' or 'g', [-] Returns ------- dfugacities_dns : list[list[float]] Mole number derivatives of fugacities for each species, [-] Notes ----- ''' ''' from sympy import * phifun1, phifun2 = symbols('phifun1, phifun2', cls=Function) n1, n2, P = symbols('n1, n2, P') x1 = n1/(n1+n2) x2 = n2/(n1+n2) to_diff = x2*P*exp(phifun1(n1)) diff(to_diff, n1).subs({n1+n1: 1}) ''' zs = self.zs if phase == 'l': Z = self.Z_l try: phis = self.phis_l except AttributeError: self.fugacities() phis = self.phis_l else: Z = self.Z_g try: phis = self.phis_g except AttributeError: self.fugacities() phis = self.phis_g dlnphis_dns = self.dlnphis_dns(Z) P = self.P N = self.N matrix = [] for i in range(N): phi_P = P*phis[i] ziPphi = phi_P*zs[i] r = dlnphis_dns[i] # row = [ziPphi*(r[j] - 1.0) for j in range(N)] row = [ziPphi*(dlnphis_dns[j][i] - 1.0) for j in range(N)] row[i] += phi_P matrix.append(row) return matrix def d2G_dep_dninjs(self, Z): r'''Calculates the molar departure Gibbs energy mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative. .. math:: \left(\frac{\partial^2 G_{dep}}{\partial n_j \partial n_i}\right)_{T, P, n_{i,j\ne k}} = f\left( \left(\frac{\partial^2 G_{dep}}{\partial x_j \partial x_i}\right)_{T, P, x_{i,j\ne k}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- d2G_dep_dninjs : float Departure Gibbs energy second mole number derivatives, [J/mol^3] ''' V = Z*self.T*R/self.P dV_dns = self.dV_dns(Z) d2Vs = self.d2V_dninjs(Z) depsilon_dns = self.depsilon_dns d2epsilon_dninjs = self.d2epsilon_dninjs ddelta_dns = self.ddelta_dns d2delta_dninjs = self.d2delta_dninjs db_dns = self.db_dns d2bs = self.d2b_dninjs da_alpha_dns = self.da_alpha_dns d2a_alpha_dninjs = self.d2a_alpha_dninjs return self._d2_G_dep_lnphi_d2_helper(V=V, d2Vs=d2Vs, d_Vs=dV_dns, dbs=db_dns, d2bs=d2bs, d_epsilons=depsilon_dns, d2_epsilons=d2epsilon_dninjs, d_deltas=ddelta_dns, d2_deltas=d2delta_dninjs, da_alphas=da_alpha_dns, d2a_alphas=d2a_alpha_dninjs, G=True) def _d2_A_dep_d2_helper(self, V, d_Vs, d2Vs, dbs, d2bs, d_epsilons, d2_epsilons, d_deltas, d2_deltas, da_alphas, d2a_alphas): # pass r'''from sympy import * # doctest:+SKIP P, T, R, x1, x2 = symbols('P, T, R, x1, x2') # doctest:+SKIP a_alpha, delta, epsilon, V, b = symbols('a\ \\alpha, delta, epsilon, V, b', cls=Function) # doctest:+SKIP da_alpha_dT, d2a_alpha_dT2 = symbols('da_alpha_dT, d2a_alpha_dT2', cls=Function) # doctest:+SKIP S_dep = R*log(P*V(x1, x2)/(R*T)) + R*log(V(x1, x2)-b(x1, x2))+2*da_alpha_dT(x1, x2)*atanh((2*V(x1, x2)+delta(x1, x2))/sqrt(delta(x1, x2)**2-4*epsilon(x1, x2)))/sqrt(delta(x1, x2)**2-4*epsilon(x1, x2))-R*log(V(x1, x2)) # doctest:+SKIP H_dep = P*V(x1, x2) - R*T + 2*atanh((2*V(x1, x2)+delta(x1, x2))/sqrt(delta(x1, x2)**2-4*epsilon(x1, x2)))*(da_alpha_dT(x1, x2)*T-a_alpha(x1, x2))/sqrt(delta(x1, x2)**2-4*epsilon(x1, x2)) # doctest:+SKIP G_dep = simplify(H_dep - T*S_dep) # doctest:+SKIP V_dep = V(x1, x2) - R*T/P U_dep = H_dep - P*V_dep A_dep = simplify(U_dep - T*S_dep) ''' T, P = self.T, self.P b = self.b N = self.N RT = T*R hess = [] for i in range(N): row = [] for j in range(N): x0 = V x3 = b x4 = x0 - x3 x5 = d2Vs[i][j] x6 = R*T x7 = d_Vs[i] x8 = d_Vs[j] x9 = self.delta x10 = self.epsilon x11 = -4*x10 + x9**2 x12 = 1/sqrt(x11) x13 = self.a_alpha x14 = 2*x0 x15 = x14 + x9 x16 = catanh(x12*x15).real x17 = 2*x16 x18 = d_deltas[i] x19 = x18*x9 - 2*d_epsilons[i] x20 = da_alphas[j] x21 = x17/x11**(3/2) x22 = d_deltas[j] x23 = x22*x9 - 2*d_epsilons[j] x24 = da_alphas[i] x25 = d2_deltas[i][j] x26 = x18*x22 + x25*x9 - 2*d2_epsilons[i][j] x27 = x13*x23 x28 = 2*x7 x29 = 1/x11 x30 = x29*x9 x31 = x19*x29 x32 = x14*x31 - x18 + x19*x30 - x28 x33 = x15**2*x29 - 1 x34 = 2/x33 x35 = x29*x34 x36 = 2*x8 x37 = x23*x29 x38 = x14*x37 - x22 + x23*x30 - x36 x39 = x11**(-2) x40 = x19*x39 x41 = x13*x38 x42 = x32*x39 x43 = x23*x40 v = (-x12*x17*d2a_alphas[i][j] + x13*x21*x26 - x13*x35*(-6*x0*x43 + x14*x26*x29 + x18*x37 + x22*x31 - x25 + x26*x30 + x28*x37 + x31*x36 - 3*x43*x9 - 2*x5) - 4*x15*x41*x42/x33**2 + x19*x20*x21 - x20*x32*x35 + x21*x23*x24 - x24*x35*x38 + x27*x34*x42 + x34*x40*x41 - x6*(x5 - d2bs[i][j])/x4 + x6*(x7 - dbs[i])*(x8 - dbs[j])/x4**2 - 6*x16*x19*x27/x11**(5/2.)) row.append(v) hess.append(row) return hess def d2A_dep_dninjs(self, Z): V = Z*self.T*R/self.P dV_dns = self.dV_dns(Z) d2Vs = self.d2V_dninjs(Z) depsilon_dns = self.depsilon_dns d2epsilon_dninjs = self.d2epsilon_dninjs ddelta_dns = self.ddelta_dns d2delta_dninjs = self.d2delta_dninjs db_dns = self.db_dns d2bs = self.d2b_dninjs da_alpha_dns = self.da_alpha_dns d2a_alpha_dninjs = self.d2a_alpha_dninjs return self._d2_A_dep_d2_helper(V=V, d2Vs=d2Vs, d_Vs=dV_dns, dbs=db_dns, d2bs=d2bs, d_epsilons=depsilon_dns, d2_epsilons=d2epsilon_dninjs, d_deltas=ddelta_dns, d2_deltas=d2delta_dninjs, da_alphas=da_alpha_dns, d2a_alphas=d2a_alpha_dninjs) def dA_dep_dns_Vt(self, phase): # pass r''' from sympy import * Vt, P, T, R, n1, n2, n3 = symbols('Vt, P, T, R, n1, n2, n3') # doctest:+SKIP P, V, a_alpha, delta, epsilon, b = symbols('P, V, a\ \\alpha, delta, epsilon, b', cls=Function) # doctest:+SKIP da_alpha_dT, d2a_alpha_dT2 = symbols('da_alpha_dT, d2a_alpha_dT2', cls=Function) # doctest:+SKIP ns = [n1, n2, n3] S_dep = R*log(P(n1, n2, n3)*V(n1, n2, n3)/(R*T)) + R*log(V(n1, n2, n3)-b(n1, n2, n3))+2*da_alpha_dT(n1, n2, n3)*atanh((2*V(n1, n2, n3)+delta(n1, n2, n3))/sqrt(delta(n1, n2, n3)**2-4*epsilon(n1, n2, n3)))/sqrt(delta(n1, n2, n3)**2-4*epsilon(n1, n2, n3))-R*log(V(n1, n2, n3)) H_dep = P(n1, n2, n3)*V(n1, n2, n3) - R*T + 2*atanh((2*V(n1, n2, n3)+delta(n1, n2, n3))/sqrt(delta(n1, n2, n3)**2-4*epsilon(n1, n2, n3)))*(da_alpha_dT(n1, n2, n3)*T-a_alpha(n1, n2, n3))/sqrt(delta(n1, n2, n3)**2-4*epsilon(n1, n2, n3)) G_dep = simplify(H_dep - T*S_dep) V_dep = V(n1, n2, n3) - R*T/P(n1, n2, n3) U_dep = H_dep - P(n1, n2, n3)*V_dep A_dep = simplify(U_dep - T*S_dep) expr = diff(A_dep, n1) for ni in ns: expr = expr.subs(Derivative(V(n1, n2, n3), ni), -Vt) expr = simplify(expr) cse(expr, optimizations='basic') ''' if phase == 'g': Vt = self.V_g else: Vt = self.V_l T, N = self.T, self.N b = self.b a_alpha = self.a_alpha epsilon = self.epsilon depsilon_dns = self.depsilon_dns ddelta_dns = self.ddelta_dns db_dns = self.db_dns da_alpha_dns = self.da_alpha_dns dP_dns_Vt = self.dP_dns_Vt(phase) x0 = self.P x1 = Vt x2 = self.b x3 = x1 - x2 x4 = self.delta x5 = x4**2 x6 = self.epsilon x7 = 4*x6 x8 = x5 - x7 x9 = x8**(7/2) x10 = 2*x1 x11 = x10 + x4 x12 = x11**2 - x5 + x7 x13 = Vt*x0 x14 = x12*x3 x15 = R*T*x9 x16 = x14*x15 x17 = self.a_alpha x18 = x0*x10 x19 = x14*catanh(x11*x8**-0.5).real jac = [] for i in range(N): x20 = ddelta_dns[i] x21 = x20*x4 - 2*depsilon_dns[i] x22 = x17*x18 v = (-(-x0*x1*x12*x15*(Vt + db_dns[i]) + x13*x16 - x16*(-x1*dP_dns_Vt[i] + x13) + x18*x19*x8**3*da_alpha_dns[i] - x19*x21*x22*x8**2 + x22*x3*x8**(5/2)*(x11*x21 + x8*(2*Vt - x20)))/(x0*x1*x12*x3*x9)) jac.append(v) return jac def d2A_dep_dninjs_Vt(self, phase): if phase == 'g': Vt = self.V_g else: Vt = self.V_l T, N = self.T, self.N b = self.b a_alpha = self.a_alpha epsilon = self.epsilon depsilon_dns = self.depsilon_dns ddelta_dns = self.ddelta_dns db_dns = self.db_dns da_alpha_dns = self.da_alpha_dns d2delta_dninjs = self.d2delta_dninjs d2epsilon_dninjs = self.d2epsilon_dninjs d2bs = self.d2b_dninjs d2a_alpha_dninjs = self.d2a_alpha_dninjs dP_dns_Vt = self.dP_dns_Vt(phase) d2P_dninjs_Vt = self.d2P_dninjs_Vt(phase) hess = [[0.0]*N for i in range(N)] for i in range(N): for j in range(i+1): x0 = self.P x1 = x0**2 x2 = Vt#V(n1, n2, n3) x3 = x2**2 x4 = self.b x5 = x2 - x4 x6 = x5**2 x7 = self.delta x8 = x7**2 x9 = self.epsilon x10 = 4*x9 x11 = -x10 + x8 x12 = x11**(25/2) x13 = 2*x2 x14 = x13 + x7 x15 = x10 + x14**2 - x8 x16 = x15**2 x17 = x1*x6 x18 = R*T*x12*x16 x19 = x17*x18 x20 = x1*x18*x3 x21 = Vt*x0 x22 = dP_dns_Vt[i] x23 = -x2*x22 + x21 x24 = 2*Vt x25 = dP_dns_Vt[j] x26 = x18*x2*x6 x27 = self.a_alpha x28 = x17*x3 x29 = 2*x28 x30 = x16*catanh(x14/sqrt(x11)).real x31 = x29*x30 x32 = ddelta_dns[i] x33 = x32*x7 - 2*depsilon_dns[i] x34 = ddelta_dns[j] x35 = x34*x7 - 2*depsilon_dns[j] x36 = x33*x35 x37 = da_alpha_dns[j] x38 = da_alpha_dns[i] x39 = d2delta_dninjs[i][j] x40 = x32*x34 + x39*x7 - 2*d2epsilon_dninjs[i][j] x41 = x11*(x24 - x32) + x13*x33 + x33*x7 x42 = x11*(x24 - x34) + x13*x35 + x35*x7 x43 = x11**(21/2)*x27 x44 = x15*x29 x45 = x43*x44 v = (-(Vt**2*x19 - Vt*x13*x19 + x0*x26*(-Vt*x22 - Vt*x25 + x0*x24 + x2*d2P_dninjs_Vt[i][j]) + x11**(23/2)*x44*(x37*x41 + x38*x42) + x11**12*x31*d2a_alpha_dninjs[i][j] - x11**11*x31*(x27*x40 + x33*x37 + x35*x38) + 6*x11**10*x27*x28*x30*x36 + 4*x14*x28*x41*x42*x43 - x18*x21*x23*x6 + x20*x5*(x24 - d2bs[i][j]) - x20*(Vt + db_dns[i])*(Vt + db_dns[j]) + x23*x25*x26 - x45*(x33*x42 + x35*x41) - x45*(x11**2*(4*Vt + x39) - x11*(x13*x40 - x24*x33 - x24*x35 + x32*x35 + x33*x34 + x40*x7) + 3*x14*x36))/(x1*x12*x16*x3*x6)) hess[i][j] = hess[j][i] = v return hess # @property # def SCp0_l(self): # S_dep = self.S_dep_l # S_dep -= R*sum([zi*log(zi) for zi in self.zs if zi > 0.0]) # ideal composition entropy composition # S_dep -= R*log(self.P/101325.0) # return S_dep # # @property # def ACp0_l(self): # return self.A_dep_l - self.T*(self.SCp0_l - self.S_dep_l) # # @property # def SCp0_g(self): # S_dep = self.S_dep_g # S_dep -= R*sum([zi*log(zi) for zi in self.zs if zi > 0.0]) # ideal composition entropy composition # S_dep -= R*log(self.P/101325.0) # return S_dep # # @property # def ACp0_g(self): # return self.A_dep_g - self.T*(self.SCp0_g - self.S_dep_g) # # def Scomp(self, phase): # v = self.T*R*sum([zi*log(zi) for zi in self.zs if zi > 0.0]) # ideal composition entropy composition # v += R*self.T*log(self.P/101325.0) # return v # # @property # def HCp0_g(self): # return self.H_dep_g # # @property # def HCp0_l(self): # return self.H_dep_l # # @property # def GCp0_g(self): # return self.HCp0_g - self.T*self.SCp0_g # # @property # def GCp0_l(self): # return self.HCp0_l - self.T*self.SCp0_l def dScomp_dns(self, phase): dP_dns_Vt = self.dP_dns_Vt(phase) mRT = -R*self.T zs, N = self.zs, self.N logzs = [log(zi) for zi in zs] tot = 0.0 for i in range(N): tot += zs[i]*logzs[i] const = R*self.T/self.P return [mRT*(tot - logzs[i]) + const*dP_dns_Vt[i] for i in range(N)] def d2Scomp_dninjs(self, phase): '''P_ref = symbols('P_ref') diff(R*T*log(P(n1, n2, n3)/P_ref), n1, n2) ''' dP_dns_Vt = self.dP_dns_Vt(phase) d2P_dninjs_Vt = self.d2P_dninjs_Vt(phase) P = self.P RT = R*self.T const = RT/P zs, N = self.zs, self.N logzs = [log(zi) for zi in zs] hess = [] for i in range(N): row = [] for j in range(N): t = sum(2.0*zs[i]*logzs[i] + 3.0*zs[i] for i in range(N)) if i != j: v = RT*(t - logzs[i] - logzs[j] -4.0) else: v = RT*(t - 2*logzs[i] - 3 - (zs[i] - 1.0)/zs[i]) v += const*(d2P_dninjs_Vt[i][j] - dP_dns_Vt[i]*dP_dns_Vt[j]/P) row.append(v) hess.append(row) return hess # TODO fix the implementation below, make it work tot = 0.0 for i in range(N): tot += zs[i]*logzs[i] tot2m1 = tot + tot - 1.0 hess = [[RT*(tot2m1 - logzs[i] - logzs[j]) for i in range(N)] for j in range(N)] return hess # return d2xs_to_dxdn_partials(hess, zs) # return d2ns_to_dn2_partials(hess, self.dScomp_dns) def d2A_dninjs_Vt(self, phase): if phase == 'g': Vt = self.V_g else: Vt = self.V_l N, zs = self.N, self.zs d2A_dep_dninjs_Vt = self.d2A_dep_dninjs_Vt(phase) d2Scomp_dninjs = self.d2Scomp_dninjs hess = [[0.0]*N for i in range(N)] for i in range(N): for j in range(N): hess[i][j] = d2Scomp_dninjs[i][j] + d2A_dep_dninjs_Vt[i][j] return hess def d2nA_dninjs_Vt(self, phase): d2ns = [[i+j for i, j in zip(r1, r2)] for r1, r2 in zip(self.d2A_dep_dninjs_Vt(phase), self.d2Scomp_dninjs(phase))] dns = [i+j for i, j in zip(self.dA_dep_dns_Vt(phase), self.dScomp_dns(phase))] return d2ns_to_dn2_partials(d2ns, dns) def d2A_dninjs_Vt_another(self, phase): d2ns = [[i+j for i, j in zip(r1, r2)] for r1, r2 in zip(self.d2A_dep_dninjs_Vt(phase), self.d2Scomp_dninjs(phase))] return d2ns # dns = [i+j for i, j in zip(self.dA_dep_dns_Vt(phase), self.dScomp_dns(phase))] # return d2ns_to_dn2_partials(d2ns, dns) def _d_main_derivatives_and_departures_dnx(self, V, db_dns, ddelta_dns, depsilon_dns, da_alpha_dns, da_alpha_dT_dns, d2a_alpha_dT2_dns, dV_dns): T = self.T Z = (self.P*V)/(R*T) x0 = self.a_alpha x2 = self.epsilon x3 = V x4 = self.delta x5 = x2 + x3**2 + x3*x4 x6 = 1/x5 x7 = self.b x8 = x3 - x7 x14 = x5**(-2) x15 = self.da_alpha_dT x16 = x14*x15 x18 = 2*x3 + x4 x23 = x5**(-3) x24 = 2*x23 x27 = x18**2 x28 = x18*x24 dndP_dT_dsn = [] dndP_dV_dns = [] dnd2P_dT2_dns = [] dnd2P_dV2_dns = [] dnd2P_dTdV_dns = [] for i in range(self.N): x1 = da_alpha_dT_dns[i] x9 = dV_dns[i] x10 = R*(x9 - db_dns[i]) x17 = 2*x10/x8**3 x12 = 2*x9 x11 = ddelta_dns[i] x21 = x11 + x12 x22 = x0*x21 x13 = x11*x3 + x12*x3 + x4*x9 + depsilon_dns[i] x25 = x0*x13 x26 = x24*x25 x19 = da_alpha_dns[i] x20 = x14*x19 dndP_dT = -x1*x6 - x10/x8**2 + x13*x16 dndP_dT_dsn.append(dndP_dT) dndP_dV = T*x17 + x14*x22 + x18*x20 - x18*x26 dndP_dV_dns.append(dndP_dV) d2a_alpha_dT2_dn = d2a_alpha_dT2_dns[i] dnd2P_dT2 = x6*(x13*x6*self.d2a_alpha_dT2 - d2a_alpha_dT2_dn) dnd2P_dT2_dns.append(dnd2P_dT2) dnd2P_dV2 = -6*T*x10/x8**4 - 2*x19*x23*x27 + 2*x20 - 2*x22*x28 + 6*x25*x27/x5**4 - 2*x26 dnd2P_dV2_dns.append(dnd2P_dV2) dnd2P_dTdV = x1*x14*x18 - x13*x15*x28 + x16*x21 + x17 dnd2P_dTdV_dns.append(dnd2P_dTdV) return dndP_dT_dsn, dndP_dV_dns, dnd2P_dT2_dns, dnd2P_dV2_dns, dnd2P_dTdV_dns def _d_main_derivatives_and_departures_dn(self, V): Z = (self.P*V)/(R*self.T) db_dns = self.db_dns ddelta_dns = self.ddelta_dns depsilon_dns = self.depsilon_dns dV_dns = self.dV_dns(Z) da_alpha_dns = self.da_alpha_dns da_alpha_dT_dns = self.da_alpha_dT_dns d2a_alpha_dT2_dns = self.d2a_alpha_dT2_dns return self._d_main_derivatives_and_departures_dnx(V, db_dns, ddelta_dns, depsilon_dns, da_alpha_dns, da_alpha_dT_dns, d2a_alpha_dT2_dns, dV_dns) def _d_main_derivatives_and_departures_dz(self, V): Z = (self.P*V)/(R*self.T) db_dzs = self.db_dzs ddelta_dzs = self.ddelta_dzs depsilon_dzs = self.depsilon_dzs dV_dzs = self.dV_dzs(Z) da_alpha_dzs = self.da_alpha_dzs da_alpha_dT_dzs = self.da_alpha_dT_dzs d2a_alpha_dT2_dzs = self.d2a_alpha_dT2_dzs return self._d_main_derivatives_and_departures_dnx(V, db_dzs, ddelta_dzs, depsilon_dzs, da_alpha_dzs, da_alpha_dT_dzs, d2a_alpha_dT2_dzs, dV_dzs) def _dnz_derivatives_and_departures(self, V, n=True): try: if V == self.V_l: l = True else: l = False except: l = False if n: f = self._d_main_derivatives_and_departures_dn else: f = self._d_main_derivatives_and_departures_dz d2P_dTdns, d2P_dVdns, d3P_dT2dns, d3P_dV2dns, d3P_dTdVdns = f(V) # Needed in calculation routines if l: (dP_dT, dP_dV, dV_dT, dV_dP, dT_dV, dT_dP, d2P_dT2, d2P_dV2, d2V_dT2, d2V_dP2, d2T_dV2, d2T_dP2, d2V_dPdT, d2P_dTdV, d2T_dPdV) = (self.dP_dT_l, self.dP_dV_l, self.dV_dT_l, self.dV_dP_l, self.dT_dV_l, self.dT_dP_l, self.d2P_dT2_l, self.d2P_dV2_l, self.d2V_dT2_l, self.d2V_dP2_l, self.d2T_dV2_l, self.d2T_dP2_l, self.d2V_dPdT_l, self.d2P_dTdV_l, self.d2T_dPdV_l) else: (dP_dT, dP_dV, dV_dT, dV_dP, dT_dV, dT_dP, d2P_dT2, d2P_dV2, d2V_dT2, d2V_dP2, d2T_dV2, d2T_dP2, d2V_dPdT, d2P_dTdV, d2T_dPdV) = (self.dP_dT_g, self.dP_dV_g, self.dV_dT_g, self.dV_dP_g, self.dT_dV_g, self.dT_dP_g, self.d2P_dT2_g, self.d2P_dV2_g, self.d2V_dT2_g, self.d2V_dP2_g, self.d2T_dV2_g, self.d2T_dP2_g, self.d2V_dPdT_g, self.d2P_dTdV_g, self.d2T_dPdV_g) d2V_dTdns = [] d2V_dPdns = [] d2T_dVdns = [] d2T_dPdns = [] d3T_dP2dns = [] d3V_dP2dns = [] d3T_dV2dns = [] d3V_dT2dns = [] d3T_dPdVdns = [] d3V_dPdTdns = [] for i in range(self.N): d2P_dTdn, d2P_dVdn, d3P_dT2dn, d3P_dV2dn, d3P_dTdVdn = ( d2P_dTdns[i], d2P_dVdns[i], d3P_dT2dns[i], d3P_dV2dns[i], d3P_dTdVdns[i]) # First derivative - one over the other d2V_dTdn = dP_dT*d2P_dVdn/dP_dV**2 - d2P_dTdn/dP_dV d2V_dTdns.append(d2V_dTdn) # dP_dT # f # dP_dV # g # Second derivative - one over the other d2V_dPdn = dV_dT*d2P_dTdn/dP_dT**2 - d2V_dTdn/dP_dT d2V_dPdns.append(d2V_dPdn) # f = dV_dT # g = dP_dT # Third derivative - inverse of other expression d2T_dVdn = -d2V_dTdn/dV_dT**2 d2T_dVdns.append(d2T_dVdn) # Fourth derivative - inverse of other expression d2T_dPdn = -d2P_dTdn/dP_dT**2 d2T_dPdns.append(d2T_dPdn) # Fifth derivative - starting to get big f = d2P_dT2 df = d3P_dT2dn g = dP_dT dg = d2P_dTdn d3T_dP2dn = 3*f*dg/g**4 - df/g**3 d3T_dP2dns.append(d3T_dP2dn) # Sixth derivative f = d2P_dV2 df = d3P_dV2dn g = dP_dV dg = d2P_dVdn d3V_dP2dn = 3*f*dg/g**4 - df/g**3 d3V_dP2dns.append(d3V_dP2dn) # Seventh - crazy f = d2P_dV2 df = d3P_dV2dn g = dP_dT dg = d2P_dTdn h = dP_dV dh = d2P_dVdn k = d2P_dTdV dk = d3P_dTdVdn j = d2P_dT2 dj = d3P_dT2dn d3T_dV2dn = (f*g**2*dg - g**3*df + 2*g**2*h*dk + 2*g**2*k*dh - g*h**2*dj - 4*g*h*k*dg - 2*g*h*j*dh + 3*h**2*j*dg)/g**4 d3T_dV2dns.append(d3T_dV2dn) # ekghth - crazy f = d2P_dT2 df = d3P_dT2dn g = dP_dV dg = d2P_dVdn h = dP_dT dh = d2P_dTdn k = d2P_dTdV dk = d3P_dTdVdn j = d2P_dV2 dj = d3P_dV2dn d3V_dT2dn = (f*g**2*dg - g**3*df + 2*g**2*h*dk + 2*g**2*k*dh - g*h**2*dj - 4*g*h*k*dg - 2*g*h*j*dh + 3*h**2*j*dg)/g**4 d3V_dT2dns.append(d3V_dT2dn) # nknth f = d2P_dTdV df = d3P_dTdVdn g = dP_dT dg = d2P_dTdn h = dP_dV dh = d2P_dVdn k = d2P_dT2 dk = d3P_dT2dn j = dP_dT dj = d2P_dTdn d3T_dPdVdn = 3*(f*g - h*k)*dj/j**4 - (f*dg + g*df - h*dk- k*dh)/j**3 d3T_dPdVdns.append(d3T_dPdVdn) # tenth f = d2P_dTdV df = d3P_dTdVdn g = dP_dV dg = d2P_dVdn h = dP_dT dh = d2P_dTdn k = d2P_dV2 dk = d3P_dV2dn j = dP_dV dj = d2P_dVdn d3V_dPdTdn = 3*(f*g - h*k)*dj/j**4 - (f*dg + g*df - h*dk- k*dh)/j**3 d3V_dPdTdns.append(d3V_dPdTdn) return (d2P_dTdns, d2P_dVdns, d2V_dTdns, d2V_dPdns, d2T_dVdns, d2T_dPdns, d3P_dT2dns, d3P_dV2dns, d3V_dT2dns, d3V_dP2dns, d3T_dV2dns, d3T_dP2dns, d3V_dPdTdns, d3P_dTdVdns, d3T_dPdVdns) def set_dnzs_derivatives_and_departures(self, n=True, x=True, only_l=False, only_g=False): r'''Sets a number of mole number and/or composition partial derivatives of thermodynamic partial derivatives. The list of properties set is as follows, with all properties suffixed with '_l' or '_g' if `n` is True: d2P_dTdns, d2P_dVdns, d2V_dTdns, d2V_dPdns, d2T_dVdns, d2T_dPdns, d3P_dT2dns, d3P_dV2dns, d3V_dT2dns, d3V_dP2dns, d3T_dV2dns, d3T_dP2dns, d3V_dPdTdns, d3P_dTdVdns, d3T_dPdVdns, dV_dep_dns, dG_dep_dns, dH_dep_dns, dU_dep_dns, dS_dep_dns, dA_dep_dns if `x` is True: d2P_dTdzs, d2P_dVdzs, d2V_dTdzs, d2V_dPdzs, d2T_dVdzs, d2T_dPdzs, d3P_dT2dzs, d3P_dV2dzs, d3V_dT2dzs, d3V_dP2dzs, d3T_dV2dzs, d3T_dP2dzs, d3V_dPdTdzs, d3P_dTdVdzs, d3T_dPdVdzs, dV_dep_dzs, dG_dep_dzs, dH_dep_dzs, dU_dep_dzs, dS_dep_dzs, dA_dep_dzs Parameters ---------- n : bool, optional Whether or not to set the mole number derivatives (sums up to one), [-] x : bool, optional Whether or not to set the composition derivatives (does not sum up to one), [-] only_l : bool, optional Whether or not to set only the liquid-like phase properties (if there are two phases), [-] only_g : bool, optional Whether or not to set only the gas-like phase properties (if there are two phases), [-] Notes ----- ''' N = self.N zs = self.zs T, P = self.T, self.P if n and x: ns = [True, False] elif n: ns = [True] elif x: ns = [False] else: return if only_l: phases = ['l'] elif only_g: phases = ['g'] else: phases = ['l', 'g'] for n in ns: for phase in phases: if phase == 'g': Z, V = self.Z_g, self.V_g else: Z, V = self.Z_l, self.V_l if n: V_fun, G_fun, H_fun = self.dV_dns, self.dG_dep_dns, self.dH_dep_dns else: V_fun, G_fun, H_fun = self.dV_dzs, self.dG_dep_dzs, self.dH_dep_dzs (d2P_dTdns, d2P_dVdns, d2V_dTdns, d2V_dPdns, d2T_dVdns, d2T_dPdns, d3P_dT2dns, d3P_dV2dns, d3V_dT2dns, d3V_dP2dns, d3T_dV2dns, d3T_dP2dns, d3V_dPdTdns, d3P_dTdVdns, d3T_dPdVdns) = self._dnz_derivatives_and_departures(V, n=n) # V dV_dep_dns = V_fun(Z) # G dG_dep_dns = G_fun(Z) # H dH_dep_dns = H_fun(Z) # U dU_dep_dns = [dH_dep_dns[i] - P*dV_dep_dns[i] for i in range(N)] # S dS_dep_dns = [(dG_dep_dns[i] - dH_dep_dns[i])/-T for i in range(N)] # A dA_dep_dns = [dU_dep_dns[i] - T*dS_dep_dns[i] for i in range(N)] if n and phase == 'l': self.d2P_dTdns_l, self.d2P_dVdns_l, self.d2V_dTdns_l = d2P_dTdns, d2P_dVdns, d2V_dTdns self.d2V_dPdns_l, self.d2T_dVdns_l, self.d2T_dPdns_l = d2V_dPdns, d2T_dVdns, d2T_dPdns self.d3P_dT2dns_l, self.d3P_dV2dns_l, self.d3V_dT2dns_l = d3P_dT2dns, d3P_dV2dns, d3V_dT2dns self.d3V_dP2dns_l, self.d3T_dV2dns_l, self.d3T_dP2dns_l = d3V_dP2dns, d3T_dV2dns, d3T_dP2dns self.d3V_dPdTdns_l, self.d3P_dTdVdns_l, self.d3T_dPdVdns_l = d3V_dPdTdns, d3P_dTdVdns, d3T_dPdVdns self.dV_dep_dns_l, self.dG_dep_dns_l, self.dH_dep_dns_l = dV_dep_dns, dG_dep_dns, dH_dep_dns self.dU_dep_dns_l, self.dS_dep_dns_l, self.dA_dep_dns_l = dU_dep_dns, dS_dep_dns, dA_dep_dns if n and phase == 'g': self.d2P_dTdns_g, self.d2P_dVdns_g, self.d2V_dTdns_g = d2P_dTdns, d2P_dVdns, d2V_dTdns self.d2V_dPdns_g, self.d2T_dVdns_g, self.d2T_dPdns_g = d2V_dPdns, d2T_dVdns, d2T_dPdns self.d3P_dT2dns_g, self.d3P_dV2dns_g, self.d3V_dT2dns_g = d3P_dT2dns, d3P_dV2dns, d3V_dT2dns self.d3V_dP2dns_g, self.d3T_dV2dns_g, self.d3T_dP2dns_g = d3V_dP2dns, d3T_dV2dns, d3T_dP2dns self.d3V_dPdTdns_g, self.d3P_dTdVdns_g, self.d3T_dPdVdns_g = d3V_dPdTdns, d3P_dTdVdns, d3T_dPdVdns self.dV_dep_dns_g, self.dG_dep_dns_g, self.dH_dep_dns_g = dV_dep_dns, dG_dep_dns, dH_dep_dns self.dU_dep_dns_g, self.dS_dep_dns_g, self.dA_dep_dns_g = dU_dep_dns, dS_dep_dns, dA_dep_dns if not n and phase == 'g': self.d2P_dTdzs_g, self.d2P_dVdzs_g, self.d2V_dTdzs_g = d2P_dTdns, d2P_dVdns, d2V_dTdns self.d2V_dPdzs_g, self.d2T_dVdzs_g, self.d2T_dPdzs_g = d2V_dPdns, d2T_dVdns, d2T_dPdns self.d3P_dT2dzs_g, self.d3P_dV2dzs_g, self.d3V_dT2dzs_g = d3P_dT2dns, d3P_dV2dns, d3V_dT2dns self.d3V_dP2dzs_g, self.d3T_dV2dzs_g, self.d3T_dP2dzs_g = d3V_dP2dns, d3T_dV2dns, d3T_dP2dns self.d3V_dPdTdzs_g, self.d3P_dTdVdzs_g, self.d3T_dPdVdzs_g = d3V_dPdTdns, d3P_dTdVdns, d3T_dPdVdns self.dV_dep_dzs_g, self.dG_dep_dzs_g, self.dH_dep_dzs_g = dV_dep_dns, dG_dep_dns, dH_dep_dns self.dU_dep_dzs_g, self.dS_dep_dzs_g, self.dA_dep_dzs_g = dU_dep_dns, dS_dep_dns, dA_dep_dns if not n and phase == 'l': self.d2P_dTdzs_l, self.d2P_dVdzs_l, self.d2V_dTdzs_l = d2P_dTdns, d2P_dVdns, d2V_dTdns self.d2V_dPdzs_l, self.d2T_dVdzs_l, self.d2T_dPdzs_l = d2V_dPdns, d2T_dVdns, d2T_dPdns self.d3P_dT2dzs_l, self.d3P_dV2dzs_l, self.d3V_dT2dzs_l = d3P_dT2dns, d3P_dV2dns, d3V_dT2dns self.d3V_dP2dzs_l, self.d3T_dV2dzs_l, self.d3T_dP2dzs_l = d3V_dP2dns, d3T_dV2dns, d3T_dP2dns self.d3V_dPdTdzs_l, self.d3P_dTdVdzs_l, self.d3T_dPdVdzs_l = d3V_dPdTdns, d3P_dTdVdns, d3T_dPdVdns self.dV_dep_dzs_l, self.dG_dep_dzs_l, self.dH_dep_dzs_l = dV_dep_dns, dG_dep_dns, dH_dep_dns self.dU_dep_dzs_l, self.dS_dep_dzs_l, self.dA_dep_dzs_l = dU_dep_dns, dS_dep_dns, dA_dep_dns def dlnphis_dP(self, phase): r'''Generic formula for calculating the pressure derivaitve of log fugacity coefficients for each species in a mixture. Verified numerically. Applicable to all cubic equations of state which can be cast in the form used here. Normally this routine is slower than EOS-specific ones, as it does not make assumptions that certain parameters are zero or equal to other parameters. .. math:: \left(\frac{\partial \ln \phi_i}{\partial P}\right)_{T, nj \ne i} = \frac{G_{dep}}{\partial P}_{T, n} + \left(\frac{\partial^2 \ln \phi}{\partial P \partial n_i} \right)_{T, P, n_{j \ne i}} Parameters ---------- phase : str One of 'l' or 'g', [-] Returns ------- dlnphis_dP : float Pressure derivatives of log fugacity coefficient for each species, [1/Pa] Notes ----- This expression for the partial derivative of the mixture `lnphi` with respect to pressure and mole number can be derived as follows; to convert to the partial molar `lnphi` pressure and temperature derivative, add ::math::`\frac{G_{dep}/(RT)}{\partial P}_{T, n}`. >>> from sympy import * # doctest:+SKIP >>> P, T, R, n = symbols('P, T, R, n') # doctest:+SKIP >>> a_alpha, a, delta, epsilon, V, b, da_alpha_dT, d2a_alpha_dT2 = symbols('a_alpha, a, delta, epsilon, V, b, da_alpha_dT, d2a_alpha_dT2', cls=Function) # doctest:+SKIP >>> S_dep = R*log(P*V(n, P)/(R*T)) + R*log(V(n, P)-b(n))+2*da_alpha_dT(n, T)*atanh((2*V(n, P)+delta(n))/sqrt(delta(n)**2-4*epsilon(n)))/sqrt(delta(n)**2-4*epsilon(n))-R*log(V(n, P)) # doctest:+SKIP >>> H_dep = P*V(n, P) - R*T + 2*atanh((2*V(n, P)+delta(n))/sqrt(delta(n)**2-4*epsilon(n)))*(da_alpha_dT(n, T)*T-a_alpha(n, T))/sqrt(delta(n)**2-4*epsilon(n)) # doctest:+SKIP >>> G_dep = H_dep - T*S_dep # doctest:+SKIP >>> lnphi = simplify(G_dep/(R*T)) # doctest:+SKIP >>> diff(diff(lnphi, P), n) # doctest:+SKIP P*Derivative(V(n, P), P, n)/(R*T) + Derivative(V(n, P), P, n)/V(n, P) - Derivative(V(n, P), P)*Derivative(V(n, P), n)/V(n, P)**2 - Derivative(V(n, P), P, n)/(V(n, P) - b(n)) - (-Derivative(V(n, P), n) + Derivative(b(n), n))*Derivative(V(n, P), P)/(V(n, P) - b(n))**2 + Derivative(V(n, P), n)/(R*T) - 4*(-2*delta(n)*Derivative(delta(n), n) + 4*Derivative(epsilon(n), n))*a_alpha(n, T)*Derivative(V(n, P), P)/(R*T*(1 - (2*V(n, P)/sqrt(delta(n)**2 - 4*epsilon(n)) + delta(n)/sqrt(delta(n)**2 - 4*epsilon(n)))**2)*(delta(n)**2 - 4*epsilon(n))**2) - 4*a_alpha(n, T)*Derivative(V(n, P), P, n)/(R*T*(1 - (2*V(n, P)/sqrt(delta(n)**2 - 4*epsilon(n)) + delta(n)/sqrt(delta(n)**2 - 4*epsilon(n)))**2)*(delta(n)**2 - 4*epsilon(n))) - 4*Derivative(V(n, P), P)*Derivative(a_alpha(n, T), n)/(R*T*(1 - (2*V(n, P)/sqrt(delta(n)**2 - 4*epsilon(n)) + delta(n)/sqrt(delta(n)**2 - 4*epsilon(n)))**2)*(delta(n)**2 - 4*epsilon(n))) - 4*(2*V(n, P)/sqrt(delta(n)**2 - 4*epsilon(n)) + delta(n)/sqrt(delta(n)**2 - 4*epsilon(n)))*(4*(-delta(n)*Derivative(delta(n), n) + 2*Derivative(epsilon(n), n))*V(n, P)/(delta(n)**2 - 4*epsilon(n))**(3/2) + 2*(-delta(n)*Derivative(delta(n), n) + 2*Derivative(epsilon(n), n))*delta(n)/(delta(n)**2 - 4*epsilon(n))**(3/2) + 4*Derivative(V(n, P), n)/sqrt(delta(n)**2 - 4*epsilon(n)) + 2*Derivative(delta(n), n)/sqrt(delta(n)**2 - 4*epsilon(n)))*a_alpha(n, T)*Derivative(V(n, P), P)/(R*T*(1 - (2*V(n, P)/sqrt(delta(n)**2 - 4*epsilon(n)) + delta(n)/sqrt(delta(n)**2 - 4*epsilon(n)))**2)**2*(delta(n)**2 - 4*epsilon(n))) + R*T*(P*Derivative(V(n, P), P)/(R*T) + V(n, P)/(R*T))*Derivative(V(n, P), n)/(P*V(n, P)**2) - R*T*(P*Derivative(V(n, P), P, n)/(R*T) + Derivative(V(n, P), n)/(R*T))/(P*V(n, P)) ''' if phase == 'g': V = self.V_g Z = self.Z_g dV_dP = self.dV_dP_g dG_dep_dP = (self.dH_dep_dP_g - self.T*self.dS_dep_dP_g)/(R*self.T) else: V = self.V_l Z = self.Z_l dV_dP = self.dV_dP_l dG_dep_dP = (self.dH_dep_dP_l - self.T*self.dS_dep_dP_l)/(R*self.T) T = self.T P = self.P dV_dns = self.dV_dns(Z) ddelta_dns = self.ddelta_dns depsilon_dns = self.depsilon_dns da_alpha_dns = self.da_alpha_dns db_dns = self.db_dns d2V_dPdns = self._dnz_derivatives_and_departures(V)[3]# self.d2V_dPdn x0 = V x2 = 1/(R*T) x3 = 1/x0 x6 = dV_dP x8 = self.b x9 = x0 - x8 x10 = 1/P x11 = self.delta x12 = 2*x0 x13 = x11 + x12 x14 = self.epsilon x15 = x11**2 - 4*x14 try: x16 = 1/x15 except ZeroDivisionError: x16 = 1e50 x17 = x13**2*x16 - 1 x18 = 1/x17 x19 = self.a_alpha x20 = 4*x16 x21 = x2*x6 x22 = x18*x21 x25 = 8*x19*x16*x16 t50 = 1.0/(x0*x0) dlnphis_dPs = [] for i in range(self.N): # number dependent calculations x1 = dV_dns[i] # Derivative(x0, n) x7 = x1*t50 x4 = d2V_dPdns[i] #Derivative(x0, P, n) # TODO calculate only this - d2V_dPdn; the T one wants d2V_dTdn x5 = P*x4 x23 = ddelta_dns[i]# Derivative(x11, n) x24 = x11*x23 - 2.0*depsilon_dns[i]#Derivative(x14, n) x26 = x16*x24 dlnphi_dP = (x1*x2 - x10*x3*(x1 + x5) + x10*x7*(P*x6 + x0) - x13*x21*x25*(2*x1 - x11*x26 - x12*x26 + x23)/x17**2 + x18*x19*x2*x20*x4 + x2*x5 + x20*x22*da_alpha_dns[i] - x22*x24*x25 + x3*x4 - x4/x9 - x6*x7 + x6*(x1 - db_dns[i])/x9**2) dlnphis_dPs.append(dlnphi_dP + dG_dep_dP) return dlnphis_dPs def dlnphis_dT(self, phase): r'''Generic formula for calculating the temperature derivaitve of log fugacity coefficients for each species in a mixture. Verified numerically. Applicable to all cubic equations of state which can be cast in the form used here. Normally this routine is slower than EOS-specific ones, as it does not make assumptions that certain parameters are zero or equal to other parameters. .. math:: \left(\frac{\partial \ln \phi_i}{\partial T}\right)_{P, nj \ne i} = \frac{\frac{G_{dep}}{RT}}{\partial T}_{P, n} + \left(\frac{\partial^2 \ln \phi}{\partial T \partial n_i} \right)_{P, n_{j \ne i}} Parameters ---------- phase : str One of 'l' or 'g', [-] Returns ------- dlnphis_dT : float Temperature derivatives of log fugacity coefficient for each species, [1/K] Notes ----- This expression for the partial derivative of the mixture `lnphi` with respect to pressure and mole number can be derived as follows; to convert to the partial molar `lnphi` pressure and temperature derivative, add ::math::`\frac{G_{dep}/(RT)}{\partial T}_{P, n}`. >>> from sympy import * # doctest:+SKIP >>> P, T, R, n = symbols('P, T, R, n') # doctest:+SKIP >>> a_alpha, a, delta, epsilon, V, b, da_alpha_dT, d2a_alpha_dT2 = symbols('a_alpha, a, delta, epsilon, V, b, da_alpha_dT, d2a_alpha_dT2', cls=Function) # doctest:+SKIP >>> S_dep = R*log(P*V(n, T)/(R*T)) + R*log(V(n, T)-b(n))+2*da_alpha_dT(n, T)*atanh((2*V(n, T)+delta(n))/sqrt(delta(n)**2-4*epsilon(n)))/sqrt(delta(n)**2-4*epsilon(n))-R*log(V(n, T)) # doctest:+SKIP >>> H_dep = P*V(n, T) - R*T + 2*atanh((2*V(n, T)+delta(n))/sqrt(delta(n)**2-4*epsilon(n)))*(da_alpha_dT(n, T)*T-a_alpha(n, T))/sqrt(delta(n)**2-4*epsilon(n)) # doctest:+SKIP >>> G_dep = H_dep - T*S_dep # doctest:+SKIP >>> lnphi = simplify(G_dep/(R*T)) # doctest:+SKIP >>> diff(diff(lnphi, T), n) # doctest:+SKIP ''' T, P, zs, N = self.T, self.P, self.zs, self.N if phase == 'g': V = self.V_g Z = self.Z_g dV_dT = self.dV_dT_g dG_dep_dT = (-T*self.dS_dep_dT_g - self.S_dep_g + self.dH_dep_dT_g)/(R*self.T) dG_dep_dT -= (-T*self.S_dep_g + self.H_dep_g)/(R*self.T*self.T) else: V = self.V_l Z = self.Z_l dV_dT = self.dV_dT_l dG_dep_dT = (-T*self.dS_dep_dT_l - self.S_dep_l + self.dH_dep_dT_l)/(R*self.T) dG_dep_dT -= (-T*self.S_dep_l + self.H_dep_l)/(R*self.T*self.T) '''R, T = symbols('R, T') H, S = symbols('H, S', cls=Function) print(diff((H(T) - T*S(T))/(R*T), T)) # (-T*Derivative(S(T), T) - S(T) + Derivative(H(T), T))/(R*T) - (-T*S(T) + H(T))/(R*T**2) ''' d2V_dTdns = self._dnz_derivatives_and_departures(V, n=True)[2] dV_dns = self.dV_dns(Z) db_dns = self.db_dns da_alpha_dns = self.da_alpha_dns da_alpha_dT_dns = self.da_alpha_dT_dns ddelta_dns = self.ddelta_dns depsilon_dns = self.depsilon_dns x0 = V x1 = 1/x0 x4 = T**(-2) x5 = 1/R x6 = P*x5 x7 = 1/T x9 = dV_dT x11 = self.b x12 = x0 - x11 x13 = self.a_alpha x15 = self.delta x16 = self.epsilon x17 = x15*x15 - 4.0*x16 if x17 == 0.0: x17 = 1e-100 x18 = 1/sqrt(x17) x19 = 2*x0 x20 = x15 + x19 x21 = 2*x5 x22 = x21*catanh(x18*x20).real x23 = x18*x22 x24 = 1/x17 x25 = x20**2*x24 - 1 x26 = 1/x25 x27 = x24*x26 x28 = 4*x27*x5 x29 = x7*x9 x30 = x13*x4 x34 = x7*self.da_alpha_dT x35 = 8*x13*x29*x5/x17**2 dlnphis_dTs = [] for i in range(N): x2 = d2V_dTdns[i] x8 = x2*x7 x3 = dV_dns[i] x10 = x3/x0**2 x14 = da_alpha_dns[i] x31 = ddelta_dns[i] x32 = x15*x31 - 2.0*depsilon_dns[i] x33 = x22*x32/x17**(3/2) x36 = x24*x32 x37 = -x15*x36 - x19*x36 + 2.0*x3 + x31 x38 = x21*x27*x37 dlnphi_dT = (x1*x2 - x1*(x2 - x3*x7) - x10*x9 + x10*(-x0*x7 + x9) + x13*x28*x8 + x14*x23*x4 + x14*x28*x29 - x20*x35*x37/x25**2 - x23*x7*da_alpha_dT_dns[i] - x26*x32*x35 - x3*x4*x6 - x30*x33 - x30*x38 + x33*x34 + x34*x38 + x6*x8 - x2/x12 + x9*(x3 - db_dns[i])/x12**2) dlnphis_dTs.append(dlnphi_dT + dG_dep_dT) return dlnphis_dTs def dlnphis_dzs(self, Z): r'''Generic formula for calculating the mole fraction derivaitves of log fugacity coefficients for each species in a mixture. Verified numerically. Applicable to all cubic equations of state which can be cast in the form used here. .. math:: \left(\frac{\partial \ln \phi_i}{\partial z_i}\right)_{P, z_{j \ne i}} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dlnphis_dzs : list[list[float]] Mole fraction derivatives of log fugacity coefficient for each species (such that the mole fractions do not sum to 1), [-] Notes ----- ''' d2dxs = self.d2lnphi_dzizjs(Z) d2ns = d2xs_to_dxdn_partials(d2dxs, self.zs) if sefl.scalar: return d2ns return array(d2ns) class EpsilonZeroMixingRules(object): @property def depsilon_dzs(self): r'''Helper method for calculating the composition derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial \epsilon}{\partial x_i}\right)_{T, P, x_{i\ne j}} = 0 Returns ------- depsilon_dzs : list[float] Composition derivative of `epsilon` of each component, [m^6/mol^2] Notes ----- This derivative is checked numerically. ''' if self.scalar: return [0.0]*self.N return zeros(self.N) @property def depsilon_dns(self): r'''Helper method for calculating the mole number derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial \epsilon}{\partial n_i}\right)_{T, P, n_{i\ne j}} = 0 Returns ------- depsilon_dns : list[float] Composition derivative of `epsilon` of each component, [m^6/mol^3] Notes ----- This derivative is checked numerically. ''' if self.scalar: return [0.0]*self.N return zeros(self.N) @property def d2epsilon_dzizjs(self): r'''Helper method for calculating the second composition derivatives (hessian) of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \epsilon}{\partial x_i \partial x_j}\right)_{T, P, x_{k\ne i,j}} = 0 Returns ------- d2epsilon_dzizjs : list[list[float]] Composition derivative of `epsilon` of each component, [m^6/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: return [[0.0]*N for i in range(N)] return zeros((N, N)) @property def d2epsilon_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \epsilon}{\partial n_i n_j}\right)_{T, P, n_{k\ne i,j}} = 0 Returns ------- d2epsilon_dninjs : list[list[float]] Second composition derivative of `epsilon` of each component, [m^6/mol^4] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: return [[0.0]*N for i in range(N)] return zeros((N, N)) @property def d3epsilon_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \epsilon}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 0 Returns ------- d3epsilon_dninjnks : list[list[list[float]]] Third mole number derivative of `epsilon` of each component, [m^6/mol^5] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: return [[[0.0]*N for _ in range(N)] for _ in range(N)] return zeros((N, N, N)) # # Python 2/3 compatibility # try: # eos.__dict__['d3epsilon_dninjnks'] = d3epsilon_dninjnks # eos.__dict__['d2epsilon_dninjs'] = d2epsilon_dninjs # eos.__dict__['d2epsilon_dzizjs'] = d2epsilon_dzizjs # eos.__dict__['depsilon_dns'] = depsilon_dns # eos.__dict__['depsilon_dzs'] = depsilon_dzs # except: # setattr(eos, 'd3epsilon_dninjnks', d3epsilon_dninjnks) # setattr(eos, 'd2epsilon_dninjs', d2epsilon_dninjs) # setattr(eos, 'd2epsilon_dzizjs', d2epsilon_dzizjs) # setattr(eos, 'depsilon_dns', depsilon_dns) # setattr(eos, 'depsilon_dzs', depsilon_dzs) class PSRKMixingRules(object): u = 1.1 A = -0.6466271649250525 # log(1.1/(1.1+1)) A_inv = 1.0/A def a_alpha_and_derivatives(self, T, full=True, quick=True, pure_a_alphas=True): r'''Method to calculate `a_alpha` and its first and second derivatives for an EOS with the PSRK mixing rules. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. For use in some methods, this returns only `a_alpha` if `full` is False. .. math:: \alpha = bRT \left[ \sum_i \frac{z_i \alpha_i}{b_i RT} + \frac{1}{A}\left(\frac{G^E}{RT} + \sum_i z_i \ln \left(\frac{b}{b_i}\right) \right)\right] .. math:: \frac{\partial \alpha}{\partial T} = RTb\left[ \sum_i \left(\frac{z_i \frac{\partial \alpha_i}{\partial T}}{RTb_i} -\frac{z_i\alpha_i}{RT^2b_i} \right) + \frac{1}{A}\left(\frac{\frac{\partial G^E}{\partial T}}{RT} - \frac{G^E}{RT^2} \right) \right] + \frac{\alpha}{T} .. math:: \frac{\partial^2 \alpha}{\partial T^2} = b\left[\sum_i \left(\frac{z_i\frac{\partial^2 \alpha_i}{\partial T^2}}{b_i} - \frac{2z_i \frac{\partial \alpha_i}{\partial T}}{T b_i} + \frac{2z_i\alpha_i}{T^2 b_i} \right) + \frac{2}{T}\left[\sum_i \left(\frac{z_i\frac{\partial \alpha_i} {\partial T}}{b_i} - \frac{z_i \alpha_i}{T b_i} \right) + \frac{1}{A}\left(\frac{\partial G^E}{\partial T} - \frac{G^E}{T} \right) \right] + \frac{1}{A}\left( \frac{\partial^2 G^E}{\partial T^2} - \frac{2}{T} \frac{\partial G^E}{\partial T} + 2\frac{G^E}{T^2} \right) \right] Parameters ---------- T : float Temperature, [K] full : bool, optional If False, calculates and returns only `a_alpha` quick : bool, optional Only the quick variant is implemented; it is little faster anyhow pure_a_alphas : bool, optional Whether or not to recalculate the a_alpha terms of pure components (for the case of mixtures only) which stay the same as the composition changes (i.e in a PT flash), [-] Returns ------- a_alpha : float Coefficient calculated by PSRK-specific method, [J^2/mol^2/Pa] da_alpha_dT : float Temperature derivative of coefficient calculated by PSRK-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2 : float Second temperature derivative of coefficient calculated by PSRK-specific method, [J^2/mol^2/Pa/K**2] Notes ----- ''' if pure_a_alphas: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = self.a_alpha_and_derivatives_vectorized(T) self.a_alphas, self.da_alpha_dTs, self.d2a_alpha_dT2s = a_alphas, da_alpha_dTs, d2a_alpha_dT2s else: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = self.a_alphas, self.da_alpha_dTs, self.d2a_alpha_dT2s b, zs, bs = self.b, self.zs, self.bs ge_model = self.ge_model if T != ge_model.T: # TODO make sure this gets set when solve_T is called ge_model = ge_model.to_T_xs(T, zs) self._last_ge = ge_model GE = ge_model.GE() if full: dGE_dT = ge_model.dGE_dT() d2GE_dT2 = ge_model.d2GE_dT2() T_inv = 1.0/T T2_inv = T_inv*T_inv RT_inv = R_inv*T_inv RT2_inv = R_inv*T2_inv A_inv = self.A_inv N = self.N tot0, tot1, d1tot, d2tot, other = 0.0, 0.0, 0.0, 0.0, 0.0 if full: for i in range(N): bi_inv = 1.0/bs[i] # Main component tot0 += zs[i]*a_alphas[i]*bi_inv*RT_inv tot1 += zs[i]*log(b*bi_inv) d1tot += zs[i]*da_alpha_dTs[i]*RT_inv*bi_inv - zs[i]*a_alphas[i]*RT2_inv*bi_inv # TODO go back to just using d1tot # TODO optimize all of this other += zs[i]*da_alpha_dTs[i]*bi_inv - zs[i]*a_alphas[i]*bi_inv*T_inv d2tot += (zs[i]*d2a_alpha_dT2s[i]*bi_inv - 2.0*zs[i]*da_alpha_dTs[i]*T_inv*bi_inv + 2.0*zs[i]*a_alphas[i]*T2_inv*bi_inv) else: for i in range(N): bi_inv = 1.0/bs[i] tot0 += zs[i]*a_alphas[i]*bi_inv*RT_inv tot1 += zs[i]*log(b*bi_inv) a_alpha = R*T*b*(tot0 + A_inv*(GE*RT_inv + tot1)) if full: da_alpha_dT = R*T*b*(d1tot + A_inv*(dGE_dT*RT_inv - GE*RT2_inv)) + a_alpha*T_inv d2a_alpha_dT2 = b*(d2tot + 2.0*T_inv*(other + A_inv*(dGE_dT - GE*T_inv)) + A_inv*(d2GE_dT2 - 2.0*T_inv*dGE_dT + 2.0*GE*T2_inv)) return a_alpha, da_alpha_dT, d2a_alpha_dT2 return a_alpha def solve_T(self, P, V, quick=True, solution=None): T = GCEOS.solve_T(self, P, V, solution=solution) if hasattr(self, '_last_ge') and self._last_ge.T == T: self.ge_model = self._last_ge del self._last_ge else: self.ge_model = self.ge_model.to_T_xs(T, self.zs) return T @property def da_alpha_dzs(self): raise NotImplementedError("TODO") @property def da_alpha_dns(self): raise NotImplementedError("TODO") @property def dna_alpha_dns(self): raise NotImplementedError("TODO") @property def d2a_alpha_dzizjs(self): raise NotImplementedError("TODO") @property def d2a_alpha_dninjs(self): raise NotImplementedError("TODO") @property def d3a_alpha_dzizjzks(self): raise NotImplementedError("TODO") @property def d3a_alpha_dninjnks(self): raise NotImplementedError("TODO") @property def da_alpha_dT_dzs(self): raise NotImplementedError("TODO") @property def da_alpha_dT_dns(self): raise NotImplementedError("TODO") @property def dna_alpha_dT_dns(self): raise NotImplementedError("TODO") @property def d2a_alpha_dT2_dzs(self): raise NotImplementedError("TODO") @property def d2a_alpha_dT2_dns(self): raise NotImplementedError("TODO") class IGMIX(EpsilonZeroMixingRules, GCEOSMIX, IG): r'''Class for solving the ideal gas [1]_ [2]_ equation of state for a mixture of any number of compounds. Subclasses :obj:`thermo.eos.IG`. Solves the EOS on initialization. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P =\frac{RT}{V} Parameters ---------- zs : list[float] Overall mole fractions of all species, [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] Tcs : list[float], optional Critical temperatures of all compounds, [K] Pcs : list[float], optional Critical pressures of all compounds, [Pa] omegas : list[float], optional Acentric factors of all compounds - Not used in this equation of state!, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 and not used[-] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = IGMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, .008], zs=[0.5, 0.5]) >>> eos.phase, eos.V_g ('g', 0.0009561632010876225) Notes ----- Many properties of this object are zero. Many of the arguments are not used and are provided for consistency only. References ---------- .. [1] Walas, Stanley M. Phase Equilibria in Chemical Engineering. Butterworth-Heinemann, 1985. .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition. New York: McGraw-Hill Professional, 2000. ''' eos_pure = IG a_alphas = None da_alpha_dTs = None d2a_alpha_dT2s = None nonstate_constants_specific = () kwargs_keys = ('kijs',) model_id = 0 def _zeros1d(self): return self.zeros1d def _zeros2d(self): return self.zeros2d def _zeros3d(self): N = self.N if self.scalar: return [[[0.0]*N for _ in range(N)] for _ in range(N)] else: return zeros((N, N, N)) @property def a_alpha_roots(self): return self.zeros1d @property def ddelta_dzs(self): r'''Helper method for calculating the composition derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial \delta}{\partial x_i}\right)_{T, P, x_{i\ne j}} = 0 Returns ------- ddelta_dzs : list[float] Composition derivative of `delta` of each component, [m^3/mol] ''' return self.zeros1d @property def ddelta_dns(self): r'''Helper method for calculating the mole number derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial \delta}{\partial n_i}\right)_{T, P, n_{i\ne j}} = 0 Returns ------- ddelta_dns : list[float] Mole number derivative of `delta` of each component, [m^3/mol^2] ''' return self.zeros1d @property def depsilon_dzs(self): r'''Helper method for calculating the composition derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial \epsilon}{\partial x_i}\right)_{T, P, x_{i\ne j}} = 0 Returns ------- depsilon_dzs : list[float] Composition derivative of `epsilon` of each component, [m^6/mol^2] ''' return self.zeros1d @property def depsilon_dns(self): r'''Helper method for calculating the mole number derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial \epsilon}{\partial n_i}\right)_{T, P, n_{i\ne j}} = 0 Returns ------- depsilon_dns : list[float] Composition derivative of `epsilon` of each component, [m^6/mol^3] ''' return self.zeros1d @property def d2delta_dzizjs(self): r'''Helper method for calculating the second composition derivatives (hessian) of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \delta}{\partial x_i\partial x_j}\right)_{T, P, x_{k\ne i,j}} = 0 Returns ------- d2delta_dzizjs : list[float] Second Composition derivative of `delta` of each component, [m^3/mol] ''' return self.zeros2d @property def d2delta_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \delta}{\partial n_i \partial n_j}\right)_{T, P, n_{k\ne i,j}} = 0 Returns ------- d2delta_dninjs : list[list[float]] Second mole number derivative of `delta` of each component, [m^3/mol^3] ''' return self.zeros2d @property def d2epsilon_dzizjs(self): r'''Helper method for calculating the second composition derivatives (hessian) of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \epsilon}{\partial x_i \partial x_j}\right)_{T, P, x_{k\ne i,j}} = 0 Returns ------- d2epsilon_dzizjs : list[list[float]] Second composition derivative of `epsilon` of each component, [m^6/mol^2] ''' return self.zeros2d @property def d2epsilon_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \epsilon}{\partial n_i n_j}\right)_{T, P, n_{k\ne i,j}} = 0 Returns ------- d2epsilon_dninjs : list[list[float]] Second mole number derivative of `epsilon` of each component, [m^6/mol^4] ''' return self.zeros2d @property def d3delta_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \delta}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 0 Returns ------- d3delta_dninjnks : list[list[list[float]]] Third mole number derivative of `delta` of each component, [m^3/mol^4] ''' return self._zeros3d() @property def d3epsilon_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \epsilon}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 0 Returns ------- d3epsilon_dninjnks : list[list[list[float]]] Third mole number derivative of `epsilon` of each component, [m^6/mol^5] ''' return self._zeros3d() def __init__(self, zs, T=None, P=None, V=None, Tcs=None, Pcs=None, omegas=None, kijs=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(zs) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if scalar: self.zeros2d = zeros2d = [[0.0]*N for _ in range(N)] else: self.zeros2d = zeros2d = zeros((N, N)) if kijs is None: kijs = zeros2d self.kijs = kijs self.kwargs = {'kijs': kijs} self.T = T self.P = P self.V = V self.b = 0.0 self.bs = self.ais = self.zeros1d = self.a_alphas = self.da_alpha_dTs = self.d2a_alpha_dT2s = zeros2d[0] self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): self.bs = other.bs self.ais = other.ais self.b = other.b self.zeros1d = self.a_alphas = self.da_alpha_dTs = self.d2a_alpha_dT2s = other.zeros1d self.zeros2d = other.zeros2d def a_alphas_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` for the Ideal Gas EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = 0 Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] ''' return self.zeros1d def a_alpha_and_derivatives_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` and their first and second derivatives for the Ideal Gas EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = 0 .. math:: \frac{d a\alpha}{dT} = 0 .. math:: \frac{d^2 a\alpha}{dT^2} = 0 Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] ''' return self.zeros1d, self.zeros1d, self.zeros1d def a_alpha_and_derivatives(self, T, full=True, quick=True, pure_a_alphas=True): # Saves time if full: return 0.0, 0.0, 0.0 return 0.0 try: a_alpha_and_derivatives.__doc__ = GCEOSMIX.a_alpha_and_derivatives.__doc__ except: pass def fugacity_coefficients(self, Z): r'''Calculate and return the fugacity coefficients of the ideal-gas phase (0 by definition). Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- log_phis : float Log fugacity coefficient for each species, [-] ''' return self.zeros1d def dlnphis_dT(self, phase): r'''Calculate and return the temperature derivative of fugacity coefficients of the ideal-gas phase (0 by definition). Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dlnphis_dT : float Temperature derivatives of log fugacity coefficient for each species, [1/K] ''' return self.zeros1d def dlnphis_dP(self, phase): r'''Calculate and return the pressure derivative of fugacity coefficients of the ideal-gas phase (0 by definition). Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dlnphis_dP : float Pressure derivatives of log fugacity coefficient for each species, [1/Pa] ''' return self.zeros1d @property def a_alpha_ijs(self): return self.zeros2d try: a_alpha_ijs.__doc__ = GCEOSMIX.a_alpha_ijs.__doc__ except: pass @property def da_alpha_dT_ijs(self): return self.zeros2d try: da_alpha_dT_ijs.__doc__ = GCEOSMIX.da_alpha_dT_ijs.__doc__ except: pass @property def d2a_alpha_dT2_ijs(self): return self.zeros2d try: d2a_alpha_dT2_ijs.__doc__ = GCEOSMIX.d2a_alpha_dT2_ijs.__doc__ except: pass class RKMIX(EpsilonZeroMixingRules, GCEOSMIX, RK): r'''Class for solving the Redlich Kwong [1]_ [2]_ cubic equation of state for a mixture of any number of compounds. Subclasses :obj:`thermo.eos.RK` . Solves the EOS on initialization and calculates fugacities for all components in all phases. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P =\frac{RT}{V-b}-\frac{a}{V\sqrt{T}(V+b)} .. math:: a = \sum_i \sum_j z_i z_j {a}_{ij} .. math:: b = \sum_i z_i b_i .. math:: a_{ij} = (1-k_{ij})\sqrt{a_{i}a_{j}} .. math:: a_i =\left(\frac{R^2(T_{c,i})^{2}}{9(\sqrt[3]{2}-1)P_{c,i}} \right) =\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}} .. math:: b_i=\left( \frac{(\sqrt[3]{2}-1)}{3}\right)\frac{RT_{c,i}}{P_{c,i}} =\frac{0.08664\cdot R T_{c,i}}{P_{c,i}} Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] omegas : float, optional Acentric factors of all compounds - Not used in this equation of state!, [-] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = RKMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.V_l, eos.V_g (4.048414781e-05, 0.00070060605863) Notes ----- The PV solution for `T` is iterative. References ---------- .. [1] Walas, Stanley M. Phase Equilibria in Chemical Engineering. Butterworth-Heinemann, 1985. .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition. New York: McGraw-Hill Professional, 2000. ''' eos_pure = RK kwargs_keys = ('kijs',) model_id = 10002 def __init__(self, Tcs, Pcs, zs, omegas=None, kijs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in cmps] else: kijs = zeros((N, N)) self.kijs = kijs self.kwargs = {'kijs': kijs} self.T = T self.P = P self.V = V c1R2_c2R, c2R = self.c1R2_c2R, self.c2R if scalar: self.bs = bs = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*bs[i] for i in cmps] b = 0.0 for i in cmps: b += bs[i]*zs[i] else: self.bs = bs = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*bs b = float((bs*zs).sum()) self.b = self.delta = b self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): b = 0.0 if self.scalar: for bi, zi in zip(self.bs, self.zs): b += bi*zi else: b = float((self.bs*self.zs).sum()) self.b = self.delta = b def a_alphas_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` for the RK EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = \frac{a}{\sqrt{\frac{T}{Tc}}} Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] Examples -------- >>> eos = RKMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.a_alphas_vectorized(115) [0.1449810919468, 0.30019773677] ''' return RK_a_alphas_vectorized(T, self.Tcs, self.ais, a_alphas=[0.0]*self.N if self.scalar else zeros(self.N)) def a_alpha_and_derivatives_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` and their first and second derivatives for the RK EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = \frac{a}{\sqrt{\frac{T}{Tc}}} .. math:: \frac{d a\alpha}{dT} = - \frac{a}{2 T\sqrt{\frac{T}{Tc}}} .. math:: \frac{d^2 a\alpha}{dT^2} = \frac{3 a}{4 T^{2}\sqrt{\frac{T}{Tc}}} Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] Examples -------- >>> eos = RKMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.a_alpha_and_derivatives_vectorized(115) ([0.1449810919468, 0.30019773677], [-0.000630352573681, -0.00130520755121], [8.2219900915e-06, 1.7024446320e-05]) ''' N = self.N if self.scalar: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = [0.0]*N, [0.0]*N, [0.0]*N else: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = zeros(N), zeros(N), zeros(N) return RK_a_alpha_and_derivatives_vectorized(T, self.Tcs, self.ais, a_alphas=a_alphas, da_alpha_dTs=da_alpha_dTs, d2a_alpha_dT2s=d2a_alpha_dT2s) def solve_T(self, P, V, solution=None): if self.N == 1 and type(self) is RKMIX: self.Tc = self.Tcs[0] self.Pc = self.Pcs[0] self.a = self.ais[0] T = super(type(self).__mro__[-4], self).solve_T(P=P, V=V, solution=solution) del self.Tc del self.Pc del self.a return T else: return super(type(self).__mro__[-3], self).solve_T(P=P, V=V, solution=solution) @property def ddelta_dzs(self): r'''Helper method for calculating the composition derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial \delta}{\partial x_i}\right)_{T, P, x_{i\ne j}} = b_i Returns ------- ddelta_dzs : list[float] Composition derivative of `delta` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' return self.bs @property def ddelta_dns(self): r'''Helper method for calculating the mole number derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial \delta}{\partial n_i}\right)_{T, P, n_{i\ne j}} = (b_i - b) Returns ------- ddelta_dns : list[float] Mole number derivative of `delta` of each component, [m^3/mol^2] Notes ----- This derivative is checked numerically. ''' b = self.b if self.scalar: return [(bi - b) for bi in self.bs] return self.bs - b @property def d2delta_dzizjs(self): r'''Helper method for calculating the second composition derivatives (hessian) of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \delta}{\partial x_i\partial x_j}\right)_{T, P, x_{k\ne i,j}} = 0 Returns ------- d2delta_dzizjs : list[float] Second Composition derivative of `delta` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: return [[0.0]*N for i in range(N)] else: return zeros((N, N)) @property def d2delta_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \delta}{\partial n_i \partial n_j}\right)_{T, P, n_{k\ne i,j}} = 2b - b_i - b_j Returns ------- d2delta_dninjs : list[list[float]] Second mole number derivative of `delta` of each component, [m^3/mol^3] Notes ----- This derivative is checked numerically. ''' return self.d2b_dninjs @property def d3delta_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \delta}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 2(-3b + b_i + b_j + b_k) Returns ------- d3delta_dninjnks : list[list[list[float]]] Third mole number derivative of `delta` of each component, [m^3/mol^4] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[[0.0]*N for _ in range(N) ] for _ in range(N)] if self.scalar else zeros((N, N, N)) return RK_d3delta_dninjnks(self.b, self.bs, N, out) class PRMIX(GCEOSMIX, PR): r'''Class for solving the Peng-Robinson [1]_ [2]_ cubic equation of state for a mixture of any number of compounds. Subclasses `PR`. Solves the EOS on initialization and calculates fugacities for all components in all phases. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{v-b}-\frac{a\alpha(T)}{v(v+b)+b(v-b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}} .. math:: b_i=0.07780\frac{RT_{c,i}}{P_{c,i}} .. math:: \alpha(T)_i=[1+\kappa_i(1-\sqrt{T_{r,i}})]^2 .. math:: \kappa_i=0.37464+1.54226\omega_i-0.26992\omega^2_i Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = PRMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.V_l, eos.V_g (3.6257362939e-05, 0.00070066592313) >>> eos.fugacities_l, eos.fugacities_g ([793860.83821, 73468.552253], [436530.92470, 358114.63827]) Notes ----- For P-V initializations, a numerical solver is used to find T. References ---------- .. [1] Peng, Ding-Yu, and Donald B. Robinson. "A New Two-Constant Equation of State." Industrial & Engineering Chemistry Fundamentals 15, no. 1 (February 1, 1976): 59-64. doi:10.1021/i160057a011. .. [2] Robinson, Donald B., Ding-Yu Peng, and Samuel Y-K Chung. "The Development of the Peng - Robinson Equation and Its Application to Phase Equilibrium in a System Containing Methanol." Fluid Phase Equilibria 24, no. 1 (January 1, 1985): 25-41. doi:10.1016/0378-3812(85)87035-7. ''' eos_pure = PR nonstate_constants_specific = ('kappas', ) kwargs_keys = ('kijs',) model_id = 10200 def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in cmps] else: kijs = zeros((N, N)) self.kijs = kijs self.kwargs = {'kijs': kijs} self.T = T self.P = P self.V = V # optimization, unfortunately c1R2_c2R, c2R = self.c1R2_c2R, self.c2R # Also tried to store the inverse of Pcs, without success - slows it down self.scalar = scalar = type(Tcs) is list if scalar: self.bs = bs = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*bs[i] for i in cmps] self.kappas = [omega*(-0.26992*omega + 1.54226) + 0.37464 for omega in omegas] b = 0.0 for i in cmps: b += bs[i]*zs[i] else: self.bs = bs = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*bs self.kappas = omegas*(-0.26992*omegas + 1.54226) + 0.37464 b = float((bs*zs).sum()) self.b = b self.delta = 2.0*b self.epsilon = -b*b self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): self.kappas = other.kappas if self.scalar: b = 0.0 for bi, zi in zip(self.bs, self.zs): b += bi*zi else: b = float((self.bs*self.zs).sum()) self.b = b self.delta = 2.0*b self.epsilon = -b*b def a_alphas_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` for the PR EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = a \left(\kappa \left(- \frac{T^{0.5}}{Tc^{0.5}} + 1\right) + 1\right)^{2} Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] ''' return PR_a_alphas_vectorized(T, self.Tcs, self.ais, self.kappas, a_alphas=[0.0]*self.N if self.scalar else zeros(self.N)) def a_alpha_and_derivatives_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` and their first and second derivatives for the PR EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = a \left(\kappa \left(- \frac{T^{0.5}}{Tc^{0.5}} + 1\right) + 1\right)^{2} .. math:: \frac{d a\alpha}{dT} = - \frac{1.0 a \kappa}{T^{0.5} Tc^{0.5}} \left(\kappa \left(- \frac{T^{0.5}}{Tc^{0.5}} + 1\right) + 1\right) .. math:: \frac{d^2 a\alpha}{dT^2} = 0.5 a \kappa \left(- \frac{1}{T^{1.5} Tc^{0.5}} \left(\kappa \left(\frac{T^{0.5}}{Tc^{0.5}} - 1\right) - 1\right) + \frac{\kappa}{T^{1.0} Tc^{1.0}}\right) Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] ''' N = self.N if self.scalar: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = [0.0]*N, [0.0]*N, [0.0]*N else: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = zeros(N), zeros(N), zeros(N) return PR_a_alpha_and_derivatives_vectorized(T, self.Tcs, self.ais, self.kappas, a_alphas=a_alphas, da_alpha_dTs=da_alpha_dTs, d2a_alpha_dT2s=d2a_alpha_dT2s) @property def d3a_alpha_dT3(self): r'''Method to calculate approximately the third temperature derivative of `a_alpha` for the PR EOS. A rigorous calculation has not been implemented. Parameters ---------- T : float Temperature, [K] Returns ------- d3a_alpha_dT3 : float Third temperature derivative :math:`a \alpha`, [J^2/mol^2/Pa/K^3] ''' try: return self._d3a_alpha_dT3 except AttributeError: pass tot = 0.0 zs = self.zs vs = self.d3a_alpha_dT3_vectorized(self.T) for i in range(self.N): tot += zs[i]*vs[i] self._d3a_alpha_dT3 = tot return tot def d3a_alpha_dT3_vectorized(self, T): r'''Method to calculate the third temperature derivative of pure-component `a_alphas` for the PR EOS. This vectorized implementation is added for extra speed. Parameters ---------- T : float Temperature, [K] Returns ------- d3a_alpha_dT3s : list[float] Third temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K^3] ''' ais, kappas, Tcs = self.ais, self.kappas, self.Tcs T_inv = 1.0/T N = self.N d3a_alpha_dT3s = [0.0]*N if self.scalar else zeros(N) for i in range(N): kappa = kappas[i] x0 = 1.0/Tcs[i] x1 = sqrt(T*x0) v = (-ais[i]*0.75*kappa*(kappa*x0 - x1*(kappa*(x1 - 1.0) - 1.0)*T_inv)*T_inv*T_inv) d3a_alpha_dT3s[i] = v return d3a_alpha_dT3s def fugacity_coefficients(self, Z): r'''Literature formula for calculating fugacity coefficients for each species in a mixture. Verified numerically. Applicable to most derivatives of the Peng-Robinson equation of state as well. Called by :obj:`fugacities <GCEOSMIX.fugacities>` on initialization, or by a solver routine which is performing a flash calculation. .. math:: \ln \hat \phi_i = \frac{B_i}{B}(Z-1)-\ln(Z-B) + \frac{A}{2\sqrt{2}B} \left[\frac{B_i}{B} - \frac{2}{a\alpha}\sum_i y_i(a\alpha)_{ij}\right] \ln\left[\frac{Z + (1+\sqrt{2})B}{Z-(\sqrt{2}-1)B}\right] .. math:: A = \frac{(a\alpha)P}{R^2 T^2} .. math:: B = \frac{b P}{RT} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- log_phis : float Log fugacity coefficient for each species, [-] ''' a_alpha = self.a_alpha # a_alpha_ijs = self.a_alpha_ijs T_inv = 1.0/self.T bs, b = self.bs, self.b P_T = self.P*T_inv A = a_alpha*P_T*R2_inv*T_inv B = b*P_T*R_inv # The two log terms need to use a complex log; typically these are # calculated at "liquid" volume solutions which are unstable # and cannot exist try: x0 = log(Z - B) except ValueError: # less than zero x0 = 0.0 root_two_B = B*root_two two_root_two_B = root_two_B + root_two_B ZB = Z + B try: x4 = A*log((ZB + root_two_B)/(ZB - root_two_B)) except ValueError: # less than zero x4 = 0.0 a_alpha_j_rows = self._a_alpha_j_rows try: t50 = 2.0*x4/(a_alpha*two_root_two_B) except ZeroDivisionError: return [0.0]*self.N t51 = (x4 + (Z - 1.0)*two_root_two_B)/(b*two_root_two_B) if self.scalar: return [bs[i]*t51 - x0 - t50*a_alpha_j_rows[i] for i in range(self.N)] else: return bs*t51 - x0 - t50*a_alpha_j_rows def dlnphis_dT(self, phase): r'''Formula for calculating the temperature derivaitve of log fugacity coefficients for each species in a mixture for the Peng-Robinson equation of state. Verified numerically. .. math:: \left(\frac{\partial \ln \phi_i}{\partial T}\right)_{P, nj \ne i} Parameters ---------- phase : str One of 'l' or 'g', [-] Returns ------- dlnphis_dT : float Temperature derivatives of log fugacity coefficient for each species, [1/K] Notes ----- This expression was derived using SymPy and optimized with the `cse` technique. ''' zs = self.zs if phase == 'g': Z = self.Z_g dZ_dT = self.dZ_dT_g else: Z = self.Z_l dZ_dT = self.dZ_dT_l bs, b = self.bs, self.b T_inv = 1.0/self.T A = self.a_alpha*self.P*R2_inv*T_inv*T_inv B = b*self.P*R_inv*T_inv x2 = T_inv*T_inv x3 = R_inv x4 = self.P*b*x3 x5 = x2*x4 x8 = x4*T_inv x10 = self.a_alpha x11 = 1.0/self.a_alpha x12 = self.da_alpha_dT x13 = root_two x14 = 1.0/b x15 = x13 + 1.0 # root_two plus 1 x16 = Z + x15*x8 x17 = x13 - 1.0 # root two minus one x18 = x16/(x17*x8 - Z) x19 = log(-x18) x13x14 = x13*x14 x10x13x14_4 = 0.25*x10*x13x14 x19x3 = x19*x3 x24 = x10x13x14_4*x19x3*x2 x25 = 0.25*x12*x13x14*x19x3*T_inv x26 = x10x13x14_4*x3*T_inv*(-dZ_dT + x15*x5 - x18*(dZ_dT + x17*x5))/(x16) x50 = -0.5*x13x14*x19x3*T_inv x51 = -x11*x12 x52 = (dZ_dT + x5)/(x8 - Z) x53 = 2.0*x11 x54 = x52/x50 x55 = x24 - x25 + x26 x56 = dZ_dT/x55 x57 = x53*x55 x58 = x14*(dZ_dT - x55) x59 = x57/x50 + x51 # Composition stuff a_alpha_j_rows = self._a_alpha_j_rows da_alpha_dT_j_rows = self._da_alpha_dT_j_rows d_lnphis_dTs = [x52 + bs[i]*x58 + x50*(x59*a_alpha_j_rows[i] + da_alpha_dT_j_rows[i]) for i in range(self.N)] return d_lnphis_dTs def dlnphis_dP(self, phase): r'''Generic formula for calculating the pressure derivaitve of log fugacity coefficients for each species in a mixture for the Peng-Robinson EOS. Verified numerically. .. math:: \left(\frac{\partial \ln \phi_i}{\partial P}\right)_{T, nj \ne i} Parameters ---------- phase : str One of 'l' or 'g', [-] Returns ------- dlnphis_dP : float Pressure derivatives of log fugacity coefficient for each species, [1/Pa] Notes ----- This expression was derived using SymPy and optimized with the `cse` technique. ''' zs = self.zs if phase == 'l': Z, dZ_dP = self.Z_l, self.dZ_dP_l else: Z, dZ_dP = self.Z_g, self.dZ_dP_g a_alpha = self.a_alpha bs, b = self.bs, self.b T_inv = 1.0/self.T x2 = 1.0/b x6 = b*R_inv*T_inv x8 = self.P*x6 x9 = (dZ_dP - x6)/(x8 - Z) x13 = Z + root_two_p1*x8 x15 = (a_alpha*root_two*x2*R_inv*T_inv*(dZ_dP + root_two_p1*x6 + x13*(dZ_dP - root_two_m1*x6)/(root_two_m1*x8 - Z))/(4.0*x13)) x16 = dZ_dP + x15 a_alpha_j_rows = self._a_alpha_j_rows x50 = -2.0/a_alpha d_lnphi_dPs = [] for i in range(self.N): x3 = bs[i]*x2 x10 = x50*a_alpha_j_rows[i] # d_lnphi_dP = dZ_dP*x3 + x15*(x10 + x3) + x9 d_lnphi_dP = x16*x3 + x15*x10 + x9 d_lnphi_dPs.append(d_lnphi_dP) return d_lnphi_dPs def d_lnphi_dzs_analytical0(self, Z, zs): # TODO try to follow "B.5.2.1 Derivatives of Fugacity Coefficient with Respect to Mole Fraction" # "Development of an Equation-of-State Thermal Flooding Simulator" N = self.N cmps_m1 = range(N-1) a_alpha = self.a_alpha a_alpha_ijs = self.a_alpha_ijs T2 = self.T*self.T b = self.b A = a_alpha*self.P/(R2*T2) B = b*self.P/(R*self.T) B2 = B*B Z2 = Z*Z A_B = A/B ZmB = Z - B dZ_dA = (B - Z)/(3.0*Z2 - 2.0*(1.0 - B)*Z + (A - 2.0*B - 3.0*B2)) # 2*(3.0*B + 1)*Z may or may not have Z # Simple phase stability-testing algorithm in the reduction method. dZ_dB = ((-Z2 + 2*(3.0*B + 1)*Z) + (A - 2.0*B - 3.0*B2))/( 3.0*Z2 - 2.0*(1.0 - B)*Z + (A - 2.0*B - 3.0*B2)) Sis = [] for i in range(N): tot = 0.0 for j in range(N): tot += zs[j]*a_alpha_ijs[i][j] Sis.append(tot) Sais = [val/a_alpha for val in Sis] Sbis = [bi/b for bi in self.bs] Snc = Sis[-1] const_A = 2.0*self.P/(R2*T2) dA_dzis = [const_A*(Si - Snc) for Si in Sis[:-1]] const_B = 2.0*self.P/(R*self.T) bnc = self.bs[-1] dB_dzis = [const_B*(self.bs[i] - bnc) for i in range(N)] # Probably wrong, missing dZ_dzs = [dZ_dA*dA_dz_i + dZ_dB*dB_dzi for dA_dz_i, dB_dzi in zip(dA_dzis, dB_dzis)] t1 = (Z2 + 2.0*Z*B - B2) t2 = clog((Z + (root_two + 1.)*B)/(Z - (root_two - 1.)*B)).real t3 = t2*-A/(B*two_root_two) t4 = -t2/(two_root_two*B) a_nc = a_alpha_ijs[-1][-1] # no idea if this is right # Have some converns of what Snc really is dlnphis_dzs_all = [] for i in range(self.N): Diks = [-A_B*(2.0*Sais[i] - Sbis[i])*(Z*dB_dzis[k] - B*dZ_dzs[k])/t1 for k in cmps_m1] Ciks = [t3*(2.0*(a_alpha_ijs[i][k] - a_nc)/a_alpha - 4.0*Sais[i]*(Sais[k] - Snc) + Sbis[i]*(Sbis[k] - Snc)) for k in cmps_m1] x5 = t4*(2.0*Sais[i] - Sbis[i]) Biks = [x5*(dA_dzis[k] - A_B*dB_dzis[k]) for k in cmps_m1 ] Aiks = [Sbis[i]*(dZ_dzs[k] - (Sbis[k] - Snc)*(Z - 1.0)) - (dZ_dzs[k] - dB_dzis[k])/ZmB for k in cmps_m1 ] dlnphis_dzs = [Aik + Bik + Cik + Dik for Aik, Bik, Cik, Dik in zip(Aiks, Biks, Ciks, Diks)] dlnphis_dzs_all.append(dlnphis_dzs) return dlnphis_dzs_all def d_lnphi_dzs_basic_num(self, Z, zs): all_diffs = [] try: if self.G_dep_l < self.G_dep_g: lnphis_ref = self.lnphis_l else: lnphis_ref = self.lnphis_g except: lnphis_ref = self.lnphis_l if hasattr(self, 'G_dep_l') else self.lnphis_g for i in range(len(zs)): zs2 = list(zs) dz = 1e-7#zs2[i]*3e- zs2[i] = zs2[i]+dz # sum_one = sum(zs2) # zs2 = normalize(zs2) eos2 = self.to_TP_zs(T=self.T, P=self.P, zs=zs2) diffs = [] for j in range(len(zs)): try: dlnphis = (eos2.lnphis_g[j] - lnphis_ref[j])/dz except: dlnphis = (eos2.lnphis_l[j] - lnphis_ref[j])/dz diffs.append(dlnphis) all_diffs.append(diffs) import numpy as np return np.array(all_diffs).T.tolist() def d_lnphi_dzs_numdifftools(self, Z, zs): import numpy as np import numdifftools as nd def lnphis_from_zs(zs2): if isinstance(zs2, np.ndarray): zs2 = zs2.tolist() zs2 = normalize(zs2) # Last row suggests the normalization breaks everything! # zs2 = normalize(zs2) # if Z == self.Z_l try: return np.array(self.to_TP_zs(T=self.T, P=self.P, zs=zs2).lnphis_l) except: return np.array(self.to_TP_zs(T=self.T, P=self.P, zs=zs2).lnphis_g) Jfun_partial = nd.Jacobian(lnphis_from_zs, step=1e-4, order=2, method='central') return Jfun_partial(zs) def dlnphis_dzs(self, Z): r'''Calculate and return the mole fraction derivaitves of log fugacity coefficients for each species in a mixture. This formula is specific to the Peng-Robinson equation of state. .. math:: \left(\frac{\partial \ln \phi_i}{\partial z_i}\right)_{P, z_{j \ne i}} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- dlnphis_dzs : list[list[float]] Mole fraction derivatives of log fugacity coefficient for each species (such that the mole fractions do not sum to 1), [-] Notes ----- This formula is from [1]_ but is validated to match the generic implementation. Examples -------- >>> kijs = [[0, 0.00076, 0.00171], [0.00076, 0, 0.00061], [0.00171, 0.00061, 0]] >>> eos = PRMIX(Tcs=[469.7, 507.4, 540.3], zs=[0.8168, 0.1501, 0.0331], omegas=[0.249, 0.305, 0.349], Pcs=[3.369E6, 3.012E6, 2.736E6], T=322.29, P=101325, kijs=kijs) >>> eos.dlnphis_dzs(eos.Z_l) [[0.009938069276, 0.0151503498382, 0.018297235797], [-0.038517738793, -0.05958926042, -0.068438990795], [-0.07057106923, -0.10363920720, -0.14116283024]] References ---------- .. [1] Chang, Yih-Bor. "Development and Application of an Equation of State Compositional Simulator" 1990. https://repositories.lib.utexas.edu/handle/2152/80585. ''' T, P, zs = self.T, self.P, self.zs T2 = T*T T_inv = 1.0/T RT_inv = R_inv*T_inv bs, b = self.bs, self.b a_alpha = self.a_alpha a_alpha_ijs = self.a_alpha_ijs a_alphas = self.a_alphas a_alpha_j_rows = self.a_alpha_j_rows N = len(zs) b2 = b*b b_inv = 1.0/b b2_inv = b_inv*b_inv a_alpha2 = a_alpha*a_alpha A = a_alpha*P*RT_inv*RT_inv B = b*P*RT_inv B_inv = 1.0/B C = 1.0/(Z - B) Zm1 = Z - 1.0 G = (Z + (1.0 + root_two)*B)/(Z + (1.0 - root_two)*B) t4 = 2.0/a_alpha t5 = -A/(two_root_two*B) Eis = [t5*(t4*a_alpha_j_rows[i] - bs[i]*b_inv) for i in range(N)] # ln_phis = [] # for i in range(N): # ln_phis.append(log(C) + Dis[i] + Eis[i]*log(G)) # return ln_phis # Bis = [bi*P/(R*T) for bi in bs] # maybe with a 2 constant? t6 = P*RT_inv dB_dxks = [t6*bk for bk in bs] # THIS IS WRONG - the sum changes w.r.t (or does it?) # Believed right now? const = (P+P)*RT_inv*RT_inv dA_dxks = [const*term_i for term_i in a_alpha_j_rows] dF_dZ_inv = 1.0/(3.0*Z*Z - 2.0*Z*(1.0 - B) + (A - 3.0*B*B - 2.0*B)) t15 = (A - 2.0*B - 3.0*B*B + 2.0*(3.0*B + 1.0)*Z - Z*Z) BmZ = (B - Z) dZ_dxs = [(BmZ*dA_dxks[i] + t15*dB_dxks[i])*dF_dZ_inv for i in range(N)] # function only of k ZmB = Z - B t20 = -1.0/(ZmB*ZmB) dC_dxs = [t20*(dZ_dxs[k] - dB_dxks[k]) for k in range(N)] dD_dxs = [] # dD_dxs = [[0.0]*N for _ in cmps] t55s = [b*dZ_dxs[k] - bs[k]*Zm1 for k in range(N)] for i in range(N): # dD_dxs_i = dD_dxs[i] b_term_ratio = bs[i]*b2_inv dD_dxs.append([b_term_ratio*t55s[k] for k in range(N)]) # for k in range(N): # dD_dxs_i[k] = b_term_ratio*t55s[k] # dD_dxs = [] # for i in range(N): # term = bs[i]/(b*b)*(b*dZ_dxs[i] - b*(Z - 1.0)) # dD_dxs.append(term) # ? Believe this is the only one with multi indexes? t1 = 1.0/(two_root_two*a_alpha*b*B) t2 = t1*A/(a_alpha*b) t50s = [B*dA_dxks[k] - A*dB_dxks[k] for k in range(N)] # problem is in here, tested numerically b_two = b + b t32 = 2.0*a_alpha*b2 t33 = 4.0*b2 t34 = t1*B_inv*a_alpha t35 = -t1*B_inv*b_two # Symmetric matrix! dE_dxs = [[0.0]*N for _ in range(N)] # TODO - makes little sense. Too many i indexes. for i in range(N): zm_aim_tot = a_alpha_j_rows[i] t30 = t34*bs[i] + t35*zm_aim_tot t31 = t33*zm_aim_tot dE_dxs_i = [] a_alpha_ijs_i = a_alpha_ijs[i] for k in range(0, i+1): # Sign was wrong in article - should be a plus second = t2*(t31*a_alpha_j_rows[k] - t32*a_alpha_ijs_i[k] - bs[i]*bs[k]*a_alpha2) dE_dxs[i][k] = dE_dxs[k][i] = t30*t50s[k] + second # dE_dxs_i.append(t1*(first + second)) # dE_dxs.append(dE_dxs_i) t59 = (Z + (1.0 - root_two)*B) t60 = two_root_two/(t59*t59) dG_dxs = [t60*(Z*dB_dxks[k] - B*dZ_dxs[k]) for k in range(N)] G_inv = 1.0/G logG = log(G) C_inv = 1.0/C dlnphis_dxs = [] # dlnphis_dxs = [[0.0]*N for _ in range(N)] t61s = [C_inv*dC_dxi for dC_dxi in dC_dxs] for i in range(N): dD_dxs_i = dD_dxs[i] dE_dxs_i = dE_dxs[i] E_G = Eis[i]*G_inv # dlnphis_dxs_i = dlnphis_dxs[i] dlnphis_dxs_i = [t61s[k] + dD_dxs_i[k] + logG*dE_dxs_i[k] + E_G*dG_dxs[k] for k in range(N)] dlnphis_dxs.append(dlnphis_dxs_i) # return dlnphis_dxs return dlnphis_dxs#, dZ_dxs, dA_dxks, dB_dxks, dC_dxs, dD_dxs, dE_dxs, dG_dxs @property def ddelta_dzs(self): r'''Helper method for calculating the composition derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial \delta}{\partial x_i}\right)_{T, P, x_{i\ne j}} = 2 b_i Returns ------- ddelta_dzs : list[float] Composition derivative of `delta` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' N = self.N return PR_ddelta_dzs(self.bs, N, out=[0.0]*N if self.scalar else zeros(N)) @property def ddelta_dns(self): r'''Helper method for calculating the mole number derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial \delta}{\partial n_i}\right)_{T, P, n_{i\ne j}} = 2 (b_i - b) Returns ------- ddelta_dns : list[float] Mole number derivative of `delta` of each component, [m^3/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N return PR_ddelta_dns(self.bs, self.b, N, out=[0.0]*N if self.scalar else zeros(N)) @property def d2delta_dzizjs(self): r'''Helper method for calculating the second composition derivatives (hessian) of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \delta}{\partial x_i\partial x_j}\right)_{T, P, x_{k\ne i,j}} = 0 Returns ------- d2delta_dzizjs : list[float] Second Composition derivative of `delta` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: return [[0.0]*N for i in range(N)] return zeros((N, N)) @property def d2delta_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \delta}{\partial n_i \partial n_j}\right)_{T, P, n_{k\ne i,j}} = 4b - 2b_i - 2b_j Returns ------- d2delta_dninjs : list[list[float]] Second mole number derivative of `delta` of each component, [m^3/mol^3] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[0.0]*N for _ in range(N)] if self.scalar else zeros((N, N)) return PR_d2delta_dninjs(self.b, self.bs, N, out) @property def d3delta_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \delta}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 4(-3b + b_i + b_j + b_k) Returns ------- d3delta_dninjnks : list[list[list[float]]] Third mole number derivative of `delta` of each component, [m^3/mol^4] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[[0.0]*N for _ in range(N) ] for _ in range(N)] if self.scalar else zeros((N, N, N)) return PR_d3delta_dninjnks(self.b, self.bs, N, out) @property def depsilon_dzs(self): r'''Helper method for calculating the composition derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial \epsilon}{\partial x_i}\right)_{T, P, x_{i\ne j}} = -2 b_i\cdot b Returns ------- depsilon_dzs : list[float] Composition derivative of `epsilon` of each component, [m^6/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N return PR_depsilon_dzs(self.b, self.bs, N, out=[0.0]*N if self.scalar else zeros(N)) @property def depsilon_dns(self): r'''Helper method for calculating the mole number derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial \epsilon}{\partial n_i}\right)_{T, P, n_{i\ne j}} = 2b(b - b_i) Returns ------- depsilon_dns : list[float] Composition derivative of `epsilon` of each component, [m^6/mol^3] Notes ----- This derivative is checked numerically. ''' N = self.N return PR_depsilon_dns(self.b, self.bs, N, out=[0.0]*N if self.scalar else zeros(N)) @property def d2epsilon_dzizjs(self): r'''Helper method for calculating the second composition derivatives (hessian) of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \epsilon}{\partial x_i \partial x_j}\right)_{T, P, x_{k\ne i,j}} = 2 b_i b_j Returns ------- d2epsilon_dzizjs : list[list[float]] Second composition derivative of `epsilon` of each component, [m^6/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[0.0]*N for _ in range(N)] if self.scalar else zeros((N, N)) return PR_d2epsilon_dzizjs(self.b, self.bs, N, out) @property def d2epsilon_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \epsilon}{\partial n_i n_j}\right)_{T, P, n_{k\ne i,j}} = -2b(2b - b_i - b_j) - 2(b - b_i)(b - b_j) Returns ------- d2epsilon_dninjs : list[list[float]] Second mole number derivative of `epsilon` of each component, [m^6/mol^4] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[0.0]*N for _ in range(N)] if self.scalar else zeros((N, N)) return PR_d2epsilon_dninjs(self.b, self.bs, N, out) @property def d3epsilon_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \epsilon}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 24b^2 - 12b(b_i + b_j + b_k) + 4(b_i b_j + b_i b_k + b_j b_k) Returns ------- d3epsilon_dninjnks : list[list[list[float]]] Third mole number derivative of `epsilon` of each component, [m^6/mol^5] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[[0.0]*N for _ in range(N) ] for _ in range(N)] if self.scalar else zeros((N, N, N)) return PR_d3epsilon_dninjnks(self.b, self.bs, N, out) def solve_T(self, P, V, quick=True, solution=None): if self.N == 1 and type(self) is PRMIX: self.Tc = self.Tcs[0] self.Pc = self.Pcs[0] self.kappa = self.kappas[0] self.a = self.ais[0] T = super(type(self).__mro__[-4], self).solve_T(P=P, V=V, solution=solution) del self.Tc del self.Pc del self.kappa del self.a return T else: return super(type(self).__mro__[-3], self).solve_T(P=P, V=V, solution=solution) class PRMIXTranslated(PRMIX): r'''Class for solving the Peng-Robinson [1]_ [2]_ translated cubic equation of state for a mixture of any number of compounds. Solves the EOS on initialization and calculates fugacities for all components in all phases. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{v + c - b} - \frac{a\alpha(T)}{(v+c)(v + c + b)+b(v + c - b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}} .. math:: b_i=0.07780\frac{RT_{c,i}}{P_{c,i}} .. math:: \alpha(T)_i=[1+\kappa_i(1-\sqrt{T_{r,i}})]^2 .. math:: \kappa_i=0.37464+1.54226\omega_i-0.26992\omega^2_i Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] cs : list[float], optional Volume translation parameters; always zero in the original implementation, [m^3/mol] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = PRMIXTranslated(T=115, P=1E6, cs=[-4.4e-6, -4.35e-6], Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.2, 0.8], kijs=[[0,0.03],[0.03,0]]) >>> eos.V_l, eos.V_g (3.9079056337e-05, 0.00060231393016) >>> eos.fugacities_l, eos.fugacities_g ([442838.8615, 108854.48589], [184396.972, 565531.7709]) Notes ----- For P-V initializations, a numerical solver is used to find T. References ---------- .. [1] Peng, Ding-Yu, and Donald B. Robinson. "A New Two-Constant Equation of State." Industrial & Engineering Chemistry Fundamentals 15, no. 1 (February 1, 1976): 59-64. doi:10.1021/i160057a011. .. [2] Robinson, Donald B., Ding-Yu Peng, and Samuel Y-K Chung. "The Development of the Peng - Robinson Equation and Its Application to Phase Equilibrium in a System Containing Methanol." Fluid Phase Equilibria 24, no. 1 (January 1, 1985): 25-41. doi:10.1016/0378-3812(85)87035-7. ''' translated = True eos_pure = PRTranslated mix_kwargs_to_pure = {'cs': 'c'} kwargs_linear = ('cs',) fugacity_coefficients = GCEOSMIX.fugacity_coefficients dlnphis_dT = GCEOSMIX.dlnphis_dT dlnphis_dP = GCEOSMIX.dlnphis_dP d_lnphi_dzs = GCEOSMIX.dlnphis_dzs P_max_at_V = GCEOSMIX.P_max_at_V model_id = 10202 # All the b derivatives happen to work out to be the same, and are checked numerically solve_T = GCEOS.solve_T kwargs_keys = ('kijs', 'cs') def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, cs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in range(N)] else: kijs = zeros((N, N)) self.kijs = kijs self.T = T self.P = P self.V = V c2R, c1R2_c2R = self.c2R, self.c1R2_c2R if scalar: b0s = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*b0s[i] for i in cmps] else: b0s = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*b0s if cs is None: if scalar: cs = [0.0]*N else: cs = zeros(N) if scalar: self.kappas = [omega*(-0.26992*omega + 1.54226) + 0.37464 for omega in omegas] b0, c = 0.0, 0.0 for i in range(N): b0 += b0s[i]*zs[i] c += cs[i]*zs[i] bs = [b0s[i] - cs[i] for i in range(N)] else: self.kappas = omegas*(-0.26992*omegas + 1.54226) + 0.37464 b0 = float((b0s*zs).sum()) c = float((cs*zs).sum()) bs = b0s - cs self.kwargs = {'kijs': kijs, 'cs': cs} self.cs = cs self.b0s = b0s self.bs = bs self.c = c self.b = b = b0 - c self.delta = 2.0*(c + b0) self.epsilon = -b0*b0 + c*(c + b0 + b0) self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): self.cs = cs = other.cs self.kappas = other.kappas zs = self.zs self.b0s = b0s = other.b0s if self.scalar: b0, c = 0.0, 0.0 for i in range(self.N): b0 += b0s[i]*zs[i] c += cs[i]*zs[i] else: b0 = float((b0s*zs).sum()) c = float((cs*zs).sum()) self.c = c self.b = b0 - c self.delta = 2.0*(c + b0) self.epsilon = -b0*b0 + c*(c + b0 + b0) # Very important to be calculated exactly the same way as the other implementation @property def ddelta_dzs(self): r'''Helper method for calculating the composition derivatives of `delta`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial \delta}{\partial x_i}\right)_{T, P, x_{i\ne j}} = 2 (c_i + b^0_i) Returns ------- ddelta_dzs : list[float] Composition derivative of `delta` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' N = self.N return PR_translated_ddelta_dzs(self.b0s, self.cs, N, [0.0]*N if self.scalar else zeros(N)) # Zero in both cases d2delta_dzizjs = PRMIX.d2delta_dzizjs d3delta_dzizjzks = PRMIX.d3delta_dzizjzks @property def ddelta_dns(self): r'''Helper method for calculating the mole number derivatives of `delta`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial \delta}{\partial n_i}\right)_{T, P, n_{i\ne j}} = 2 (c_i + b^0_i) - \delta Returns ------- ddelta_dns : list[float] Mole number derivative of `delta` of each component, [m^3/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N return PR_translated_ddelta_dns(self.b0s, self.cs, self.delta, N, [0.0]*N if self.scalar else zeros(N)) @property def d2delta_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `delta`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial^2 \delta}{\partial n_i \partial n_j}\right)_{T, P, n_{k\ne i,j}} = 2\left(\delta - b^0_i - b^0_j - c_i - c_j \right) Returns ------- d2delta_dninjs : list[list[float]] Second mole number derivative of `delta` of each component, [m^3/mol^3] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[0.0]*N for _ in range(N)] if self.scalar else zeros((N, N)) return PR_translated_d2delta_dninjs(self.b0s, self.cs, self.b, self.c, self.delta, N, out) @property def d3delta_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `delta`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial^3 \delta}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 4\left(b^0_i + b^0_j + b^0_k + c_i + c_j + c_k \right) - 6 \delta Returns ------- d3delta_dninjnks : list[list[list[float]]] Third mole number derivative of `delta` of each component, [m^3/mol^4] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[[0.0]*N for _ in range(N)] for _ in range(N)] if self.scalar else zeros((N, N, N)) return PR_translated_d3delta_dninjnks(self.b0s, self.cs, self.delta, N, out) @property def depsilon_dzs(self): r'''Helper method for calculating the composition derivatives of `epsilon`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial \epsilon}{\partial x_i}\right)_{T, P, x_{i\ne j}} = c_i(2b^0_i + c) + c(2b^0_i + c_i) - 2b^0 b^0_i Returns ------- depsilon_dzs : list[float] Composition derivative of `epsilon` of each component, [m^6/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N return PR_translated_depsilon_dzs(self.epsilon, self.c, self.b, self.b0s, self.cs, N, [0.0]*N if self.scalar else zeros(N)) @property def depsilon_dns(self): r'''Helper method for calculating the mole number derivatives of `epsilon`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial \epsilon}{\partial n_i}\right)_{T, P, n_{i\ne j}} = 2b^0(b^0 - b^0_i) - c(2b^0 - 2b_i^0 + c - c_i) - (c - c_i)(2b^0 + c) Returns ------- depsilon_dns : list[float] Composition derivative of `epsilon` of each component, [m^6/mol^3] Notes ----- This derivative is checked numerically. ''' epsilon, c, b = self.epsilon, self.c, self.b N, b0s, cs = self.N, self.b0s, self.cs return PR_translated_depsilon_dns(epsilon, c, b, b0s, cs, N, out=([0.0]*N if self.scalar else zeros(N))) @property def d2epsilon_dzizjs(self): r'''Helper method for calculating the second composition derivatives (hessian) of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \epsilon}{\partial x_i \partial x_j}\right)_{T, P, x_{k\ne i,j}} = -2 b^0_i b^0_j + 2b^0_i c_j + 2b^0_j c_i + 2c_i c_j Returns ------- d2epsilon_dzizjs : list[list[float]] Second composition derivative of `epsilon` of each component, [m^6/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[0.0]*N for _ in range(N)] if self.scalar else zeros((N, N)) return PR_translated_d2epsilon_dzizjs(self.b0s, self.cs, N=N, out=out) d3epsilon_dzizjzks = GCEOSMIX.d3epsilon_dzizjzks # Zeros @property def d2epsilon_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \epsilon}{\partial n_i n_j}\right)_{T, P, n_{k\ne i,j}} = -2b^0(2b^0 - b_i^0 - b_j^0) + c(4b^0 - 2b^0_i - 2b^0_j + 2c - c_i - c_j) -2(b^0 - b_i^0)(b^0 - b^0_j) + (c - c_i)(2b^0 - 2b^0_j - c_j + c) + (c - c_j)(2b^0 - 2b^0_i - c_i + c) + (2b^0 + c)(2c-c_i - c_j) Returns ------- d2epsilon_dninjs : list[list[float]] Second mole number derivative of `epsilon` of each component, [m^6/mol^4] Notes ----- This derivative is checked numerically. ''' # Not trusted yet - numerical check does not have enough digits N = self.N out = [[0.0]*N for _ in range(N)] if self.scalar else zeros((N, N)) return PR_translated_d2epsilon_dninjs(self.b0s, self.cs, self.b, self.c, N, out=out) @property def d3epsilon_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \epsilon}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 4b^0(3b^0 - b_i^0 - b_j^0 - b_k^0) -2c(6b^0 - 2(b_i^0 + b_j^0 + b_k^0) + 3c - (c_i + c_j + c_k)) +2(b^0-b_i^0)(2b^0 - b_j^0 - b_k^0) + 2(b^0 - b^0_j)(2b^0 - b_i^0 - b_k^0) +2(b^0-b^0_k)(2b^0 - b^0_i-b^0_j) -(c-c_i)(4b^0 - 2b^0_j - 2b^0_k + 2c - c_j - c_k) -(c-c_j)(4b^0 - 2b^0_i - 2b^0_k + 2c - c_i - c_k) -(c-c_k)(4b^0 - 2b^0_j - 2b^0_i + 2c - c_j - c_i) -2(c + 2b^0)(3c - c_i - c_j - c_k) -(2c - c_i - c_j)(2b^0 + c - 2b^0_k - c_k) -(2c - c_i - c_k)(2b^0 + c - 2b^0_j - c_j) -(2c - c_j - c_k)(2b^0 + c - 2b^0_i - c_i) Returns ------- d3epsilon_dninjnks : list[list[list[float]]] Third mole number derivative of `epsilon` of each component, [m^6/mol^5] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[[0.0]*N for _ in range(N)] for _ in range(N)] if self.scalar else zeros((N, N, N)) return PR_translated_d3epsilon_dninjnks(self.b0s, self.cs, self.b, self.c, self.epsilon, N, out) class PRMIXTranslatedPPJP(PRMIXTranslated): r'''Class for solving the Pina-Martinez, Privat, Jaubert, and Peng revision of the Peng-Robinson equation of state. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{v + c - b} - \frac{a\alpha(T)}{(v+c)(v + c + b)+b(v + c - b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}} .. math:: b_i=0.07780\frac{RT_{c,i}}{P_{c,i}} .. math:: \alpha(T)_i=[1+\kappa_i(1-\sqrt{T_{r,i}})]^2 .. math:: \kappa_i=0.3919 + 1.4996 \omega - 0.2721\omega^2 + 0.1063\omega^3 Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] cs : list[float], optional Volume translation parameters, [m^3/mol] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = PRMIXTranslatedPPJP(T=115, P=1E6, cs=[-4.4e-6, -4.35e-6], Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.2, 0.8], kijs=[[0,0.03],[0.03,0]]) >>> eos.V_l, eos.V_g (3.8989032701e-05, 0.00059686183724) >>> eos.fugacities_l, eos.fugacities_g ([444791.13707, 104520.280997], [184782.600238, 563352.147]) Notes ----- For P-V initializations, a numerical solver is used to find T. References ---------- .. [1] Pina-Martinez, Andrés, Romain Privat, Jean-Noël Jaubert, and Ding-Yu Peng. "Updated Versions of the Generalized Soave α-Function Suitable for the Redlich-Kwong and Peng-Robinson Equations of State." Fluid Phase Equilibria, December 7, 2018. https://doi.org/10.1016/j.fluid.2018.12.007. ''' eos_pure = PRTranslatedPPJP mix_kwargs_to_pure = {'cs': 'c'} kwargs_linear = ('cs',) kwargs_keys = ('kijs', 'cs') model_id = 10207 def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, cs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in cmps] else: kijs = zeros((N, N)) self.kijs = kijs self.T = T self.P = P self.V = V c2R, c1R2_c2R = self.c2R, self.c1R2_c2R if scalar: b0s = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*b0s[i] for i in cmps] else: b0s = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*b0s if cs is None: if scalar: cs = [0.0]*N else: cs = zeros(N) if scalar: self.kappas = [omega*(omega*(0.1063*omega - 0.2721) + 1.4996) + 0.3919 for omega in omegas] b0, c = 0.0, 0.0 for i in range(N): b0 += b0s[i]*zs[i] c += cs[i]*zs[i] bs = [b0s[i] - cs[i] for i in range(N)] else: self.kappas = omegas*(omegas*(0.1063*omegas - 0.2721) + 1.4996) + 0.3919 b0 = float((b0s*zs).sum()) c = float((cs*zs).sum()) bs = b0s - cs self.kwargs = {'kijs': kijs, 'cs': cs} self.cs = cs self.b0s = b0s self.bs = bs self.c = c self.b = b = b0 - c self.delta = 2.0*(c + b0) self.epsilon = -b0*b0 + c*(c + b0 + b0) self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() class PRMIXTranslatedConsistent(Twu91_a_alpha, PRMIXTranslated): r'''Class for solving the volume translated Le Guennec, Privat, and Jaubert revision of the Peng-Robinson equation of state according to [1]_. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{v + c - b} - \frac{a\alpha(T)}{(v+c)(v + c + b)+b(v + c - b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}} .. math:: b_i=0.07780\frac{RT_{c,i}}{P_{c,i}} .. math:: \alpha_i = \left(\frac{T}{T_{c}}\right)^{c_{3} \left(c_{2} - 1\right)} e^{c_{1} \left(- \left(\frac{T}{T_{c}} \right)^{c_{2} c_{3}} + 1\right)} If `c` is not provided, they are estimated as: .. math:: c =\frac{R T_c}{P_c}(0.0198\omega - 0.0065) If `alpha_coeffs` is not provided, the parameters `L` and `M` are estimated from the acentric factor as follows: .. math:: L = 0.1290\omega^2 + 0.6039\omega + 0.0877 .. math:: M = 0.1760\omega^2 - 0.2600\omega + 0.8884 Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] cs : list[float], optional Volume translation parameters, [m^3/mol] alpha_coeffs : list[tuple(float[3])], optional Coefficients L, M, N (also called C1, C2, C3) of TWU 1991 form, [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = PRMIXTranslatedConsistent(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.2, 0.8], kijs=[[0,0.03],[0.03,0]]) >>> eos.V_l, eos.V_g (3.675235812e-05, 0.00059709319879) >>> eos.fugacities_l, eos.fugacities_g ([443454.9336, 106184.004057], [184122.74082, 563037.785]) Notes ----- For P-V initializations, a numerical solver is used to find T. References ---------- .. [1] Le Guennec, Yohann, Romain Privat, and Jean-Noël Jaubert. "Development of the Translated-Consistent Tc-PR and Tc-RK Cubic Equations of State for a Safe and Accurate Prediction of Volumetric, Energetic and Saturation Properties of Pure Compounds in the Sub- and Super-Critical Domains." Fluid Phase Equilibria 429 (December 15, 2016): 301-12. https://doi.org/10.1016/j.fluid.2016.09.003. ''' eos_pure = PRTranslatedConsistent kwargs_linear = ('cs', 'alpha_coeffs') mix_kwargs_to_pure = {'cs': 'c', 'alpha_coeffs': 'alpha_coeffs'} kwargs_keys = ('kijs', 'alpha_coeffs', 'cs') model_id = 10203 # There is an updated set of correlations - which means a revision flag is needed # Analysis of the Combinations of Property Data That Are Suitable for a Safe Estimation of Consistent Twu α-Function Parameters: Updated Parameter Values for the Translated-Consistent tc-PR and tc-RK Cubic Equations of State def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, cs=None, alpha_coeffs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in cmps] else: kijs = zeros((N, N)) self.kijs = kijs self.T = T self.P = P self.V = V c1R2_c2R, c2R = self.c1R2_c2R, self.c2R if scalar: b0s = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*b0s[i] for i in cmps] else: b0s = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*b0s if cs is None: if scalar: cs = [R*Tcs[i]/Pcs[i]*(0.0198*min(max(omegas[i], -0.01), 1.48) - 0.0065) for i in range(N)] else: cs = R*Tcs/Pcs*(0.0198*npmin(npmax(omegas, -0.01), 1.48) - 0.0065) if alpha_coeffs is None: alpha_coeffs = [] for i in range(N): o = min(max(omegas[i], -0.01), 1.48) L = o*(0.1290*o + 0.6039) + 0.0877 M = o*(0.1760*o - 0.2600) + 0.8884 alpha_coeffs.append((L, M, 2.0)) self.kwargs = {'kijs': kijs, 'alpha_coeffs': alpha_coeffs, 'cs': cs} self.alpha_coeffs = alpha_coeffs self.cs = cs if scalar: b0, c = 0.0, 0.0 for i in range(N): b0 += b0s[i]*zs[i] c += cs[i]*zs[i] bs = [b0s[i] - cs[i] for i in range(N)] else: b0 = float((b0s*zs).sum()) c = float((cs*zs).sum()) bs = b0s - cs self.b0s = b0s self.bs = bs self.c = c self.b = b = b0 - c self.delta = 2.0*(c + b0) self.epsilon = -b0*b0 + c*(c + b0 + b0) self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): self.cs = cs = other.cs self.alpha_coeffs = other.alpha_coeffs zs = self.zs self.b0s = b0s = other.b0s if self.scalar: b0, c = 0.0, 0.0 for i in range(self.N): b0 += b0s[i]*zs[i] c += cs[i]*zs[i] else: b0 = float((zs*b0s).sum()) c = float((zs*cs).sum()) self.c = c self.b = b0 - c self.delta = 2.0*(c + b0) self.epsilon = -b0*b0 + c*(c + b0 + b0) # Very important to be calculated exactly the same way as the other implementation class SRKMIX(EpsilonZeroMixingRules, GCEOSMIX, SRK): r'''Class for solving the Soave-Redlich-Kwong cubic equation of state for a mixture of any number of compounds. Solves the EOS on initialization and calculates fugacities for all components in all phases. The implemented method here is :obj:`fugacity_coefficients <SRKMIX.fugacity_coefficients>`, which implements the formula for fugacity coefficients in a mixture as given in [1]_. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{V-b} - \frac{a\alpha(T)}{V(V+b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i =\left(\frac{R^2(T_{c,i})^{2}}{9(\sqrt[3]{2}-1)P_{c,i}} \right) =\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}} .. math:: b_i =\left( \frac{(\sqrt[3]{2}-1)}{3}\right)\frac{RT_{c,i}}{P_{c,i}} =\frac{0.08664\cdot R T_{c,i}}{P_{c,i}} .. math:: \alpha(T)_i = \left[1 + m_i\left(1 - \sqrt{\frac{T}{T_{c,i}}}\right)\right]^2 .. math:: m_i = 0.480 + 1.574\omega_i - 0.176\omega_i^2 Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> SRK_mix = SRKMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> SRK_mix.V_l, SRK_mix.V_g (4.1047569614e-05, 0.0007110158049) Notes ----- For P-V initializations, a numerical solver is used to find T. References ---------- .. [1] Soave, Giorgio. "Equilibrium Constants from a Modified Redlich-Kwong Equation of State." Chemical Engineering Science 27, no. 6 (June 1972): 1197-1203. doi:10.1016/0009-2509(72)80096-4. .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition. New York: McGraw-Hill Professional, 2000. .. [3] Walas, Stanley M. Phase Equilibria in Chemical Engineering. Butterworth-Heinemann, 1985. ''' eos_pure = SRK nonstate_constants_specific = ('ms',) kwargs_keys = ('kijs', ) model_id = 10100 ddelta_dzs = RKMIX.ddelta_dzs ddelta_dns = RKMIX.ddelta_dns d2delta_dzizjs = RKMIX.d2delta_dzizjs d2delta_dninjs = RKMIX.d2delta_dninjs d3delta_dninjnks = RKMIX.d3delta_dninjnks def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in cmps] else: kijs = zeros((N, N)) self.kijs = kijs self.kwargs = {'kijs': kijs} self.T = T self.P = P self.V = V if self.scalar: self.ais = [self.c1*R2*Tc*Tc/Pc for Tc, Pc in zip(Tcs, Pcs)] self.bs = [self.c2*R*Tc/Pc for Tc, Pc in zip(Tcs, Pcs)] ms = [omega*(1.574 - 0.176*omega) + 0.480 for omega in omegas] b = sum(bi*zi for bi, zi in zip(self.bs, self.zs)) else: Tc_Pc_ratio = Tcs/Pcs self.ais = self.c1R2*Tcs*Tc_Pc_ratio self.bs = bs = self.c2R*Tc_Pc_ratio ms = omegas*(1.574 - 0.176*omegas) + 0.480 b = float((bs*zs).sum()) self.b = b self.ms = ms self.delta = self.b self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): self.ms = other.ms if self.scalar: self.b = b = sum([bi*zi for bi, zi in zip(self.bs, self.zs)]) else: self.b = b = float((self.bs*self.zs).sum()) self.delta = b def a_alphas_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` for the SRK EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = a \left(m \left(- \sqrt{\frac{T}{Tc}} + 1\right) + 1\right)^{2} Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] ''' return SRK_a_alphas_vectorized(T, self.Tcs, self.ais, self.ms, a_alphas=[0.0]*self.N if self.scalar else zeros(self.N)) def a_alpha_and_derivatives_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` and their first and second derivatives for the SRK EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = a \left(m \left(- \sqrt{\frac{T}{Tc}} + 1\right) + 1\right)^{2} .. math:: \frac{d a\alpha}{dT} = \frac{a m}{T} \sqrt{\frac{T}{Tc}} \left(m \left(\sqrt{\frac{T}{Tc}} - 1\right) - 1\right) .. math:: \frac{d^2 a\alpha}{dT^2} = \frac{a m \sqrt{\frac{T}{Tc}}}{2 T^{2}} \left(m + 1\right) Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] ''' N = self.N if self.scalar: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = [0.0]*N, [0.0]*N, [0.0]*N else: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = zeros(N), zeros(N), zeros(N) return SRK_a_alpha_and_derivatives_vectorized(T, self.Tcs, self.ais, self.ms, a_alphas=a_alphas, da_alpha_dTs=da_alpha_dTs, d2a_alpha_dT2s=d2a_alpha_dT2s) def fugacity_coefficients(self, Z): r'''Literature formula for calculating fugacity coefficients for each species in a mixture. Verified numerically. Applicable to most derivatives of the SRK equation of state as well. Called by :obj:`fugacities <GCEOSMIX.fugacities>` on initialization, or by a solver routine which is performing a flash calculation. .. math:: \ln \hat \phi_i = \frac{B_i}{B}(Z-1) - \ln(Z-B) + \frac{A}{B} \left[\frac{B_i}{B} - \frac{2}{a \alpha}\sum_i y_i(a\alpha)_{ij} \right]\ln\left(1+\frac{B}{Z}\right) .. math:: A=\frac{a\alpha P}{R^2T^2} .. math:: B = \frac{bP}{RT} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- log_phis : float Log fugacity coefficient for each species, [-] ''' N = self.N return SRK_lnphis(self.T, self.P, Z, self.b, self.a_alpha, self.bs, self.a_alpha_j_rows, N, lnphis=[0.0]*N if self.scalar else zeros(N)) def dlnphis_dT(self, phase): r'''Formula for calculating the temperature derivaitve of log fugacity coefficients for each species in a mixture for the SRK equation of state. Verified numerically. .. math:: \left(\frac{\partial \ln \phi_i}{\partial T}\right)_{P, nj \ne i} Parameters ---------- phase : str One of 'l' or 'g', [-] Returns ------- dlnphis_dT : float Temperature derivatives of log fugacity coefficient for each species, [1/K] Notes ----- This expression was derived using SymPy and optimized with the `cse` technique. ''' zs = self.zs if phase == 'g': Z = self.Z_g dZ_dT = self.dZ_dT_g else: Z = self.Z_l dZ_dT = self.dZ_dT_l da_alpha_dT_j_rows = self._da_alpha_dT_j_rows N = self.N P, bs, b = self.P, self.bs, self.b T_inv = 1.0/self.T A = self.a_alpha*P*R2_inv*T_inv*T_inv B = b*P*R_inv*T_inv x2 = T_inv*T_inv x4 = P*b*R_inv x6 = x4*T_inv x8 = self.a_alpha x9 = 1.0/x8 x10 = self.da_alpha_dT x11 = 1.0/b x12 = 1.0/Z x13 = x12*x6 + 1.0 x14 = log(x13) x19 = x11*x14*x2*R_inv*x8 x20 = x10*x11*x14*R_inv*T_inv x21 = P*x12*x2*x8*(dZ_dT*x12 + T_inv)/(R2*x13) x50 = -x11*x14*R_inv*T_inv x51 = -2.0*x10 x52 = (dZ_dT + x2*x4)/(x6 - Z) # Composition stuff d_lnphis_dTs = [] a_alpha_j_rows = self.a_alpha_j_rows for i in range(N): x7 = a_alpha_j_rows[i] x15 = (x50*(x51*x7*x9 + 2.0*da_alpha_dT_j_rows[i]) + x52) x16 = bs[i]*x11 x18 = -x16 + 2.0*x7*x9 d_lhphi_dT = dZ_dT*x16 + x15 + x18*(x19 - x20 + x21) d_lnphis_dTs.append(d_lhphi_dT) return d_lnphis_dTs def dlnphis_dP(self, phase): r'''Generic formula for calculating the pressure derivaitve of log fugacity coefficients for each species in a mixture for the SRK EOS. Verified numerically. .. math:: \left(\frac{\partial \ln \phi_i}{\partial P}\right)_{T, nj \ne i} Parameters ---------- phase : str One of 'l' or 'g', [-] Returns ------- dlnphis_dP : float Pressure derivatives of log fugacity coefficient for each species, [1/Pa] Notes ----- This expression was derived using SymPy and optimized with the `cse` technique. ''' zs = self.zs if phase == 'l': Z, dZ_dP = self.Z_l, self.dZ_dP_l else: Z, dZ_dP = self.Z_g, self.dZ_dP_g a_alpha = self.a_alpha N = self.N bs, b = self.bs, self.b T_inv = 1.0/self.T a_alpha_j_rows = self._a_alpha_j_rows RT_inv = T_inv*R_inv x0 = Z x1 = dZ_dP x2 = 1.0/b x4 = b*RT_inv x5 = self.P*x4 x6 = (dZ_dP - x4)/(x5 - Z) x7 = a_alpha x9 = 1./Z x10 = a_alpha*x9*(self.P*dZ_dP*x9 - 1.0)*RT_inv*RT_inv/((x5*x9 + 1.0)) x50 = 2.0/a_alpha d_lnphi_dPs = [] for i in range(N): x8 = x50*a_alpha_j_rows[i] x3 = bs[i]*x2 d_lnphi_dP = dZ_dP*x3 + x10*(x8 - x3) + x6 d_lnphi_dPs.append(d_lnphi_dP) return d_lnphi_dPs class SRKMIXTranslated(SRKMIX): r'''Class for solving the volume translated Soave-Redlich-Kwong cubic equation of state for a mixture of any number of compounds. Subclasses :obj:`SRKMIX`. Solves the EOS on initialization and calculates fugacities for all components in all phases. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{V + c - b} - \frac{a\alpha(T)}{(V + c)(V + c + b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i =\left(\frac{R^2(T_{c,i})^{2}}{9(\sqrt[3]{2}-1)P_{c,i}} \right) =\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}} .. math:: b_i =\left( \frac{(\sqrt[3]{2}-1)}{3}\right)\frac{RT_{c,i}}{P_{c,i}} =\frac{0.08664\cdot R T_{c,i}}{P_{c,i}} .. math:: \alpha(T)_i = \left[1 + m_i\left(1 - \sqrt{\frac{T}{T_{c,i}}}\right)\right]^2 .. math:: m_i = 0.480 + 1.574\omega_i - 0.176\omega_i^2 Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] cs : list[float], optional Volume translation parameters; always zero in the original implementation, [m^3/mol] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = SRKMIXTranslated(T=115, P=1E6, cs=[-4.4e-6, -4.35e-6], Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.2, 0.8], kijs=[[0,0.03],[0.03,0]]) >>> eos.V_l, eos.V_g (4.35928920e-05, 0.00060927202) Notes ----- For P-V initializations, a numerical solver is used to find T. ''' fugacity_coefficients = GCEOSMIX.fugacity_coefficients dlnphis_dT = GCEOSMIX.dlnphis_dT dlnphis_dP = GCEOSMIX.dlnphis_dP d_lnphi_dzs = GCEOSMIX.dlnphis_dzs P_max_at_V = GCEOSMIX.P_max_at_V solve_T = GCEOS.solve_T model_id = 10101 eos_pure = SRKTranslated translated = True mix_kwargs_to_pure = {'cs': 'c'} kwargs_linear = ('cs',) kwargs_keys = ('kijs', 'cs') def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, cs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if cs is None: if scalar: cs = [0.0]*N else: cs = zeros(N) if kijs is None: if scalar: kijs = [[0.0]*N for i in cmps] else: kijs = zeros((N, N)) self.kijs = kijs self.kwargs = {'kijs': kijs, 'cs': cs} self.T = T self.P = P self.V = V c2R, c1R2_c2R = self.c2R, self.c1R2_c2R if scalar: b0s = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*b0s[i] for i in cmps] self.ms = [0.480 + omega*(1.574 - 0.176*omega) for omega in omegas] else: b0s = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*b0s self.ms = 0.480 + omegas*(1.574 - 0.176*omegas) self.cs = cs if scalar: b0, c = 0.0, 0.0 for i in range(N): b0 += b0s[i]*zs[i] c += cs[i]*zs[i] bs = [b0s[i] - cs[i] for i in range(N)] else: b0 = float((b0s*zs).sum()) c = float((cs*zs).sum()) bs = b0s - cs self.b0s = b0s self.bs = bs self.c = c self.b = b = b0 - c self.delta = c + c + b0 self.epsilon = c*(b0 + c) self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): self.cs = cs = other.cs self.ms = other.ms zs = self.zs self.b0s = b0s = other.b0s if self.scalar: b0, c = 0.0, 0.0 for i in range(self.N): b0 += b0s[i]*zs[i] c += cs[i]*zs[i] else: b0 = float((b0s*zs).sum()) c = float((cs*zs).sum()) self.c = c self.b = b0 - c self.delta = c + c + b0 self.epsilon = c*(b0 + c) @property def ddelta_dzs(self): r'''Helper method for calculating the composition derivatives of `delta`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial \delta}{\partial x_i}\right)_{T, P, x_{i\ne j}} = 2 (c_i + b^0_i) Returns ------- ddelta_dzs : list[float] Composition derivative of `delta` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' b0s, cs = self.b0s, self.cs if self.scalar: return [(2.0*cs[i] + b0s[i]) for i in range(self.N)] return 2.0*cs + b0s # Zero in both cases d2delta_dzizjs = PRMIX.d2delta_dzizjs d3delta_dzizjzks = PRMIX.d3delta_dzizjzks @property def ddelta_dns(self): r'''Helper method for calculating the mole number derivatives of `delta`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial \delta}{\partial n_i}\right)_{T, P, n_{i\ne j}} = (2 c_i + b^0_i) - \delta Returns ------- ddelta_dns : list[float] Mole number derivative of `delta` of each component, [m^3/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N return SRK_translated_ddelta_dns(self.b0s, self.cs, self.delta, N, out=[0.0]*N if self.scalar else zeros(N)) @property def d2delta_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `delta`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial^2 \delta}{\partial n_i \partial n_j}\right)_{T, P, n_{k\ne i,j}} = \left(\2(b^0 - c_i - c_j) + 4c - b_i^0 - b_j^0\right) Returns ------- d2delta_dninjs : list[list[float]] Second mole number derivative of `delta` of each component, [m^3/mol^3] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[0.0]*N for _ in range(N)] if self.scalar else zeros((N, N)) return SRK_translated_d2delta_dninjs(self.b0s, self.cs, self.b, self.c, self.delta, N, out) @property def d3delta_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `delta`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial^3 \delta}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = -6b^0 + 2(b^0_i + b^0_j + b^0_k) + -12c +4(c_i + c_j + c_k) Returns ------- d3delta_dninjnks : list[list[list[float]]] Third mole number derivative of `delta` of each component, [m^3/mol^4] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[[0.0]*N for _ in range(N)] for _ in range(N)] if self.scalar else zeros((N, N, N)) return SRK_translated_d3delta_dninjnks(self.b0s, self.cs, self.b, self.c, self.delta, N, out) @property def depsilon_dzs(self): r'''Helper method for calculating the composition derivatives of `epsilon`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial \epsilon}{\partial x_i}\right)_{T, P, x_{i\ne j}} = c_i b^0 + 2c c_i + b_i c Returns ------- depsilon_dzs : list[float] Composition derivative of `epsilon` of each component, [m^6/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N out = [0.0]*N if self.scalar else zeros(N) return SRK_translated_depsilon_dzs(self.b0s, self.cs, self.b, self.c, N, out) @property def depsilon_dns(self): r'''Helper method for calculating the mole number derivatives of `epsilon`. Note this is independent of the phase. :math:`b^0` refers to the original `b` parameter not involving any translation. .. math:: \left(\frac{\partial \epsilon}{\partial n_i}\right)_{T, P, n_{i\ne j}} = -b^0(c - c_i) - c(b^0 - b_i^0) - 2c(c - c_i) Returns ------- depsilon_dns : list[float] Composition derivative of `epsilon` of each component, [m^6/mol^3] Notes ----- This derivative is checked numerically. ''' N = self.N return SRK_translated_depsilon_dns(self.b0s, self.cs, self.b, self.c, N, out=[0.0]*N if self.scalar else zeros(N)) @property def d2epsilon_dzizjs(self): r'''Helper method for calculating the second composition derivatives (hessian) of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \epsilon}{\partial x_i \partial x_j}\right)_{T, P, x_{k\ne i,j}} = b^0_i c_j + b^0_j c_i + 2c_i c_j Returns ------- d2epsilon_dzizjs : list[list[float]] Second composition derivative of `epsilon` of each component, [m^6/mol^2] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[0.0]*N for _ in range(N)] if self.scalar else zeros((N, N)) return SRK_translated_d2epsilon_dzizjs(self.b0s, self.cs, self.b, self.c, N, out=out) d3epsilon_dzizjzks = GCEOSMIX.d3epsilon_dzizjzks # Zeros @property def d2epsilon_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \epsilon}{\partial n_i n_j}\right)_{T, P, n_{k\ne i,j}} = b^0(2c - c_i - c_j) + c(2b^0 - b_i^0 - b_j^0) + 2c(2c - c_i - c_j) +(b^0 - b^0_i)(c - c_j) + (b^0 - b_j^0)(c - c_i) + 2(c - c_i)(c - c_j) Returns ------- d2epsilon_dninjs : list[list[float]] Second mole number derivative of `epsilon` of each component, [m^6/mol^4] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[0.0]*N for _ in range(N)] if self.scalar else zeros((N, N)) return SRK_translated_d2epsilon_dninjs(self.b0s, self.cs, self.b, self.c, N, out) @property def d3epsilon_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `epsilon`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \epsilon}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = -2b^0(3c - c_i - c_j - c_k) - 2c(3b^0 - b^0_i - b^0_j - b^0_k) - 4c(3c - c_i - c_j - c_k) -(b^0 - b^0_i)(2c - c_j - c_k) -(b^0 - b^0_j)(2c - c_i - c_k) -(b^0 - b^0_k)(2c - c_i - c_j) - (c - c_i)(2b^0 - b^0_j - b^0_k) - (c - c_j)(2b^0 - b^0_i - b^0_k) - (c - c_k)(2b^0 - b^0_i - b^0_j) -2(c - c_i)(2c - c_j - c_k) -2(c - c_j)(2c - c_i - c_k) -2(c - c_k)(2c - c_i - c_j) Returns ------- d3epsilon_dninjnks : list[list[list[float]]] Third mole number derivative of `epsilon` of each component, [m^6/mol^5] Notes ----- This derivative is checked numerically. ''' N = self.N out = [[[0.0]*N for _ in range(N)] for _ in range(N)] if self.scalar else zeros((N, N, N)) return SRK_translated_d3epsilon_dninjnks(self.b0s, self.cs, self.b, self.c, self.epsilon, N, out) class SRKMIXTranslatedConsistent(Twu91_a_alpha, SRKMIXTranslated): r'''Class for solving the volume translated Le Guennec, Privat, and Jaubert revision of the SRK equation of state according to [1]_. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{V + c - b} - \frac{a\alpha(T)}{(V + c)(V + c + b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: \alpha_i = \left(\frac{T}{T_{c,i}}\right)^{c_{3} \left(c_{2} - 1\right)} e^{c_{1} \left(- \left(\frac{T}{T_{c,i}} \right)^{c_{2} c_{3}} + 1\right)} .. math:: b = \sum_i z_i b_i .. math:: a_i =\left(\frac{R^2(T_{c,i})^{2}}{9(\sqrt[3]{2}-1)P_{c,i}} \right) =\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}} .. math:: b_i =\left( \frac{(\sqrt[3]{2}-1)}{3}\right)\frac{RT_{c,i}}{P_{c,i}} =\frac{0.08664\cdot R T_{c,i}}{P_{c,i}} If `cs` is not provided, they are estimated as: .. math:: c =\frac{R T_c}{P_c}(0.0172\omega - 0.0096) If `alpha_coeffs` is not provided, the parameters `L` and `M` are estimated from each of the acentric factors as follows: .. math:: L = 0.0947\omega^2 + 0.6871\omega + 0.1508 .. math:: M = 0.1615\omega^2 - 0.2349\omega + 0.8876 Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] cs : list[float], optional Volume translation parameters, [m^3/mol] alpha_coeffs : list[list[float]] Coefficients for :obj:`thermo.eos_alpha_functions.Twu91_a_alpha`, [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = SRKMIXTranslatedConsistent(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.2, 0.8], kijs=[[0,0.03],[0.03,0]]) >>> eos.V_l, eos.V_g (3.591044498e-05, 0.0006020501621) Notes ----- For P-V initializations, a numerical solver is used to find T. References ---------- .. [1] Le Guennec, Yohann, Romain Privat, and Jean-Noël Jaubert. "Development of the Translated-Consistent Tc-PR and Tc-RK Cubic Equations of State for a Safe and Accurate Prediction of Volumetric, Energetic and Saturation Properties of Pure Compounds in the Sub- and Super-Critical Domains." Fluid Phase Equilibria 429 (December 15, 2016): 301-12. https://doi.org/10.1016/j.fluid.2016.09.003. ''' eos_pure = SRKTranslatedConsistent mix_kwargs_to_pure = {'cs': 'c', 'alpha_coeffs': 'alpha_coeffs'} kwargs_linear = ('cs', 'alpha_coeffs') kwargs_keys = ('kijs', 'alpha_coeffs', 'cs') model_id = 10102 def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, cs=None, alpha_coeffs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in range(N)] else: kijs = zeros((N, N)) self.kijs = kijs self.T = T self.P = P self.V = V c2R, c1R2_c2R = self.c2R, self.c1R2_c2R if scalar: b0s = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*b0s[i] for i in cmps] else: b0s = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*b0s if cs is None: if scalar: cs = [R*Tcs[i]/Pcs[i]*(0.0172*min(max(omegas[i], -0.01), 1.46) + 0.0096) for i in range(N)] else: cs = R*Tcs/Pcs*(0.0172*npmin(npmax(omegas, -0.01), 1.46) + 0.0096) if alpha_coeffs is None: alpha_coeffs = [] for i in range(N): o = min(max(omegas[i], -0.01), 1.46) L = o*(0.0947*o + 0.6871) + 0.1508 M = o*(0.1615*o - 0.2349) + 0.8876 alpha_coeffs.append((L, M, 2.0)) self.kwargs = {'kijs': kijs, 'alpha_coeffs': alpha_coeffs, 'cs': cs} self.alpha_coeffs = alpha_coeffs self.cs = cs if scalar: b0, c = 0.0, 0.0 for i in range(N): b0 += b0s[i]*zs[i] c += cs[i]*zs[i] bs = [b0s[i] - cs[i] for i in range(N)] else: b0 = float((b0s*zs).sum()) c = float((cs*zs).sum()) bs = b0s - cs self.b0s = b0s self.bs = bs self.c = c self.b = b = b0 - c self.delta = c + c + b0 self.epsilon = c*(b0 + c) self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): self.cs = cs = other.cs self.alpha_coeffs = other.alpha_coeffs zs = self.zs self.b0s = b0s = other.b0s if self.scalar: b0, c = 0.0, 0.0 for i in range(self.N): b0 += b0s[i]*zs[i] c += cs[i]*zs[i] else: b0 = float((b0s*zs).sum()) c = float((cs*zs).sum()) self.c = c self.b = b0 - c self.delta = c + c + b0 self.epsilon = c*(b0 + c) class MSRKMIXTranslated(Soave_1979_a_alpha, SRKMIXTranslatedConsistent): r'''Class for solving the volume translated Soave (1980) alpha function, revision of the Soave-Redlich-Kwong equation of state for a pure compound according to [1]_. Uses two fitting parameters `N` and `M` to more accurately fit the vapor pressure of pure species. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{V + c - b} - \frac{a\alpha(T)}{(V + c)(V + c + b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: \alpha(T)_i = 1 + (1 - T_{r,i})(M + \frac{N}{T_{r,i}}) .. math:: b = \sum_i z_i b_i .. math:: a_i =\left(\frac{R^2(T_{c,i})^{2}}{9(\sqrt[3]{2}-1)P_{c,i}} \right) =\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}} .. math:: b_i =\left( \frac{(\sqrt[3]{2}-1)}{3}\right)\frac{RT_{c,i}}{P_{c,i}} =\frac{0.08664\cdot R T_{c,i}}{P_{c,i}} This is an older correlation that offers lower accuracy on many properties which were sacrificed to obtain the vapor pressure accuracy. The alpha function of this EOS does not meet any of the consistency requriements for alpha functions. Coefficients can be found in [2]_, or estimated with the method in [3]_. The estimation method in [3]_ works as follows, using the acentric factor and true critical compressibility: .. math:: M = 0.4745 + 2.7349(\omega Z_c) + 6.0984(\omega Z_c)^2 .. math:: N = 0.0674 + 2.1031(\omega Z_c) + 3.9512(\omega Z_c)^2 An alternate estimation scheme is provided in [1]_, which provides analytical solutions to calculate the parameters `M` and `N` from two points on the vapor pressure curve, suggested as 10 mmHg and 1 atm. This is used as an estimation method here if the parameters are not provided, and the two vapor pressure points are obtained from the original SRK equation of state. Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] cs : list[float], optional Volume translation parameters, [m^3/mol] alpha_coeffs : list[list[float]] Coefficients for :obj:`thermo.eos_alpha_functions.Soave_1979_a_alpha`, [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = MSRKMIXTranslated(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.2, 0.8], kijs=[[0,0.03],[0.03,0]]) >>> eos.V_l, eos.V_g (3.9222990198e-05, 0.00060438075638) Notes ----- For P-V initializations, a numerical solver is used to find T. References ---------- .. [1] Soave, G. "Rigorous and Simplified Procedures for Determining the Pure-Component Parameters in the Redlich—Kwong—Soave Equation of State." Chemical Engineering Science 35, no. 8 (January 1, 1980): 1725-30. https://doi.org/10.1016/0009-2509(80)85007-X. .. [2] Sandarusi, Jamal A., Arthur J. Kidnay, and Victor F. Yesavage. "Compilation of Parameters for a Polar Fluid Soave-Redlich-Kwong Equation of State." Industrial & Engineering Chemistry Process Design and Development 25, no. 4 (October 1, 1986): 957-63. https://doi.org/10.1021/i200035a020. .. [3] Valderrama, Jose O., Héctor De la Puente, and Ahmed A. Ibrahim. "Generalization of a Polar-Fluid Soave-Redlich-Kwong Equation of State." Fluid Phase Equilibria 93 (February 11, 1994): 377-83. https://doi.org/10.1016/0378-3812(94)87021-7. ''' kwargs_keys = ('kijs', 'alpha_coeffs', 'cs') eos_pure = MSRKTranslated model_id = 10103 def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, cs=None, alpha_coeffs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: kijs = [[0.0]*N for i in cmps] self.kijs = kijs self.T = T self.P = P self.V = V c1R2, c2R = self.c1*R2, self.c2*R self.ais = [c1R2*Tcs[i]*Tcs[i]/Pcs[i] for i in cmps] b0s = [c2R*Tcs[i]/Pcs[i] for i in cmps] if cs is None: cs = [0.0]*N # TODO peneloux? Inherit? if alpha_coeffs is None: alpha_coeffs = [] for i in cmps: alpha_coeffs.append(MSRKTranslated.estimate_MN(Tcs[i], Pcs[i], omegas[i], cs[i])) self.kwargs = {'kijs': kijs, 'alpha_coeffs': alpha_coeffs, 'cs': cs} self.alpha_coeffs = alpha_coeffs self.cs = cs b0, c = 0.0, 0.0 for i in cmps: b0 += b0s[i]*zs[i] c += cs[i]*zs[i] self.b0s = b0s self.bs = [b0s[i] - cs[i] for i in cmps] self.c = c self.b = b = b0 - c self.delta = c + c + b0 self.epsilon = c*(b0 + c) self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() class PSRK(Mathias_Copeman_poly_a_alpha, PSRKMixingRules, SRKMIXTranslated): r'''Class for solving the Predictive Soave-Redlich-Kwong [1]_ equation of state for a mixture of any number of compounds. Solves the EOS on initialization. Two of `T`, `P`, and `V` are needed to solve the EOS. .. warning:: This class is not complete! Fugacities and their derivatives among others are not yet implemented. .. math:: P = \frac{RT}{V-b} - \frac{a\alpha(T)}{V(V+b)} .. math:: b = \sum_i z_i b_i .. math:: a_i =\left(\frac{R^2(T_{c,i})^{2}}{9(\sqrt[3]{2}-1)P_{c,i}} \right) =\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}} .. math:: b_i =\left( \frac{(\sqrt[3]{2}-1)}{3}\right)\frac{RT_{c,i}}{P_{c,i}} =\frac{0.08664\cdot R T_{c,i}}{P_{c,i}} Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] alpha_coeffs : list[list[float]] Coefficients for :obj:`thermo.eos_alpha_functions.Mathias_Copeman_poly_a_alpha`, [-] ge_model : :obj:`thermo.activity.GibbsExcess` object Excess Gibbs free energy model; to match the `PSRK` model, this is a :obj:`thermo.unifac.UNIFAC` object, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] cs : list[float], optional Volume translation parameters; always zero in the original implementation, [m^3/mol] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, equimolar CO2, n-hexane: >>> from thermo.unifac import UNIFAC, PSRKIP, PSRKSG >>> Tcs = [304.2, 507.4] >>> Pcs = [7.37646e6, 3.014419e6] >>> omegas = [0.2252, 0.2975] >>> zs = [0.5, 0.5] >>> Mathias_Copeman_coeffs = [[-1.7039, 0.2515, 0.8252, 1.0], [2.9173, -1.4411, 1.1061, 1.0]] >>> T = 313. >>> P = 1E6 >>> ge_model = UNIFAC.from_subgroups(T=T, xs=zs, chemgroups=[{117: 1}, {1:2, 2:4}], subgroups=PSRKSG, interaction_data=PSRKIP, version=0) >>> eos = PSRK(Tcs=Tcs, Pcs=Pcs, omegas=omegas, zs=zs, ge_model=ge_model, alpha_coeffs=Mathias_Copeman_coeffs, T=T, P=P) >>> eos PSRK(Tcs=[304.2, 507.4], Pcs=[7376460.0, 3014419.0], omegas=[0.2252, 0.2975], kijs=[[0.0, 0.0], [0.0, 0.0]], alpha_coeffs=[[-1.7039, 0.2515, 0.8252, 1.0], [2.9173, -1.4411, 1.1061, 1.0]], cs=[0.0, 0.0], ge_model=UNIFAC(T=313.0, xs=[0.5, 0.5], rs=[1.3, 4.4998000000000005], qs=[0.982, 3.856], Qs=[0.848, 0.54, 0.982], vs=[[0, 2], [0, 4], [1, 0]], psi_abc=([[0.0, 0.0, 919.8], [0.0, 0.0, 919.8], [-38.672, -38.672, 0.0]], [[0.0, 0.0, -3.9132], [0.0, 0.0, -3.9132], [0.8615, 0.8615, 0.0]], [[0.0, 0.0, 0.0046309], [0.0, 0.0, 0.0046309], [-0.0017906, -0.0017906, 0.0]]), version=0), zs=[0.5, 0.5], T=313.0, P=1000000.0) >>> eos.phase, eos.V_l, eos.V_g ('l/g', 0.000110889753959, 0.00197520225546) Notes ----- References ---------- .. [1] Holderbaum, T., and J. Gmehling. "PSRK: A Group Contribution Equation of State Based on UNIFAC.” Fluid Phase Equilibria 70, no. 2-3 (December 30, 1991): 251-65. https://doi.org/10.1016/0378-3812(91)85038-V. ''' eos_pure = SRKTranslated mix_kwargs_to_pure = {'cs': 'c', 'alpha_coeffs': 'alpha_coeffs'} kwargs_linear = ('cs', 'alpha_coeffs') kwargs_keys = ('kijs', 'alpha_coeffs', 'cs', 'ge_model') model_id = 10300 def __init__(self, Tcs, Pcs, omegas, zs, alpha_coeffs, ge_model, kijs=None, cs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: kijs = [[0.0]*N for i in cmps] if cs is None: cs = [0.0]*N self.kijs = kijs self.T = T self.P = P self.V = V c1R2, c2R = self.c1*R2, self.c2*R self.ais = [c1R2*Tcs[i]*Tcs[i]/Pcs[i] for i in cmps] b0s = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.kwargs = {'kijs': kijs, 'alpha_coeffs': alpha_coeffs, 'cs': cs, 'ge_model': ge_model} self.alpha_coeffs = alpha_coeffs self.cs = cs if zs != ge_model.xs or ge_model.T != T: if T is None: T = 298.15 # default value, need to check in a_alpha call ge_model = ge_model.to_T_xs(T, zs) self.ge_model = ge_model b0, c = 0.0, 0.0 for i in cmps: b0 += b0s[i]*zs[i] c += cs[i]*zs[i] self.b0s = b0s self.bs = [b0s[i] - cs[i] for i in cmps] self.c = c self.b = b = b0 - c self.delta = c + c + b0 self.epsilon = c*(b0 + c) self.solve(only_l=only_l, only_g=only_g) # if fugacities: # self.fugacities() def _fast_init_specific(self, other): zs = self.zs self.ge_model = other.ge_model.to_T_xs(self.T, zs) self.cs = cs = other.cs self.alpha_coeffs = other.alpha_coeffs self.b0s = b0s = other.b0s b0, c = 0.0, 0.0 for i in range(self.N): b0 += b0s[i]*zs[i] c += cs[i]*zs[i] self.c = c self.b = b0 - c self.delta = c + c + b0 self.epsilon = c*(b0 + c) class PR78MIX(PRMIX): r'''Class for solving the Peng-Robinson cubic equation of state for a mixture of any number of compounds according to the 1978 variant. Subclasses `PR`. Solves the EOS on initialization and calculates fugacities for all components in all phases. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{v-b}-\frac{a\alpha(T)}{v(v+b)+b(v-b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}} .. math:: b_i=0.07780\frac{RT_{c,i}}{P_{c,i}} .. math:: \alpha(T)_i=[1+\kappa_i(1-\sqrt{T_{r,i}})]^2 .. math:: \kappa_i = 0.37464+1.54226\omega_i-0.26992\omega_i^2 \text{ if } \omega_i \le 0.491 .. math:: \kappa_i = 0.379642 + 1.48503 \omega_i - 0.164423\omega_i^2 + 0.016666 \omega_i^3 \text{ if } \omega_i > 0.491 Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa, with modified acentric factors to show the difference between :obj:`PRMIX` >>> eos = PR78MIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.6, 0.7], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.V_l, eos.V_g (3.2396438915e-05, 0.00050433802024) >>> eos.fugacities_l, eos.fugacities_g ([833048.45119, 6160.9088153], [460717.27767, 279598.90103]) Notes ----- This variant is recommended over the original. References ---------- .. [1] Peng, Ding-Yu, and Donald B. Robinson. "A New Two-Constant Equation of State." Industrial & Engineering Chemistry Fundamentals 15, no. 1 (February 1, 1976): 59-64. doi:10.1021/i160057a011. .. [2] Robinson, Donald B., Ding-Yu Peng, and Samuel Y-K Chung. "The Development of the Peng - Robinson Equation and Its Application to Phase Equilibrium in a System Containing Methanol." Fluid Phase Equilibria 24, no. 1 (January 1, 1985): 25-41. doi:10.1016/0378-3812(85)87035-7. ''' eos_pure = PR78 model_id = 10201 def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in range(N)] else: kijs = zeros((N, N)) self.kijs = kijs self.kwargs = {'kijs': kijs} self.T = T self.P = P self.V = V c1R2_c2R, c2R = self.c1R2_c2R, self.c2R if scalar: self.bs = bs = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*bs[i] for i in cmps] self.kappas = kappas = [omega*(-0.26992*omega + 1.54226) + 0.37464 for omega in omegas] for i, omega in enumerate(omegas): if omega > 0.491: kappas[i] = omega*(omega*(0.016666*omega - 0.164423) + 1.48503) + 0.379642 b = 0.0 for i in cmps: b += bs[i]*zs[i] else: self.bs = bs = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*bs self.kappas = kappas = omegas*(-0.26992*omegas + 1.54226) + 0.37464 b = float((bs*zs).sum()) high_omega_idxs = npwhere(omegas > 0.491) high_omegas = omegas[high_omega_idxs] kappas[high_omega_idxs] = high_omegas*(high_omegas*(0.016666*high_omegas - 0.164423) + 1.48503) + 0.379642 self.b = b self.delta = 2.*b self.epsilon = -b*b self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() class VDWMIX(EpsilonZeroMixingRules, GCEOSMIX, VDW): r'''Class for solving the Van der Waals [1]_ [2]_ cubic equation of state for a mixture of any number of compounds. Solves the EOS on initialization and calculates fugacities for all components in all phases. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P=\frac{RT}{V-b}-\frac{a}{V^2} .. math:: a = \sum_i \sum_j z_i z_j {a}_{ij} .. math:: b = \sum_i z_i b_i .. math:: a_{ij} = (1-k_{ij})\sqrt{a_{i}a_{j}} .. math:: a_i=\frac{27}{64}\frac{(RT_{c,i})^2}{P_{c,i}} .. math:: b_i=\frac{RT_{c,i}}{8P_{c,i}} Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] omegas : float, optional Acentric factors of all compounds - Not used in equation of state!, [-] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = VDWMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.V_l, eos.V_g (5.881369844883e-05, 0.00077708723758) >>> eos.fugacities_l, eos.fugacities_g ([854533.266920, 207126.8497276], [448470.736338, 397826.543999]) Notes ----- For P-V initializations, a numerical solver is used to find T. References ---------- .. [1] Walas, Stanley M. Phase Equilibria in Chemical Engineering. Butterworth-Heinemann, 1985. .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition. New York: McGraw-Hill Professional, 2000. ''' eos_pure = VDW nonstate_constants_specific = tuple() kwargs_keys = ('kijs',) model_id = 10001 def __init__(self, Tcs, Pcs, zs, kijs=None, T=None, P=None, V=None, omegas=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) self.Tcs = Tcs self.Pcs = Pcs self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*self.N for i in range(N)] else: kijs = zeros((N, N)) self.kijs = kijs self.kwargs = {'kijs': kijs} self.T = T self.P = P self.V = V c1R2, c2R = self.c1R2, self.c2R if self.scalar: self.ais = [c1R2*Tc*Tc/Pc for Tc, Pc in zip(Tcs, Pcs)] self.bs = [c2R*Tc/Pc for Tc, Pc in zip(Tcs, Pcs)] self.b = sum(bi*zi for bi, zi in zip(self.bs, self.zs)) else: Tc_Pc_ratio = Tcs/Pcs self.ais = c1R2*Tcs*Tc_Pc_ratio self.bs = bs = c2R*Tc_Pc_ratio self.b = float((bs*zs).sum()) self.omegas = omegas self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): if self.scalar: self.b = sum(bi*zi for bi, zi in zip(self.bs, self.zs)) else: self.b = float((self.bs*self.zs).sum()) def a_alphas_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` for the VDW EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = a Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] ''' return self.ais def a_alpha_and_derivatives_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` and their first and second derivatives for the VDW EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = a .. math:: \frac{d a\alpha}{dT} = 0 .. math:: \frac{d^2 a\alpha}{dT^2} = 0 Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] ''' if self.scalar: zero_array = [0.0]*self.N else: zero_array = zeros(self.N) return self.ais, zero_array, zero_array def fugacity_coefficients(self, Z): r'''Literature formula for calculating fugacity coefficients for each species in a mixture. Verified numerically. Called by `fugacities` on initialization, or by a solver routine which is performing a flash calculation. .. math:: \ln \hat \phi_i = \frac{b_i}{V-b} - \ln\left[Z\left(1 - \frac{b}{V}\right)\right] - \frac{2\sqrt{aa_i}}{RTV} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- log_phis : float Log fugacity coefficient for each species, [-] References ---------- .. [1] Walas, Stanley M. Phase Equilibria in Chemical Engineering. Butterworth-Heinemann, 1985. ''' N = self.N return VDW_lnphis(self.T, self.P, Z, self.b, self.a_alpha, self.bs, self.a_alpha_roots, N, lnphis=[0.0]*N if self.scalar else zeros(N)) def dlnphis_dT(self, phase): r'''Formula for calculating the temperature derivaitve of log fugacity coefficients for each species in a mixture for the VDW equation of state. Verified numerically. .. math:: \left(\frac{\partial \ln \phi_i}{\partial T}\right)_{P, nj \ne i} Parameters ---------- phase : str One of 'l' or 'g', [-] Returns ------- dlnphis_dT : float Temperature derivatives of log fugacity coefficient for each species, [1/K] Notes ----- This expression was derived using SymPy and optimized with the `cse` technique. ''' zs = self.zs if phase == 'g': Z = self.Z_g dZ_dT = self.dZ_dT_g else: Z = self.Z_l dZ_dT = self.dZ_dT_l N = self.N T, P, ais, bs, b = self.T, self.P, self.ais, self.bs, self.b T_inv = 1.0/T T_inv2 = T_inv*T_inv A = self.a_alpha*P*R2_inv*T_inv2 B = b*P*R_inv*T_inv x0 = self.a_alpha x4 = 1.0/Z x5 = 4.0*P*R2_inv*x4*T_inv2*T_inv x8 = 2*P*R2_inv*T_inv2*dZ_dT/Z**2 x9 = P*R2_inv*x4*T_inv2*self.da_alpha_dT/x0 x10 = 1.0/P x11 = R*x10*(T*dZ_dT + Z)/(-R*T*x10*Z + b)**2 x13 = b*T_inv*R_inv x14 = P*x13*x4 - 1.0 x15 = x4*(P*x13*(T_inv + x4*dZ_dT) - x14*dZ_dT)/x14 # Composition stuff d_lnphis_dTs = [] for i in range(N): x1 = (ais[i]*x0)**0.5 d_lhphi_dT = -bs[i]*x11 + x1*x5 + x1*x8 - x1*x9 + x15 d_lnphis_dTs.append(d_lhphi_dT) return d_lnphis_dTs def dlnphis_dP(self, phase): r'''Generic formula for calculating the pressure derivaitve of log fugacity coefficients for each species in a mixture for the VDW EOS. Verified numerically. .. math:: \left(\frac{\partial \ln \phi_i}{\partial P}\right)_{T, nj \ne i} Parameters ---------- phase : str One of 'l' or 'g', [-] Returns ------- dlnphis_dP : float Pressure derivatives of log fugacity coefficient for each species, [1/Pa] Notes ----- This expression was derived using SymPy and optimized with the `cse` technique. ''' zs = self.zs if phase == 'l': Z, dZ_dP = self.Z_l, self.dZ_dP_l else: Z, dZ_dP = self.Z_g, self.dZ_dP_g a_alpha = self.a_alpha N = self.N T, P, bs, b, ais = self.T, self.P, self.bs, self.b, self.ais T_inv = 1.0/T RT_inv = T_inv*R_inv x3 = T_inv*T_inv x5 = 1.0/Z x6 = 2.0*R2_inv*x3*x5 x8 = 2.0*P*R2_inv*x3*dZ_dP*x5*x5 x9 = 1./P x10 = Z*x9 x11 = R*T*x9*(-x10 + dZ_dP)/(-R*T*x10 + b)**2 x12 = P*x5 x13 = b*RT_inv x14 = x12*x13 - 1.0 x15 = -x5*(-x13*(x12*dZ_dP - 1.0) + x14*dZ_dP)/x14 d_lnphi_dPs = [] for i in range(N): x1 = (ais[i]*a_alpha)**0.5 d_lnphi_dP = -bs[i]*x11 - x1*x6 + x1*x8 + x15 d_lnphi_dPs.append(d_lnphi_dP) return d_lnphi_dPs @property def ddelta_dzs(self): r'''Helper method for calculating the composition derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial \delta}{\partial x_i}\right)_{T, P, x_{i\ne j}} = 0 Returns ------- ddelta_dzs : list[float] Composition derivative of `delta` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' if self.scalar: zero_array = [0.0]*self.N else: zero_array = zeros(self.N) return zero_array @property def ddelta_dns(self): r'''Helper method for calculating the mole number derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial \delta}{\partial n_i}\right)_{T, P, n_{i\ne j}} = 0 Returns ------- ddelta_dns : list[float] Mole number derivative of `delta` of each component, [m^3/mol^2] Notes ----- This derivative is checked numerically. ''' if self.scalar: zero_array = [0.0]*self.N else: zero_array = zeros(self.N) return zero_array @property def d2delta_dzizjs(self): r'''Helper method for calculating the second composition derivatives (hessian) of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \delta}{\partial x_i\partial x_j}\right)_{T, P, x_{k\ne i,j}} = 0 Returns ------- d2delta_dzizjs : list[float] Second Composition derivative of `delta` of each component, [m^3/mol] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: zero_array = [[0.0]*N for i in range(N)] else: zero_array = zeros((N, N)) return zero_array @property def d2delta_dninjs(self): r'''Helper method for calculating the second mole number derivatives (hessian) of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^2 \delta}{\partial n_i \partial n_j}\right)_{T, P, n_{k\ne i,j}} = 0 Returns ------- d2delta_dninjs : list[list[float]] Second mole number derivative of `delta` of each component, [m^3/mol^3] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: zero_array = [[0.0]*N for i in range(N)] else: zero_array = zeros((N, N)) return zero_array @property def d3delta_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \delta}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 0 Returns ------- d3delta_dninjnks : list[list[list[float]]] Third mole number derivative of `delta` of each component, [m^3/mol^4] Notes ----- This derivative is checked numerically. ''' N = self.N if self.scalar: zero_array = [[[0.0]*N for _ in range(N)] for _ in range(N)] else: zero_array = zeros((N, N, N)) return zero_array class PRSVMIX(PRMIX, PRSV): r'''Class for solving the Peng-Robinson-Stryjek-Vera equations of state for a mixture as given in [1]_. Subclasses :obj:`PRMIX` and :obj:`PRSV <thermo.eos.PRSV>`. Solves the EOS on initialization and calculates fugacities for all components in all phases. Inherits the method of calculating fugacity coefficients from :obj:`PRMIX`. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{v-b}-\frac{a\alpha(T)}{v(v+b)+b(v-b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}} .. math:: b_i=0.07780\frac{RT_{c,i}}{P_{c,i}} .. math:: \alpha(T)_i=[1+\kappa_i(1-\sqrt{T_{r,i}})]^2 .. math:: \kappa_i = \kappa_{0,i} + \kappa_{1,i}(1 + T_{r,i}^{0.5})(0.7 - T_{r,i}) .. math:: \kappa_{0,i} = 0.378893 + 1.4897153\omega_i - 0.17131848\omega_i^2 + 0.0196554\omega_i^3 Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] kappa1s : list[float], optional Fit parameter; available in [1]_ for over 90 compounds, SRKMIXTranslated[-] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- P-T initialization, two-phase, nitrogen and methane >>> eos = PRSVMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.phase, eos.V_l, eos.H_dep_l, eos.S_dep_l ('l/g', 3.6235536165e-05, -6349.0055583, -49.1240502472) Notes ----- [1]_ recommends that `kappa1` be set to 0 for Tr > 0.7. This is not done by default; the class boolean `kappa1_Tr_limit` may be set to True and the problem re-solved with that specified if desired. `kappa1_Tr_limit` is not supported for P-V inputs. For P-V initializations, a numerical solver is used to find T. [2]_ and [3]_ are two more resources documenting the PRSV EOS. [4]_ lists `kappa` values for 69 additional compounds. See also :obj:`PRSV2MIX`. Note that tabulated `kappa` values should be used with the critical parameters used in their fits. Both [1]_ and [4]_ only considered vapor pressure in fitting the parameter. References ---------- .. [1] Stryjek, R., and J. H. Vera. "PRSV: An Improved Peng-Robinson Equation of State for Pure Compounds and Mixtures." The Canadian Journal of Chemical Engineering 64, no. 2 (April 1, 1986): 323-33. doi:10.1002/cjce.5450640224. .. [2] Stryjek, R., and J. H. Vera. "PRSV - An Improved Peng-Robinson Equation of State with New Mixing Rules for Strongly Nonideal Mixtures." The Canadian Journal of Chemical Engineering 64, no. 2 (April 1, 1986): 334-40. doi:10.1002/cjce.5450640225. .. [3] Stryjek, R., and J. H. Vera. "Vapor-liquid Equilibrium of Hydrochloric Acid Solutions with the PRSV Equation of State." Fluid Phase Equilibria 25, no. 3 (January 1, 1986): 279-90. doi:10.1016/0378-3812(86)80004-8. .. [4] Proust, P., and J. H. Vera. "PRSV: The Stryjek-Vera Modification of the Peng-Robinson Equation of State. Parameters for Other Pure Compounds of Industrial Interest." The Canadian Journal of Chemical Engineering 67, no. 1 (February 1, 1989): 170-73. doi:10.1002/cjce.5450670125. ''' eos_pure = PRSV nonstate_constants_specific = ('kappa0s', 'kappa1s', 'kappas') mix_kwargs_to_pure = {'kappa1s': 'kappa1'} kwargs_linear = ('kappa1s',) kwargs_keys = ('kijs', 'kappa1s') model_id = 10205 def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, T=None, P=None, V=None, kappa1s=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0]*self.N for i in range(N)] else: kijs = zeros((N, N)) self.kijs = kijs if kappa1s is None: if scalar: kappa1s = [0.0 for i in range(N)] else: kappa1s = zeros(N) self.kwargs = {'kijs': kijs, 'kappa1s': kappa1s} self.T = T self.P = P self.V = V c1R2_c2R, c2R = self.c1R2_c2R, self.c2R if scalar: self.kappa0s = [omega*(omega*(0.0196554*omega - 0.17131848) + 1.4897153) + 0.378893 for omega in omegas] self.bs = bs = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*bs[i] for i in cmps] b = 0.0 for i in cmps: b += bs[i]*zs[i] else: self.kappa0s = omegas*(omegas*(0.0196554*omegas - 0.17131848) + 1.4897153) + 0.378893 self.bs = bs = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*bs b = float((bs*zs).sum()) self.b = b self.delta = 2.0*b self.epsilon = -b*b self.check_sufficient_inputs() if self.V and self.P: # Deal with T-solution here; does NOT support kappa1_Tr_limit. self.kappa1s = kappa1s solution = 'g' if (only_g and not only_l) else ('l' if only_l else None) self.T = self.solve_T(self.P, self.V, solution=solution) else: self.kappa1s = [(0 if (T/Tc > 0.7 and self.kappa1_Tr_limit) else kappa1) for kappa1, Tc in zip(kappa1s, Tcs)] self.kappas = [kappa0 + kappa1*(1 + (self.T/Tc)**0.5)*(0.7 - (self.T/Tc)) for kappa0, kappa1, Tc in zip(self.kappa0s, self.kappa1s, self.Tcs)] self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): self.kappa0s = other.kappa0s self.kappa1s = other.kappa1s self.kappas = other.kappas if self.scalar: b = 0.0 for bi, zi in zip(self.bs, self.zs): b += bi*zi else: b = float((self.bs*self.zs).sum()) self.b = b self.delta = 2.0*b self.epsilon = -b*b def a_alphas_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` for the PRSV EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = a \left(\left(\kappa_{0} + \kappa_{1} \left(\sqrt{\frac{ T}{Tc}} + 1\right) \left(- \frac{T}{Tc} + \frac{7}{10}\right) \right) \left(- \sqrt{\frac{T}{Tc}} + 1\right) + 1\right)^{2} Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] ''' return PRSV_a_alphas_vectorized(T, self.Tcs, self.ais, self.kappa0s, self.kappa1s, a_alphas=[0.0]*self.N if self.scalar else zeros(self.N)) def a_alpha_and_derivatives_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` and their first and second derivatives for the PRSV EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha = a \left(\left(\kappa_{0} + \kappa_{1} \left(\sqrt{\frac{ T}{Tc}} + 1\right) \left(- \frac{T}{Tc} + \frac{7}{10}\right) \right) \left(- \sqrt{\frac{T}{Tc}} + 1\right) + 1\right)^{2} Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] ''' N = self.N if self.scalar: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = [0.0]*N, [0.0]*N, [0.0]*N else: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = zeros(N), zeros(N), zeros(N) return PRSV_a_alpha_and_derivatives_vectorized(T, self.Tcs, self.ais, self.kappa0s, self.kappa1s, a_alphas=a_alphas, da_alpha_dTs=da_alpha_dTs, d2a_alpha_dT2s=d2a_alpha_dT2s) class PRSV2MIX(PRMIX, PRSV2): r'''Class for solving the Peng-Robinson-Stryjek-Vera 2 equations of state for a Mixture as given in [1]_. Subclasses :obj:`PRMIX` and `PRSV2 <thermo.eos.PRSV2>`. Solves the EOS on initialization and calculates fugacities for all components in all phases. Inherits the method of calculating fugacity coefficients from :obj:`PRMIX`. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{v-b}-\frac{a\alpha(T)}{v(v+b)+b(v-b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}} .. math:: b_i=0.07780\frac{RT_{c,i}}{P_{c,i}} .. math:: \alpha(T)_i=[1+\kappa_i(1-\sqrt{T_{r,i}})]^2 .. math:: \kappa_i = \kappa_{0,i} + [\kappa_{1,i} + \kappa_{2,i}(\kappa_{3,i} - T_{r,i})(1-T_{r,i}^{0.5})] (1 + T_{r,i}^{0.5})(0.7 - T_{r,i}) .. math:: \kappa_{0,i} = 0.378893 + 1.4897153\omega_i - 0.17131848\omega_i^2 + 0.0196554\omega_i^3 Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] kappa1s : list[float], optional Fit parameter; available in [1]_ for over 90 compounds, [-] kappa2s : list[float], optional Fit parameter; available in [1]_ for over 90 compounds, [-] kappa3s : list[float], optional Fit parameter; available in [1]_ for over 90 compounds, [-] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = PRSV2MIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.V_l, eos.V_g (3.6235536165e-05, 0.00070024238654) >>> eos.fugacities_l, eos.fugacities_g ([794057.58318, 72851.22327], [436553.65618, 357878.11066]) Notes ----- For P-V initializations, a numerical solver is used to find T. Note that tabulated `kappa` values should be used with the critical parameters used in their fits. [1]_ considered only vapor pressure in fitting the parameter. References ---------- .. [1] Stryjek, R., and J. H. Vera. "PRSV2: A Cubic Equation of State for Accurate Vapor-liquid Equilibria Calculations." The Canadian Journal of Chemical Engineering 64, no. 5 (October 1, 1986): 820-26. doi:10.1002/cjce.5450640516. ''' eos_pure = PRSV2 nonstate_constants_specific = ('kappa1s', 'kappa2s', 'kappa3s', 'kappa0s', 'kappas') mix_kwargs_to_pure = {'kappa1s': 'kappa1', 'kappa2s': 'kappa2', 'kappa3s': 'kappa3'} kwargs_linear = ('kappa1s', 'kappa2s', 'kappa3s') kwargs_keys = ('kijs', 'kappa1s', 'kappa2s', 'kappa3s') model_id = 10206 def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, T=None, P=None, V=None, kappa1s=None, kappa2s=None, kappa3s=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in cmps] else: kijs = zeros((N, N)) self.kijs = kijs if scalar: if kappa1s is None: kappa1s = [0.0]*N if kappa2s is None: kappa2s = [0.0]*N if kappa3s is None: kappa3s = [0.0]*N else: if kappa1s is None: kappa1s = zeros(N) if kappa2s is None: kappa2s = zeros(N) if kappa3s is None: kappa3s = zeros(N) self.kwargs = {'kijs': kijs, 'kappa1s': kappa1s, 'kappa2s': kappa2s, 'kappa3s': kappa3s} self.kappa1s = kappa1s self.kappa2s = kappa2s self.kappa3s = kappa3s self.T = T self.P = P self.V = V c2R, c1R2_c2R = self.c2R, self.c1R2_c2R if scalar: self.bs = bs = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*bs[i] for i in cmps] self.kappa0s = kappa0s = [omega*(omega*(0.0196554*omega - 0.17131848) + 1.4897153) + 0.378893 for omega in omegas] b = 0.0 for i in cmps: b += bs[i]*zs[i] else: self.bs = bs = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*bs self.kappa0s = kappa0s = omegas*(omegas*(0.0196554*omegas - 0.17131848) + 1.4897153) + 0.378893 b = float((bs*zs).sum()) self.b = b self.delta = 2.0*b self.epsilon = -b*b if self.V and self.P: solution = 'g' if (only_g and not only_l) else ('l' if only_l else None) self.T = T = self.solve_T(self.P, self.V, solution=solution) if scalar: kappas = [0.0]*N for i in cmps: Tr = T/Tcs[i] sqrtTr = sqrt(Tr) kappas[i] = kappa0s[i] + ((kappa1s[i] + kappa2s[i]*(kappa3s[i] - Tr)*(1. - sqrtTr))*(1. + sqrtTr)*(0.7 - Tr)) else: Trs = T/Tcs sqrtTrs = npsqrt(Trs) kappas = kappa0s + ((kappa1s + kappa2s*(kappa3s - Trs)*(1. - sqrtTrs))*(1. + sqrtTrs)*(0.7 - Trs)) self.kappas = kappas self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): self.kappa0s = other.kappa0s self.kappa1s = other.kappa1s self.kappa2s = other.kappa2s self.kappa3s = other.kappa3s self.kappas = other.kappas if self.scalar: b = 0.0 for bi, zi in zip(self.bs, self.zs): b += bi*zi else: b = float((self.bs*self.zs).sum()) self.b = b self.delta = b + b self.epsilon = -b*b def a_alphas_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` for the PRSV2 EOS. This vectorized implementation is added for extra speed. Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] Examples -------- >>> eos = PRSV2MIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.a_alphas_vectorized(300) [0.0860568595, 0.20174345803] ''' return PRSV2_a_alphas_vectorized(T, self.Tcs, self.ais, self.kappa0s, self.kappa1s, self.kappa2s, self.kappa3s, a_alphas=([0.0]*self.N if self.scalar else zeros(self.N))) def a_alpha_and_derivatives_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` and their first and second derivatives for the PRSV2 EOS. This vectorized implementation is added for extra speed. Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] ''' N = self.N if self.scalar: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = [0.0]*N, [0.0]*N, [0.0]*N else: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = zeros(N), zeros(N), zeros(N) return PRSV2_a_alpha_and_derivatives_vectorized(T, self.Tcs, self.ais, self.kappa0s, self.kappa1s, self.kappa2s, self.kappa3s, a_alphas=a_alphas, da_alpha_dTs=da_alpha_dTs, d2a_alpha_dT2s=d2a_alpha_dT2s) class TWUPRMIX(TwuPR95_a_alpha, PRMIX): r'''Class for solving the Twu [1]_ variant of the Peng-Robinson cubic equation of state for a mixture. Solves the EOS on initialization and calculates fugacities for all components in all phases. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{v-b}-\frac{a\alpha(T)}{v(v+b)+b(v-b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}} .. math:: b_i=0.07780\frac{RT_{c,i}}{P_{c,i}} .. math:: \alpha_i = \alpha_i^{(0)} + \omega_i(\alpha_i^{(1)}-\alpha_i^{(0)}) .. math:: \alpha^{(\text{0 or 1})} = T_{r,i}^{N(M-1)}\exp[L(1-T_{r,i}^{NM})] For sub-critical conditions: L0, M0, N0 = 0.125283, 0.911807, 1.948150; L1, M1, N1 = 0.511614, 0.784054, 2.812520 For supercritical conditions: L0, M0, N0 = 0.401219, 4.963070, -0.2; L1, M1, N1 = 0.024955, 1.248089, -8. Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = TWUPRMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.V_l, eos.V_g (3.624571041e-05, 0.0007004401318) >>> eos.fugacities_l, eos.fugacities_g ([792155.022163, 73305.88829], [436468.967764, 358049.2495573]) Notes ----- For P-V initializations, a numerical solver is used to find T. Claimed to be more accurate than the PR, PR78 and PRSV equations. References ---------- .. [1] Twu, Chorng H., John E. Coon, and John R. Cunningham. "A New Generalized Alpha Function for a Cubic Equation of State Part 1. Peng-Robinson Equation." Fluid Phase Equilibria 105, no. 1 (March 15, 1995): 49-59. doi:10.1016/0378-3812(94)02601-V. ''' eos_pure = TWUPR P_max_at_V = GCEOS.P_max_at_V solve_T = GCEOS.solve_T kwargs_keys = ('kijs', ) model_id = 10204 def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in cmps] else: kijs = zeros((N, N)) self.kijs = kijs self.kwargs = {'kijs': kijs} self.T = T self.P = P self.V = V c2R, c1R2_c2R = self.c2R, self.c1R2_c2R if scalar: self.bs = bs = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*bs[i] for i in cmps] b = 0.0 for i in cmps: b += bs[i]*zs[i] else: self.bs = bs = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*bs b = float((bs*zs).sum()) self.b = b self.delta = 2.*b self.epsilon = -b*b self.check_sufficient_inputs() self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): if self.scalar: b = 0.0 for bi, zi in zip(self.bs, self.zs): b += bi*zi else: b = float((self.bs*self.zs).sum()) self.b = b self.delta = 2.0*b self.epsilon = -b*b class TWUSRKMIX(TwuSRK95_a_alpha, SRKMIX): r'''Class for solving the Twu variant of the Soave-Redlich-Kwong cubic equation of state for a mixture. Solves the EOS on initialization and calculates fugacities for all components in all phases. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{V-b} - \frac{a\alpha(T)}{V(V+b)} .. math:: a_i =\left(\frac{R^2(T_{c,i})^{2}}{9(\sqrt[3]{2}-1)P_{c,i}} \right) =\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}} .. math:: b_i =\left( \frac{(\sqrt[3]{2}-1)}{3}\right)\frac{RT_{c,i}}{P_{c,i}} =\frac{0.08664\cdot R T_{c,i}}{P_{c,i}} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: \alpha_i = \alpha^{(0,i)} + \omega_i(\alpha^{(1,i)}-\alpha^{(0,i)}) .. math:: \alpha^{(\text{0 or 1, i})} = T_{r,i}^{N(M-1)}\exp[L(1-T_{r,i}^{NM})] For sub-critical conditions: L0, M0, N0 = 0.141599, 0.919422, 2.496441 L1, M1, N1 = 0.500315, 0.799457, 3.291790 For supercritical conditions: L0, M0, N0 = 0.441411, 6.500018, -0.20 L1, M1, N1 = 0.032580, 1.289098, -8.0 Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = TWUSRKMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.V_l, eos.V_g (4.1087927542e-05, 0.00071170732525) >>> eos.fugacities_l, eos.fugacities_g ([809692.830826, 74093.6388157], [441783.431489, 362470.3174107]) Notes ----- For P-V initializations, a numerical solver is used to find T. Claimed to be more accurate than the SRK equation. References ---------- .. [1] Twu, Chorng H., John E. Coon, and John R. Cunningham. "A New Generalized Alpha Function for a Cubic Equation of State Part 2. Redlich-Kwong Equation." Fluid Phase Equilibria 105, no. 1 (March 15, 1995): 61-69. doi:10.1016/0378-3812(94)02602-W. ''' # a_alpha_mro = -5 kwargs_keys = ('kijs', ) eos_pure = TWUSRK P_max_at_V = GCEOS.P_max_at_V solve_T = GCEOS.solve_T model_id = 10104 def __init__(self, Tcs, Pcs, omegas, zs, kijs=None, T=None, P=None, V=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in range(N)] else: kijs = zeros((N, N)) self.kijs = kijs self.kwargs = {'kijs': kijs} self.T = T self.P = P self.V = V c2R, c1R2_c2R = self.c2R, self.c1R2_c2R if scalar: self.bs = bs = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*bs[i] for i in cmps] b = 0.0 for i in cmps: b += bs[i]*zs[i] else: self.bs = bs = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*bs b = float((bs*zs).sum()) self.delta = self.b = b self.check_sufficient_inputs() self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): b = 0.0 bs, zs = self.bs, self.zs if self.scalar: for i in range(self.N): b += bs[i]*zs[i] else: b = float((bs*zs).sum()) self.delta = self.b = b class APISRKMIX(SRKMIX, APISRK): r'''Class for solving the Refinery Soave-Redlich-Kwong cubic equation of state for a mixture of any number of compounds, as shown in the API Databook [1]_. Subclasses :obj:`APISRK <thermo.eos.APISRK>`. Solves the EOS on initialization and calculates fugacities for all components in all phases. Two of `T`, `P`, and `V` are needed to solve the EOS. .. math:: P = \frac{RT}{V-b} - \frac{a\alpha(T)}{V(V+b)} .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: b = \sum_i z_i b_i .. math:: a_i =\left(\frac{R^2(T_{c,i})^{2}}{9(\sqrt[3]{2}-1)P_{c,i}} \right) =\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}} .. math:: b_i =\left( \frac{(\sqrt[3]{2}-1)}{3}\right)\frac{RT_{c,i}}{P_{c,i}} =\frac{0.08664\cdot R T_{c,i}}{P_{c,i}} .. math:: \alpha(T)_i = \left[1 + S_{1,i}\left(1-\sqrt{T_{r,i}}\right) + S_{2,i} \frac{1- \sqrt{T_{r,i}}}{\sqrt{T_{r,i}}}\right]^2 .. math:: S_{1,i} = 0.48508 + 1.55171\omega_i - 0.15613\omega_i^2 \text{ if S1 is not tabulated } Parameters ---------- Tcs : float Critical temperatures of all compounds, [K] Pcs : float Critical pressures of all compounds, [Pa] omegas : float Acentric factors of all compounds, [-] zs : float Overall mole fractions of all species, [-] kijs : list[list[float]], optional n*n size list of lists with binary interaction parameters for the Van der Waals mixing rules, default all 0 [-] T : float, optional Temperature, [K] P : float, optional Pressure, [Pa] V : float, optional Molar volume, [m^3/mol] S1s : float, optional Fit constant or estimated from acentric factor if not provided [-] S2s : float, optional Fit constant or 0 if not provided [-] fugacities : bool, optional Whether or not to calculate fugacity related values (phis, log phis, and fugacities); default True, [-] only_l : bool, optional When true, if there is a liquid and a vapor root, only the liquid root (and properties) will be set; default False, [-] only_g : bool, optional When true, if there is a liquid and a vapor root, only the vapor root (and properties) will be set; default False, [-] Notes ----- For P-V initializations, a numerical solver is used to find T. Examples -------- T-P initialization, nitrogen-methane at 115 K and 1 MPa: >>> eos = APISRKMIX(T=115, P=1E6, Tcs=[126.1, 190.6], Pcs=[33.94E5, 46.04E5], omegas=[0.04, 0.011], zs=[0.5, 0.5], kijs=[[0,0],[0,0]]) >>> eos.V_l, eos.V_g (4.101592310e-05, 0.00071046883030) >>> eos.fugacities_l, eos.fugacities_g ([817882.3033, 71620.4823812], [442158.29113, 361519.79877]) References ---------- .. [1] API Technical Data Book: General Properties & Characterization. American Petroleum Institute, 7E, 2005. ''' eos_pure = APISRK nonstate_constants_specific = ('S1s', 'S2s') mix_kwargs_to_pure = {'S1s': 'S1', 'S2s': 'S2'} kwargs_linear = ('S1s', 'S2s') kwargs_keys = ('kijs', 'S1s', 'S2s') model_id = 10105 def __init__(self, Tcs, Pcs, zs, omegas=None, kijs=None, T=None, P=None, V=None, S1s=None, S2s=None, fugacities=True, only_l=False, only_g=False): self.N = N = len(Tcs) cmps = range(N) self.Tcs = Tcs self.Pcs = Pcs self.omegas = omegas self.zs = zs self.scalar = scalar = type(zs) is list if kijs is None: if scalar: kijs = [[0.0]*N for i in cmps] else: kijs = zeros((N, N)) self.kijs = kijs self.kwargs = {'kijs': kijs} self.T = T self.P = P self.V = V self.check_sufficient_inputs() # Setup S1s and S2s if S1s is None and omegas is None: raise ValueError('Either acentric factor of S1 is required') if S1s is None: if scalar: self.S1s = [omega*(1.55171 - 0.15613*omega) + 0.48508 for omega in omegas] else: self.S1s = omegas*(1.55171 - 0.15613*omegas) + 0.48508 else: self.S1s = S1s if S2s is None: if scalar: S2s = [0.0]*N else: S2s = zeros(N) self.S2s = S2s self.kwargs = {'S1s': self.S1s, 'S2s': self.S2s} c2R, c1R2_c2R = self.c2R, self.c1R2_c2R if scalar: self.bs = bs = [c2R*Tcs[i]/Pcs[i] for i in cmps] self.ais = [c1R2_c2R*Tcs[i]*bs[i] for i in cmps] b = 0.0 for i in cmps: b += bs[i]*zs[i] else: self.bs = bs = c2R*Tcs/Pcs self.ais = c1R2_c2R*Tcs*bs b = float((bs*zs).sum()) self.b = self.delta = b self.solve(only_l=only_l, only_g=only_g) if fugacities: self.fugacities() def _fast_init_specific(self, other): self.S1s = other.S1s self.S2s = other.S2s if self.scalar: self.delta = self.b = sum([bi*zi for bi, zi in zip(self.bs, self.zs)]) else: self.delta = self.b = float((self.bs*self.zs).sum()) def a_alphas_vectorized(self, T): a_alphas = [0.0]*self.N if self.scalar else zeros(self.N) return APISRK_a_alphas_vectorized(T, self.Tcs, self.ais, self.S1s, self.S2s, a_alphas=a_alphas) def a_alpha_and_derivatives_vectorized(self, T): r'''Method to calculate the pure-component `a_alphas` and their first and second derivatives for the API SRK EOS. This vectorized implementation is added for extra speed. .. math:: a\alpha(T) = a\left[1 + S_1\left(1-\sqrt{T_r}\right) + S_2\frac{1 - \sqrt{T_r}}{\sqrt{T_r}}\right]^2 .. math:: \frac{d a\alpha}{dT} = a\frac{Tc}{T^{2}} \left(- S_{2} \left(\sqrt{ \frac{T}{Tc}} - 1\right) + \sqrt{\frac{T}{Tc}} \left(S_{1} \sqrt{ \frac{T}{Tc}} + S_{2}\right)\right) \left(S_{2} \left(\sqrt{\frac{ T}{Tc}} - 1\right) + \sqrt{\frac{T}{Tc}} \left(S_{1} \left(\sqrt{ \frac{T}{Tc}} - 1\right) - 1\right)\right) .. math:: \frac{d^2 a\alpha}{dT^2} = a\frac{1}{2 T^{3}} \left(S_{1}^{2} T \sqrt{\frac{T}{Tc}} - S_{1} S_{2} T \sqrt{\frac{T}{Tc}} + 3 S_{1} S_{2} Tc \sqrt{\frac{T}{Tc}} + S_{1} T \sqrt{\frac{T}{Tc}} - 3 S_{2}^{2} Tc \sqrt{\frac{T}{Tc}} + 4 S_{2}^{2} Tc + 3 S_{2} Tc \sqrt{\frac{T}{Tc}}\right) Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] ''' N = self.N if self.scalar: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = [0.0]*N, [0.0]*N, [0.0]*N else: a_alphas, da_alpha_dTs, d2a_alpha_dT2s = zeros(N), zeros(N), zeros(N) return APISRK_a_alpha_and_derivatives_vectorized(T, self.Tcs, self.ais, self.S1s, self.S2s, a_alphas=a_alphas, da_alpha_dTs=da_alpha_dTs, d2a_alpha_dT2s=d2a_alpha_dT2s) def P_max_at_V(self, V): if self.N == 1 and self.S2s[0] == 0: self.ms = self.S1s P_max_at_V = SRK.P_max_at_V(self, V) del self.ms return P_max_at_V return GCEOSMIX.P_max_at_V(self, V) eos_mix_list = [PRMIX, SRKMIX, PR78MIX, VDWMIX, PRSVMIX, PRSV2MIX, TWUPRMIX, TWUSRKMIX, APISRKMIX, IGMIX, RKMIX, PRMIXTranslatedConsistent, PRMIXTranslatedPPJP, SRKMIXTranslatedConsistent, PRMIXTranslated, SRKMIXTranslated] '''List of all exported EOS classes. ''' eos_mix_no_coeffs_list = [PRMIX, SRKMIX, PR78MIX, VDWMIX, TWUPRMIX, TWUSRKMIX, IGMIX, RKMIX, PRMIXTranslatedConsistent, PRMIXTranslated, SRKMIXTranslated, PRMIXTranslatedPPJP, SRKMIXTranslatedConsistent] '''List of all exported EOS classes that do not require special parameters or can fill in their special parameters from other specified parameters. ''' eos_mix_dict = {c.__name__: c for c in eos_mix_list} '''dict : Dict of all cubic mixture equation of state classes, indexed by their class name. ''' eos_mix_full_path_dict = {c.__full_path__: c for c in eos_mix_list} '''dict : Dict of all cubic mixture equation of state classes, indexed by their module path and class name. ''' eos_mix_full_path_reverse_dict = {c: c.__full_path__ for c in eos_mix_list} '''dict : Dict of all cubic mixture equation of state classes, indexed by their module path and class name. '''
36.496243
1,710
0.542829
61,588
422,590
3.56727
0.036614
0.0204
0.005189
0.005558
0.754362
0.719446
0.684626
0.662136
0.638941
0.616684
0
0.052996
0.327729
422,590
11,578
1,711
36.499395
0.720333
0.485563
0
0.553784
0
0
0.010465
0.000551
0
0
0
0.001036
0.000425
1
0.058673
false
0.005315
0.004039
0.002551
0.153274
0.000425
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
43930e1ff7425ef708802f69f9ad4976162d847f
315
py
Python
hknweb/academics/views/logistics/instructor.py
Boomaa23/hknweb
2c2ce38b5f1c0c6e04ba46282141557357bd5326
[ "MIT" ]
20
2018-01-07T02:15:43.000Z
2021-09-15T04:25:50.000Z
hknweb/academics/views/logistics/instructor.py
Boomaa23/hknweb
2c2ce38b5f1c0c6e04ba46282141557357bd5326
[ "MIT" ]
292
2018-02-01T18:31:18.000Z
2022-03-30T22:15:08.000Z
hknweb/academics/views/logistics/instructor.py
Boomaa23/hknweb
2c2ce38b5f1c0c6e04ba46282141557357bd5326
[ "MIT" ]
85
2017-11-13T06:33:13.000Z
2022-03-30T20:32:55.000Z
from hknweb.academics.views.base_viewset import AcademicEntityViewSet from hknweb.academics.models import Instructor from hknweb.academics.serializers import InstructorSerializer class InstructorViewSet(AcademicEntityViewSet): queryset = Instructor.objects.all() serializer_class = InstructorSerializer
28.636364
69
0.847619
30
315
8.833333
0.6
0.113208
0.215094
0
0
0
0
0
0
0
0
0
0.101587
315
10
70
31.5
0.936396
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.5
0
1
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
439dd3f137e1b2f2d07dacc62043ed850050e384
517
py
Python
photos_time_warp/utils.py
tkrunning/photos_time_warp
0805a1a4f778387847f8a06040fe187cce744beb
[ "MIT" ]
null
null
null
photos_time_warp/utils.py
tkrunning/photos_time_warp
0805a1a4f778387847f8a06040fe187cce744beb
[ "MIT" ]
null
null
null
photos_time_warp/utils.py
tkrunning/photos_time_warp
0805a1a4f778387847f8a06040fe187cce744beb
[ "MIT" ]
null
null
null
"""Utils for photos_time_warp""" def pluralize(count, singular, plural): """Return singular or plural based on count""" if count == 1: return singular else: return plural def noop(*args, **kwargs): """No-op function for use as verbose if verbose not set""" pass def red(msg: str) -> str: """Return red string in rich markdown""" return f"[red]{msg}[/red]" def green(msg: str) -> str: """Return green string in rich markdown""" return f"[green]{msg}[/green]"
21.541667
62
0.615087
73
517
4.328767
0.520548
0.088608
0.056962
0.094937
0.170886
0.170886
0
0
0
0
0
0.002532
0.235977
517
23
63
22.478261
0.797468
0.371373
0
0
0
0
0.120401
0
0
0
0
0
0
1
0.363636
false
0.090909
0
0
0.727273
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
1
0
0
3
43ade1146900611382a7d447fb044df89477c1c0
3,841
py
Python
python/my_custard.py
ensan-hcl/CustardKit
96c5a484e98dd2f0e43df1855ed92e0799a00b33
[ "MIT" ]
1
2021-03-25T13:26:07.000Z
2021-03-25T13:26:07.000Z
python/my_custard.py
ensan-hcl/CustardKit
96c5a484e98dd2f0e43df1855ed92e0799a00b33
[ "MIT" ]
13
2021-03-24T13:53:11.000Z
2021-04-18T02:52:37.000Z
python/my_custard.py
ensan-hcl/CustardKit
96c5a484e98dd2f0e43df1855ed92e0799a00b33
[ "MIT" ]
2
2021-03-24T13:51:20.000Z
2021-03-24T13:52:38.000Z
from source.custard import * custard = Custard( identifier="my_custard", language=Language.ja_JP, input_style=InputStyle.direct, metadata=Metadata( custard_version="1.0", display_name="私のカスタード", ), interface=Interface( key_style=KeyStyle.tenkey_style, key_layout=GridFitLayout(row_count=2, column_count=2), keys=[ KeyData( specifier=GridFitSpecifier(x=0, y=0), key=SystemKey(SystemKeyType.change_keyboard) ), KeyData( specifier=GridFitSpecifier(x=0, y=1), key=CustomKey( design=KeyDesign( label=TextLabel(text="あ"), color=KeyColor.normal ), press_actions=[], longpress_actions=LongpressAction( start=[ DeleteAction(1), ] ), variations=[ FlickVariationData( direction=FlickDirection.left, key=Variation( design=VariationDesign( label=TextLabel(text="い"), ), press_actions=[ InputAction("い") ], longpress_actions=LongpressAction() ) ) ] ) ), KeyData( specifier=GridFitSpecifier(x=1, y=0), key=CustomKey( design=KeyDesign( label=TextLabel(text="あ"), color=KeyColor.normal ), press_actions=[], longpress_actions=LongpressAction( start=[ DeleteAction(1), ] ), variations=[ FlickVariationData( direction=FlickDirection.left, key=Variation( design=VariationDesign( label=TextLabel(text="い"), ), press_actions=[ InputAction("い") ], ) ) ] ) ), KeyData( specifier=GridFitSpecifier(x=1, y=1), key=CustomKey( design=KeyDesign( label=TextLabel(text="あ"), color=KeyColor.normal ), press_actions=[], longpress_actions=LongpressAction( start=[ DeleteAction(1), ] ), variations=[ FlickVariationData( direction=FlickDirection.left, key=Variation( design=VariationDesign( label=TextLabel(text="い"), ), press_actions=[ InputAction("い") ], ) ) ] ) ), ] ) ) custard.write(name="my_custard")
34.603604
67
0.332205
192
3,841
6.53125
0.34375
0.066986
0.086124
0.105263
0.72807
0.72807
0.618022
0.618022
0.618022
0.618022
0
0.009659
0.595678
3,841
110
68
34.918182
0.797811
0
0
0.650943
0
0
0.010154
0
0
0
0
0
0
1
0
false
0
0.009434
0
0.009434
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
43c5b3e5404bab89458cc859314d82e96f1049a9
3,783
py
Python
pythonProject1/venv/Lib/site-packages/TkinterExtensions/Widgets/Frames.py
mjtomlinson/CNE330_Python_1_Final_Project
05020806860937ef37b9a0ad2e27de4897a606de
[ "CC0-1.0" ]
null
null
null
pythonProject1/venv/Lib/site-packages/TkinterExtensions/Widgets/Frames.py
mjtomlinson/CNE330_Python_1_Final_Project
05020806860937ef37b9a0ad2e27de4897a606de
[ "CC0-1.0" ]
null
null
null
pythonProject1/venv/Lib/site-packages/TkinterExtensions/Widgets/Frames.py
mjtomlinson/CNE330_Python_1_Final_Project
05020806860937ef37b9a0ad2e27de4897a606de
[ "CC0-1.0" ]
null
null
null
# ------------------------------------------------------------------------------ # Created by Tyler Stegmaier. # Property of TrueLogic Company. # Copyright (c) 2020. # ------------------------------------------------------------------------------ # # ------------------------------------------------------------------------------ from enum import Enum from typing import Union from ..Widgets.BaseWidgets import * from ..Widgets.base import * __all__ = [ 'Frame', 'LabelFrame', 'FrameThemed', 'LabelFrameThemed', 'FrameTypes', ] class BaseFrameMixin: InstanceID: Union[str, int, Enum] = None def SetID(self, InstanceID: Union[str, int, Enum]): self.InstanceID = InstanceID return self @property def __name__(self): try: base = super().__name__() except AttributeError: base = self.__class__.__name__ if self.InstanceID: if isinstance(self.InstanceID, Enum): InstanceID = self.InstanceID.value else: InstanceID = self.InstanceID return f'{base}_{InstanceID}'.lower() return base # noinspection DuplicatedCode class Frame(tk.Frame, BaseTkinterWidget, BaseFrameMixin): def __init__(self, master, **kwargs): tk.Frame.__init__(self, master, **kwargs) def _options(self, cnf, kwargs=None) -> dict: return super()._options(cnf, BaseTkinterWidget.convert_kwargs(kwargs)) class LabelFrame(tk.LabelFrame, BaseTextTkinterWidget, BaseFrameMixin): """Construct a labelframe _widget with the master MASTER. STANDARD OPTIONS borderwidth, cursor, font, foreground, highlightbackground, highlightcolor, highlightthickness, padx, pady, relief, takefocus, text WIDGET-SPECIFIC OPTIONS background, class, colormap, container, height, labelanchor, labelwidget, visual, width """ def __init__(self, master, text: str = '', **kwargs): tk.LabelFrame.__init__(self, master=master, text=text, **kwargs) BaseTextTkinterWidget.__init__(self, text=text, configure=False) @property def txt(self) -> str: return self._txt.get() @txt.setter def txt(self, value: str): self._txt.set(value) self.configure(text=value) def _options(self, cnf, kwargs=None) -> dict: return super()._options(cnf, BaseTkinterWidget.convert_kwargs(kwargs)) # noinspection DuplicatedCode class FrameThemed(ttk.Frame, BaseTkinterWidget, BaseFrameMixin): def __init__(self, master, **kwargs): ttk.Frame.__init__(self, master=master, **kwargs) def _options(self, cnf, kwargs=None) -> dict: return super()._options(cnf, BaseTkinterWidget.convert_kwargs(kwargs)) class LabelFrameThemed(ttk.LabelFrame, BaseTextTkinterWidget, BaseFrameMixin): """Construct a labelframe _widget with the master MASTER. STANDARD OPTIONS borderwidth, cursor, font, foreground, highlightbackground, highlightcolor, highlightthickness, padx, pady, relief, takefocus, text WIDGET-SPECIFIC OPTIONS background, class, colormap, container, height, labelanchor, labelwidget, visual, width """ def __init__(self, master, text: str = '', **kwargs): ttk.LabelFrame.__init__(self, master=master, text=text, **kwargs) BaseTextTkinterWidget.__init__(self, text=text, configure=False) @property def txt(self) -> str: return self._txt.get() @txt.setter def txt(self, value: str): self._txt.set(value) self.configure(text=value) def _options(self, cnf, kwargs=None) -> dict: return super()._options(cnf, BaseTkinterWidget.convert_kwargs(kwargs)) FrameTypes = Union[Frame, LabelFrame, FrameThemed, LabelFrameThemed]
28.877863
120
0.63336
370
3,783
6.262162
0.248649
0.034527
0.048338
0.029348
0.698317
0.676737
0.676737
0.676737
0.625809
0.625809
0
0.001325
0.20222
3,783
130
121
29.1
0.766402
0.283109
0
0.425926
0
0
0.027193
0
0
0
0
0
0
1
0.259259
false
0
0.074074
0.111111
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
3
43dde93c073173dc14db7a4ad8a9da6ea6955aa1
247
py
Python
python/manus_apps/__main__.py
lukacu/manus
bd34c6d7a0f7ecd7a1e62119d2adc8b1af9eefae
[ "MIT" ]
1
2018-10-04T16:08:08.000Z
2018-10-04T16:08:08.000Z
python/manus_apps/__main__.py
manus-project/manus
bd34c6d7a0f7ecd7a1e62119d2adc8b1af9eefae
[ "MIT" ]
1
2016-10-21T08:58:52.000Z
2016-10-21T08:58:52.000Z
python/manus_apps/__main__.py
manus-project/manus
bd34c6d7a0f7ecd7a1e62119d2adc8b1af9eefae
[ "MIT" ]
1
2016-10-21T21:57:19.000Z
2016-10-21T21:57:19.000Z
from __future__ import absolute_import import sys, os if __name__ == '__main__': if len(sys.argv) < 2: from .launcher import application_launcher application_launcher() else: from .launcher import start_app start_app(sys.argv[1])
22.454545
47
0.740891
34
247
4.882353
0.529412
0.084337
0.216867
0
0
0
0
0
0
0
0
0.009804
0.174089
247
11
48
22.454545
0.803922
0
0
0
0
0
0.032258
0
0
0
0
0
0
1
0
true
0
0.444444
0
0.444444
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
3
78db9502b13516cbe5cd182bed5c6e75398b145d
406
py
Python
measure/serializers.py
luke-feng/MAP
bc82ec20e2859dd6437d314fc12880f5e6b6aad8
[ "Apache-2.0" ]
1
2021-11-30T19:38:55.000Z
2021-11-30T19:38:55.000Z
measure/serializers.py
luke-feng/MAP
bc82ec20e2859dd6437d314fc12880f5e6b6aad8
[ "Apache-2.0" ]
null
null
null
measure/serializers.py
luke-feng/MAP
bc82ec20e2859dd6437d314fc12880f5e6b6aad8
[ "Apache-2.0" ]
1
2022-02-25T22:48:21.000Z
2022-02-25T22:48:21.000Z
from .models import Measures from rest_framework import serializers class MeasuresSerializer(serializers.ModelSerializer): measure_type_name = serializers.CharField(source='measure_type_id.measure_name', read_only=True) incident_category_name = serializers.CharField(source='incident_category.incident_category', read_only=True) class Meta: model = Measures fields = '__all__'
40.6
112
0.79064
46
406
6.630435
0.543478
0.157377
0.157377
0.196721
0
0
0
0
0
0
0
0
0.135468
406
9
113
45.111111
0.868946
0
0
0
0
0
0.172414
0.155172
0
0
0
0
0
1
0
false
0
0.25
0
0.75
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
3
78f6871bbad7836285eef5edfd9b37d15d84ab2f
22,090
py
Python
src/cc_catalog_airflow/dags/provider_api_scripts/common/storage/test_image.py
gauravahlawat81/cccatalog
cabfa11c4e1d68c66390ed46649282b7d33e2c58
[ "MIT" ]
65
2018-05-25T00:47:18.000Z
2021-11-30T05:58:43.000Z
src/cc_catalog_airflow/dags/provider_api_scripts/common/storage/test_image.py
cc-archive/cccatalog
bc95ccc159ed7f1444d44e1db08d9a11a16c6d12
[ "MIT" ]
463
2018-05-01T14:35:42.000Z
2021-06-11T20:32:50.000Z
src/cc_catalog_airflow/dags/provider_api_scripts/common/storage/test_image.py
cc-archive/cccatalog
bc95ccc159ed7f1444d44e1db08d9a11a16c6d12
[ "MIT" ]
81
2018-05-05T20:33:12.000Z
2021-04-28T02:23:10.000Z
import logging import requests import pytest import tldextract from common.storage import image logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s: %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) # This avoids needing the internet for testing. image.licenses.urls.tldextract.extract = tldextract.TLDExtract( suffix_list_urls=None ) image.columns.urls.tldextract.extract = tldextract.TLDExtract( suffix_list_urls=None ) @pytest.fixture def setup_env(monkeypatch): monkeypatch.setenv('OUTPUT_DIR', '/tmp') @pytest.fixture def mock_rewriter(monkeypatch): def mock_rewrite_redirected_url(url_string): return url_string monkeypatch.setattr( image.licenses.urls, 'rewrite_redirected_url', mock_rewrite_redirected_url, ) @pytest.fixture def get_good(monkeypatch): def mock_get(url, timeout=60): return requests.Response() monkeypatch.setattr(image.licenses.urls.requests, 'get', mock_get) def test_ImageStore_uses_OUTPUT_DIR_variable( monkeypatch, ): testing_output_dir = '/my_output_dir' monkeypatch.setenv('OUTPUT_DIR', testing_output_dir) image_store = image.ImageStore() assert testing_output_dir in image_store._OUTPUT_PATH def test_ImageStore_falls_back_to_tmp_output_dir_variable( monkeypatch, setup_env, ): monkeypatch.delenv('OUTPUT_DIR') image_store = image.ImageStore() assert '/tmp' in image_store._OUTPUT_PATH def test_ImageStore_includes_provider_in_output_file_string( setup_env, ): image_store = image.ImageStore('test_provider') assert type(image_store._OUTPUT_PATH) == str assert 'test_provider' in image_store._OUTPUT_PATH def test_ImageStore_add_item_adds_realistic_image_to_buffer( setup_env, mock_rewriter ): license_url = 'https://creativecommons.org/publicdomain/zero/1.0/' image_store = image.ImageStore(provider='testing_provider') image_store.add_item( foreign_landing_url='https://images.org/image01', image_url='https://images.org/image01.jpg', license_url=license_url, ) assert len(image_store._image_buffer) == 1 def test_ImageStore_add_item_adds_multiple_images_to_buffer( mock_rewriter, setup_env, ): image_store = image.ImageStore(provider='testing_provider') image_store.add_item( foreign_landing_url='https://images.org/image01', image_url='https://images.org/image01.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) image_store.add_item( foreign_landing_url='https://images.org/image02', image_url='https://images.org/image02.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) image_store.add_item( foreign_landing_url='https://images.org/image03', image_url='https://images.org/image03.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) image_store.add_item( foreign_landing_url='https://images.org/image04', image_url='https://images.org/image04.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) assert len(image_store._image_buffer) == 4 def test_ImageStore_add_item_flushes_buffer( mock_rewriter, setup_env, tmpdir, ): output_file = 'testing.tsv' tmp_directory = tmpdir output_dir = str(tmp_directory) tmp_file = tmp_directory.join(output_file) tmp_path_full = str(tmp_file) image_store = image.ImageStore( provider='testing_provider', output_file=output_file, output_dir=output_dir, buffer_length=3 ) image_store.add_item( foreign_landing_url='https://images.org/image01', image_url='https://images.org/image01.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) image_store.add_item( foreign_landing_url='https://images.org/image02', image_url='https://images.org/image02.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) image_store.add_item( foreign_landing_url='https://images.org/image03', image_url='https://images.org/image03.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) image_store.add_item( foreign_landing_url='https://images.org/image04', image_url='https://images.org/image04.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) assert len(image_store._image_buffer) == 1 with open(tmp_path_full) as f: lines = f.read().split('\n') assert len(lines) == 4 # recall the last '\n' will create an empty line. def test_ImageStore_commit_writes_nothing_if_no_lines_in_buffer(): image_store = image.ImageStore(output_dir='/path/does/not/exist') image_store.commit() def test_ImageStore_produces_correct_total_images(mock_rewriter, setup_env): image_store = image.ImageStore(provider='testing_provider') image_store.add_item( foreign_landing_url='https://images.org/image01', image_url='https://images.org/image01.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) image_store.add_item( foreign_landing_url='https://images.org/image02', image_url='https://images.org/image02.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) image_store.add_item( foreign_landing_url='https://images.org/image03', image_url='https://images.org/image03.jpg', license_url='https://creativecommons.org/publicdomain/zero/1.0/' ) assert image_store.total_images == 3 def test_ImageStore_get_image_places_given_args( monkeypatch, setup_env ): image_store = image.ImageStore(provider='testing_provider') args_dict = { 'foreign_landing_url': 'https://landing_page.com', 'image_url': 'http://imageurl.com', 'license_': 'testlicense', 'license_version': '1.0', 'license_url': None, 'foreign_identifier': 'foreign_id', 'thumbnail_url': 'http://thumbnail.com', 'width': 200, 'height': 500, 'creator': 'tyler', 'creator_url': 'https://creatorurl.com', 'title': 'agreatpicture', 'meta_data': {'description': 'cat picture'}, 'raw_tags': [{'name': 'tag1', 'provider': 'testing'}], 'watermarked': 'f', 'source': 'testing_source' } def mock_license_chooser(license_url, license_, license_version): return image.licenses.LicenseInfo( license_, license_version, license_url ) monkeypatch.setattr( image.licenses, 'get_license_info', mock_license_chooser ) def mock_get_source(source, provider): return source monkeypatch.setattr( image.util, 'get_source', mock_get_source ) def mock_enrich_tags(tags): return tags monkeypatch.setattr( image_store, '_enrich_tags', mock_enrich_tags ) actual_image = image_store._get_image(**args_dict) args_dict['tags'] = args_dict.pop('raw_tags') args_dict.pop('license_url') args_dict['provider'] = 'testing_provider' args_dict['filesize'] = None assert actual_image == image.Image(**args_dict) def test_ImageStore_get_image_calls_license_chooser( monkeypatch, setup_env, ): image_store = image.ImageStore() def mock_license_chooser(license_url, license_, license_version): return image.licenses.LicenseInfo( 'diff_license', None, license_url ) monkeypatch.setattr( image.licenses, 'get_license_info', mock_license_chooser ) actual_image = image_store._get_image( license_url='https://license/url', license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data=None, raw_tags=None, watermarked=None, source=None, ) assert actual_image.license_ == 'diff_license' def test_ImageStore_get_image_gets_source( monkeypatch, setup_env, ): image_store = image.ImageStore() def mock_get_source(source, provider): return 'diff_source' monkeypatch.setattr(image.util, 'get_source', mock_get_source) actual_image = image_store._get_image( license_url='https://license/url', license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data=None, raw_tags=None, watermarked=None, source=None, ) assert actual_image.source == 'diff_source' def test_ImageStore_get_image_replaces_non_dict_meta_data_with_no_license_url( setup_env, ): image_store = image.ImageStore() actual_image = image_store._get_image( license_url=None, license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data='notadict', raw_tags=None, watermarked=None, source=None, ) assert actual_image.meta_data == { 'license_url': None, 'raw_license_url': None } def test_ImageStore_get_image_creates_meta_data_with_valid_license_url( monkeypatch, setup_env ): def mock_license_chooser(license_url, license_, license_version): return image.licenses.LicenseInfo( license_, license_version, license_url ) monkeypatch.setattr( image.licenses, 'get_license_info', mock_license_chooser ) license_url = 'https://my.license.url' image_store = image.ImageStore() actual_image = image_store._get_image( license_url=license_url, license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data=None, raw_tags=None, watermarked=None, source=None, ) assert actual_image.meta_data == { 'license_url': license_url, 'raw_license_url': license_url } def test_ImageStore_get_image_adds_valid_license_url_to_dict_meta_data( monkeypatch, setup_env ): def mock_license_chooser(license_url, license_, license_version): return image.licenses.LicenseInfo( license_, license_version, license_url ) monkeypatch.setattr( image.licenses, 'get_license_info', mock_license_chooser ) image_store = image.ImageStore() actual_image = image_store._get_image( license_url='https://license/url', license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data={'key1': 'val1'}, raw_tags=None, watermarked=None, source=None, ) assert actual_image.meta_data == { 'key1': 'val1', 'license_url': 'https://license/url', 'raw_license_url': 'https://license/url' } def test_ImageStore_get_image_fixes_invalid_license_url( monkeypatch, setup_env ): original_url = 'https://license/url', updated_url = 'https://updatedurl.com' def mock_license_chooser(license_url, license_, license_version): return image.licenses.LicenseInfo( license_, license_version, updated_url ) monkeypatch.setattr( image.licenses, 'get_license_info', mock_license_chooser ) image_store = image.ImageStore() actual_image = image_store._get_image( license_url=original_url, license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data={}, raw_tags=None, watermarked=None, source=None, ) assert actual_image.meta_data == { 'license_url': updated_url, 'raw_license_url': original_url } def test_ImageStore_get_image_enriches_singleton_tags( setup_env, ): image_store = image.ImageStore('test_provider') actual_image = image_store._get_image( license_url='https://license/url', license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data=None, raw_tags=['lone'], watermarked=None, source=None, ) assert actual_image.tags == [{'name': 'lone', 'provider': 'test_provider'}] def test_ImageStore_get_image_tag_blacklist( setup_env, ): raw_tags = [ 'cc0', 'valid', 'garbage:=metacrap', 'uploaded:by=flickrmobile', { 'name': 'uploaded:by=instagram', 'provider': 'test_provider' } ] image_store = image.ImageStore('test_provider') actual_image = image_store._get_image( license_url='https://license/url', license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data=None, raw_tags=raw_tags, watermarked=None, source=None, ) assert actual_image.tags == [ {'name': 'valid', 'provider': 'test_provider'} ] def test_ImageStore_get_image_enriches_multiple_tags( setup_env, ): image_store = image.ImageStore('test_provider') actual_image = image_store._get_image( license_url='https://license/url', license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data=None, raw_tags=['tagone', 'tag2', 'tag3'], watermarked=None, source=None, ) assert actual_image.tags == [ {'name': 'tagone', 'provider': 'test_provider'}, {'name': 'tag2', 'provider': 'test_provider'}, {'name': 'tag3', 'provider': 'test_provider'}, ] def test_ImageStore_get_image_leaves_preenriched_tags( setup_env ): image_store = image.ImageStore('test_provider') tags = [ {'name': 'tagone', 'provider': 'test_provider'}, {'name': 'tag2', 'provider': 'test_provider'}, {'name': 'tag3', 'provider': 'test_provider'}, ] actual_image = image_store._get_image( license_url='https://license/url', license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data=None, raw_tags=tags, watermarked=None, source=None, ) assert actual_image.tags == tags def test_ImageStore_get_image_nones_nonlist_tags( setup_env, ): image_store = image.ImageStore('test_provider') tags = 'notalist' actual_image = image_store._get_image( license_url='https://license/url', license_='license', license_version='1.5', foreign_landing_url=None, image_url=None, thumbnail_url=None, foreign_identifier=None, width=None, height=None, creator=None, creator_url=None, title=None, meta_data=None, raw_tags=tags, watermarked=None, source=None, ) assert actual_image.tags is None @pytest.fixture def default_image_args( setup_env, ): return dict( foreign_identifier=None, foreign_landing_url='https://image.org', image_url='https://image.org', thumbnail_url=None, width=None, height=None, filesize=None, license_='cc0', license_version='1.0', creator=None, creator_url=None, title=None, meta_data=None, tags=None, watermarked=None, provider=None, source=None, ) def test_create_tsv_row_non_none_if_req_fields( default_image_args, get_good, setup_env, ): image_store = image.ImageStore() test_image = image.Image(**default_image_args) actual_row = image_store._create_tsv_row(test_image) assert actual_row is not None def test_create_tsv_row_none_if_no_foreign_landing_url( default_image_args, setup_env, ): image_store = image.ImageStore() image_args = default_image_args image_args['foreign_landing_url'] = None test_image = image.Image(**image_args) expect_row = None actual_row = image_store._create_tsv_row(test_image) assert expect_row == actual_row def test_create_tsv_row_none_if_no_license( default_image_args, setup_env, ): image_store = image.ImageStore() image_args = default_image_args image_args['license_'] = None test_image = image.Image(**image_args) expect_row = None actual_row = image_store._create_tsv_row(test_image) assert expect_row == actual_row def test_create_tsv_row_none_if_no_license_version( default_image_args, setup_env, ): image_store = image.ImageStore() image_args = default_image_args image_args['license_version'] = None test_image = image.Image(**image_args) expect_row = None actual_row = image_store._create_tsv_row(test_image) assert expect_row == actual_row def test_create_tsv_row_returns_none_if_missing_image_url( default_image_args, setup_env, ): image_store = image.ImageStore() image_args = default_image_args image_args['image_url'] = None test_image = image.Image(**image_args) expect_row = None actual_row = image_store._create_tsv_row(test_image) assert expect_row == actual_row def test_create_tsv_row_handles_empty_dict_and_tags( default_image_args, setup_env, ): image_store = image.ImageStore() meta_data = {} tags = [] image_args = default_image_args image_args['meta_data'] = meta_data image_args['tags'] = tags test_image = image.Image(**image_args) actual_row = image_store._create_tsv_row(test_image).split('\t') actual_meta_data, actual_tags = actual_row[12], actual_row[13] expect_meta_data, expect_tags = '\\N', '\\N' assert expect_meta_data == actual_meta_data assert expect_tags == actual_tags def test_create_tsv_row_turns_empty_into_nullchar( default_image_args, setup_env, ): image_store = image.ImageStore() image_args = default_image_args test_image = image.Image(**image_args) actual_row = image_store._create_tsv_row(test_image).split('\t') assert all( [ actual_row[i] == '\\N' for i in [0, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15] ] ) is True assert actual_row[-1] == '\\N\n' def test_create_tsv_row_properly_places_entries( setup_env, monkeypatch ): def mock_validate_url(url_string): return url_string monkeypatch.setattr( image.columns.urls, 'validate_url_string', mock_validate_url ) image_store = image.ImageStore() req_args_dict = { 'foreign_landing_url': 'https://landing_page.com', 'image_url': 'http://imageurl.com', 'license_': 'testlicense', 'license_version': '1.0', } args_dict = { 'foreign_identifier': 'foreign_id', 'thumbnail_url': 'http://thumbnail.com', 'width': 200, 'height': 500, 'filesize': None, 'creator': 'tyler', 'creator_url': 'https://creatorurl.com', 'title': 'agreatpicture', 'meta_data': {'description': 'cat picture'}, 'tags': [{'name': 'tag1', 'provider': 'testing'}], 'watermarked': 'f', 'provider': 'testing_provider', 'source': 'testing_source' } args_dict.update(req_args_dict) test_image = image.Image(**args_dict) actual_row = image_store._create_tsv_row( test_image ) expect_row = '\t'.join([ 'foreign_id', 'https://landing_page.com', 'http://imageurl.com', 'http://thumbnail.com', '200', '500', '\\N', 'testlicense', '1.0', 'tyler', 'https://creatorurl.com', 'agreatpicture', '{"description": "cat picture"}', '[{"name": "tag1", "provider": "testing"}]', 'f', 'testing_provider', 'testing_source' ]) + '\n' assert expect_row == actual_row
27.962025
79
0.642825
2,582
22,090
5.138652
0.091789
0.052759
0.035047
0.052759
0.764923
0.720832
0.709753
0.67546
0.652547
0.607024
0
0.009948
0.24459
22,090
789
80
27.997465
0.785162
0.00421
0
0.643478
0
0
0.171092
0.003046
0
0
0
0
0.044928
1
0.062319
false
0
0.007246
0.017391
0.086957
0
0
0
0
null
0
0
0
0
1
1
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
60008a75a289dd5232f1480d185bec635fc50d31
1,476
py
Python
src/utils/utilities.py
alex-smtv/FreePIE-Joystick-Mapper
82f80e235b546ddcba463188aef93153d7e5ac91
[ "MIT" ]
1
2022-03-04T07:53:54.000Z
2022-03-04T07:53:54.000Z
src/utils/utilities.py
alex-smtv/FreePIE-Joystick-Mapper
82f80e235b546ddcba463188aef93153d7e5ac91
[ "MIT" ]
null
null
null
src/utils/utilities.py
alex-smtv/FreePIE-Joystick-Mapper
82f80e235b546ddcba463188aef93153d7e5ac91
[ "MIT" ]
null
null
null
from collections import Iterable def is_iterable(obj): return isinstance(obj, Iterable) # https://stackoverflow.com/a/1123026 # Simulate anonymous class: basically use a dict like it's an Object class Bunch(object): def __init__(self, **kwds): self.__dict__.update(kwds) def __eq__(self, other): return self.__dict__ == other.__dict__ # def guarantee_to_be_tuple(maybe_tuple): # return (maybe_tuple,) if type(maybe_tuple) is not tuple else maybe_tuple def tuple_it_if_needed(maybe_tuple): if type(maybe_tuple) is list: return tuple(maybe_tuple) else: return maybe_tuple if type(maybe_tuple) is tuple else (maybe_tuple,) def sort_keep_unique_tuple_list(given_tuple_list): if not isinstance(given_tuple_list, (tuple, list)): raise ValueError("'sort_keep_unique_tuple' got called with a parameter that is not a tuple or a list (specified: {}).".format(type(given_tuple_list))) return tuple( sorted( set(given_tuple_list), reverse = False ) ) # The range of values from a joystick axis is not the same as in a vjoy def convert_val_joy_to_vjoy(value, joy_max_axis, vjoy_max_axis): return (value * vjoy_max_axis)/joy_max_axis # Taken from FreePie, more info on: # https://stackoverflow.com/a/5295202 # [xMin, xMax] --> [yMin, yMax] # x = the number def scale_val(x, xMin, xMax, yMin, yMax): return yMin + 1.0 *(yMax - yMin)*(x - xMin)/(xMax - xMin)
33.545455
158
0.699864
223
1,476
4.340807
0.408072
0.103306
0.057851
0.049587
0.144628
0.099174
0.099174
0.070248
0
0
0
0.013536
0.199187
1,476
44
159
33.545455
0.805415
0.27439
0
0
0
0
0.09322
0.022599
0
0
0
0
0
1
0.269231
false
0
0.038462
0.153846
0.615385
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
6017e8bdd53481baaa43510168b00072df9a1810
303
py
Python
PyObjCTest/test_nsextensionrequesthandling.py
linuxfood/pyobjc-framework-Cocoa-test
3475890f165ab26a740f13d5afe4c62b4423a140
[ "MIT" ]
null
null
null
PyObjCTest/test_nsextensionrequesthandling.py
linuxfood/pyobjc-framework-Cocoa-test
3475890f165ab26a740f13d5afe4c62b4423a140
[ "MIT" ]
null
null
null
PyObjCTest/test_nsextensionrequesthandling.py
linuxfood/pyobjc-framework-Cocoa-test
3475890f165ab26a740f13d5afe4c62b4423a140
[ "MIT" ]
null
null
null
import Foundation # noqa: F401 from PyObjCTools.TestSupport import TestCase, min_sdk_level, onlyOn64Bit import objc class TestNSExtensionRequestHandling(TestCase): @min_sdk_level("10.10") @onlyOn64Bit def testProtocols10_10(self): objc.protocolNamed("NSExtensionRequestHandling")
27.545455
72
0.782178
31
303
7.483871
0.677419
0.094828
0.12069
0.163793
0
0
0
0
0
0
0
0.057692
0.141914
303
10
73
30.3
0.834615
0.033003
0
0
0
0
0.106529
0.089347
0
0
0
0
0
1
0.125
false
0
0.375
0
0.625
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
602af8b87504a0795e3ddb942ad5d884cab93b7d
363
py
Python
python/leetcode/top-interview-questions/arrays/04_contains_duplicate.py
holyketzer/ctci_v6
8877093c3f6744887a4c04ffcdee44d3592170c8
[ "MIT" ]
1
2021-07-04T19:07:04.000Z
2021-07-04T19:07:04.000Z
python/leetcode/top-interview-questions/arrays/04_contains_duplicate.py
holyketzer/ctci_v6
8877093c3f6744887a4c04ffcdee44d3592170c8
[ "MIT" ]
null
null
null
python/leetcode/top-interview-questions/arrays/04_contains_duplicate.py
holyketzer/ctci_v6
8877093c3f6744887a4c04ffcdee44d3592170c8
[ "MIT" ]
1
2020-12-22T21:20:35.000Z
2020-12-22T21:20:35.000Z
class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ values = set([]) for v in nums: if v in values: return True else: values.add(v) return False print Solution().containsDuplicate([1, 2, 3, 4, 5]) print Solution().containsDuplicate([1, 2, 3, 4, 5, 1])
19.105263
54
0.570248
48
363
4.3125
0.604167
0.028986
0.289855
0.299517
0.338164
0.338164
0.338164
0.338164
0
0
0
0.042308
0.283747
363
18
55
20.166667
0.753846
0
0
0
0
0
0
0
0
0
0
0
0
0
null
null
0
0
null
null
0.181818
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
3
606c060ff7e3f4b487fc11c93124aa3ae966ea71
117
py
Python
src/Python/Turtle/08B-ifelse.py
programmer1017/MathTech
5d7a9692d77a4a379824f691ae1cba3b0d2d4d59
[ "MIT" ]
null
null
null
src/Python/Turtle/08B-ifelse.py
programmer1017/MathTech
5d7a9692d77a4a379824f691ae1cba3b0d2d4d59
[ "MIT" ]
null
null
null
src/Python/Turtle/08B-ifelse.py
programmer1017/MathTech
5d7a9692d77a4a379824f691ae1cba3b0d2d4d59
[ "MIT" ]
null
null
null
a = 3 if a ==2: print("A") if a==3: print("B") if a==4: print("C") else: print("D")
6.882353
14
0.358974
20
117
2.1
0.5
0.214286
0
0
0
0
0
0
0
0
0
0.057971
0.410256
117
16
15
7.3125
0.550725
0
0
0
0
0
0.034188
0
0
0
0
0
0
1
0
false
0
0
0
0
0.444444
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
3
60988495898da69dafc27099ea6b8eff8b168b45
60
py
Python
code/abc131_a_03.py
KoyanagiHitoshi/AtCoder
731892543769b5df15254e1f32b756190378d292
[ "MIT" ]
3
2019-08-16T16:55:48.000Z
2021-04-11T10:21:40.000Z
code/abc131_a_03.py
KoyanagiHitoshi/AtCoder
731892543769b5df15254e1f32b756190378d292
[ "MIT" ]
null
null
null
code/abc131_a_03.py
KoyanagiHitoshi/AtCoder
731892543769b5df15254e1f32b756190378d292
[ "MIT" ]
null
null
null
S=input() print("Good" if S[0]!=S[1]!=S[2]!=S[3] else "Bad")
30
50
0.533333
15
60
2.133333
0.733333
0
0
0
0
0
0
0
0
0
0
0.072727
0.083333
60
2
50
30
0.509091
0
0
0
0
0
0.114754
0
0
0
0
0
0
1
0
false
0
0
0
0
0.5
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
3
60998205c38d4a615dc601d1dd84d291363c2449
335
py
Python
msgiver/setting_base.py
tanish-kr/msgiver
c2f266f3b955869352b7a31ca032da89db4d69b8
[ "MIT" ]
2
2017-04-13T16:08:55.000Z
2017-10-06T05:25:55.000Z
msgiver/setting_base.py
tanish-kr/msgiver
c2f266f3b955869352b7a31ca032da89db4d69b8
[ "MIT" ]
8
2017-03-31T08:31:13.000Z
2017-04-13T16:07:06.000Z
msgiver/setting_base.py
tanish-kr/msgiver
c2f266f3b955869352b7a31ca032da89db4d69b8
[ "MIT" ]
1
2018-05-23T02:35:54.000Z
2018-05-23T02:35:54.000Z
# -*- coding: utf-8 -*- import six from abc import ABCMeta, abstractmethod @six.add_metaclass(ABCMeta) class SettingBase(object): @abstractmethod def generate(self, args): """ Generate setting file :param dict args: setting parameter :raises ParseError: """ pass
18.611111
47
0.59403
33
335
6
0.787879
0
0
0
0
0
0
0
0
0
0
0.004329
0.310448
335
17
48
19.705882
0.852814
0.298507
0
0
1
0
0
0
0
0
0
0
0
1
0.142857
false
0.142857
0.285714
0
0.571429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
3
609a747f6ba8d4d6690824b24063e36ac3e4f80d
41
py
Python
src/abstract_map_simulator/__init__.py
btalb/abstract_map_simulator
59e0d4bbe67b20937156aa7808c877a237853561
[ "BSD-3-Clause" ]
1
2021-02-02T08:37:37.000Z
2021-02-02T08:37:37.000Z
src/abstract_map_simulator/__init__.py
btalb/abstract_map_simulator
59e0d4bbe67b20937156aa7808c877a237853561
[ "BSD-3-Clause" ]
null
null
null
src/abstract_map_simulator/__init__.py
btalb/abstract_map_simulator
59e0d4bbe67b20937156aa7808c877a237853561
[ "BSD-3-Clause" ]
null
null
null
__all__ = ["simulator", "tags", "tools"]
20.5
40
0.609756
4
41
5.25
1
0
0
0
0
0
0
0
0
0
0
0
0.121951
41
1
41
41
0.583333
0
0
0
0
0
0.439024
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
60acce7453d89d6df9bbe8e4209a3fbcafabd3d0
442
py
Python
tradeiobot/bot/keyboards.py
hcv57/tradeio-bot
a4c9f96a104e20ca0618d8d787cfef3599c8ebb7
[ "MIT" ]
2
2018-10-28T18:47:02.000Z
2019-10-09T14:52:04.000Z
tradeiobot/bot/keyboards.py
hcv57/tradeio-bot
a4c9f96a104e20ca0618d8d787cfef3599c8ebb7
[ "MIT" ]
null
null
null
tradeiobot/bot/keyboards.py
hcv57/tradeio-bot
a4c9f96a104e20ca0618d8d787cfef3599c8ebb7
[ "MIT" ]
null
null
null
from telegram import ReplyKeyboardMarkup, KeyboardButton def main_keyboard(): # http://unicode.org/emoji/charts/full-emoji-list.html return ReplyKeyboardMarkup([ [KeyboardButton('/balance (beta)')], [KeyboardButton('/markets 📈'), KeyboardButton('/volume 💰'), KeyboardButton('/exchange 🚀')], [KeyboardButton('/token 💎'), KeyboardButton('/progress 🚦'), KeyboardButton('/about ℹ')] ], resize_keyboard=True)
44.2
99
0.683258
43
442
7.093023
0.767442
0.216393
0
0
0
0
0
0
0
0
0
0
0.147059
442
10
100
44.2
0.795756
0.117647
0
0
0
0
0.18509
0
0
0
0
0
0
1
0.142857
true
0
0.142857
0.142857
0.428571
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
1
0
0
0
3
60be1c6e3c40e74413e07dad8631cb04a8b477b5
241
py
Python
meregistro/apps/seguridad/forms/BloquearUsuarioForm.py
MERegistro/meregistro
6cde3cab2bd1a8e3084fa38147de377d229391e3
[ "BSD-3-Clause" ]
null
null
null
meregistro/apps/seguridad/forms/BloquearUsuarioForm.py
MERegistro/meregistro
6cde3cab2bd1a8e3084fa38147de377d229391e3
[ "BSD-3-Clause" ]
null
null
null
meregistro/apps/seguridad/forms/BloquearUsuarioForm.py
MERegistro/meregistro
6cde3cab2bd1a8e3084fa38147de377d229391e3
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: UTF-8 -*- from django import forms from apps.seguridad.models import MotivoBloqueo class BloquearUsuarioForm(forms.Form): motivo = forms.ModelChoiceField(queryset=MotivoBloqueo.objects.filter(accion='L'), required=True)
26.777778
101
0.771784
28
241
6.642857
0.821429
0
0
0
0
0
0
0
0
0
0
0.004651
0.107884
241
8
102
30.125
0.860465
0.087137
0
0
0
0
0.004587
0
0
0
0
0
0
1
0
false
0
0.5
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
60cae5d49eeb54615f1395db5135eaa614fa6434
2,408
py
Python
0-python-tutorial/25-dates05_strftime09_Y.py
luis2ra/py3-00-w3schools
6bb851837f8ef9520491d13fa2c909047c9b18cf
[ "MIT" ]
null
null
null
0-python-tutorial/25-dates05_strftime09_Y.py
luis2ra/py3-00-w3schools
6bb851837f8ef9520491d13fa2c909047c9b18cf
[ "MIT" ]
null
null
null
0-python-tutorial/25-dates05_strftime09_Y.py
luis2ra/py3-00-w3schools
6bb851837f8ef9520491d13fa2c909047c9b18cf
[ "MIT" ]
null
null
null
# Demo Python Datetime - The strftime() Method ''' The strftime() Method The datetime object has a method for formatting date objects into readable strings. The method is called strftime(), and takes one parameter, format, to specify the format of the returned string. Directive Description Example %a Weekday, short version Wed %A Weekday, full version Wednesday %w Weekday as a number 0-6, 0 is Sunday 3 %d Day of month 01-31 31 %b Month name, short version Dec %B Month name, full version December %m Month as a number 01-12 12 %y Year, short version, without century 18 %Y Year, full version 2018 %H Hour 00-23 17 %I Hour 00-12 05 %p AM/PM PM %M Minute 00-59 41 %S Second 00-59 08 %f Microsecond 000000-999999 548513 %z UTC offset +0100 %Z Timezone CST %j Day number of year 001-366 365 %U Week number of year, Sunday as the first day of week, 00-53 52 %W Week number of year, Monday as the first day of week, 00-53 52 %c Local version of date and time Mon Dec 31 17:41:00 2018 %x Local version of date 12/31/18 %X Local version of time 17:41:00 %% A % character % ''' import datetime x = datetime.datetime.now() print(x) print(x.strftime("%Y"))
57.333333
111
0.354236
221
2,408
3.859729
0.484163
0.042204
0.042204
0.046893
0.058617
0.058617
0.058617
0.058617
0.058617
0
0
0.119577
0.607558
2,408
42
112
57.333333
0.783069
1.074336
0
0
0
0
0.02439
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0.5
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
3
60cb3c129ef1c9d15a4c48175b43fa012bf4c212
2,073
py
Python
backend/userauth/migrations/0001_initial.py
daeisbae/PeerOrgan-HackNYU2022
3f11f80fe101800727743e348ccb4f9135198950
[ "MIT" ]
null
null
null
backend/userauth/migrations/0001_initial.py
daeisbae/PeerOrgan-HackNYU2022
3f11f80fe101800727743e348ccb4f9135198950
[ "MIT" ]
null
null
null
backend/userauth/migrations/0001_initial.py
daeisbae/PeerOrgan-HackNYU2022
3f11f80fe101800727743e348ccb4f9135198950
[ "MIT" ]
null
null
null
# Generated by Django 4.0 on 2022-02-27 09:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='Recipient', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('phone_number', models.CharField(max_length=15)), ('address', models.CharField(max_length=100)), ('city', models.CharField(max_length=50)), ('zipcode', models.CharField(max_length=10)), ('state', models.CharField(max_length=50)), ('health_card_number', models.CharField(max_length=12)), ('birthday', models.DateField()), ('blood_group', models.CharField(max_length=3)), ('organ', models.CharField(max_length=50)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='recipient', to='auth.user')), ], ), migrations.CreateModel( name='Donor', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('phone_number', models.CharField(max_length=15)), ('birthday', models.DateField()), ('address', models.CharField(blank=True, max_length=100, null=True)), ('city', models.CharField(max_length=50)), ('state', models.CharField(max_length=50)), ('zipcode', models.CharField(max_length=10)), ('health_card_number', models.CharField(max_length=12)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='donor', to='auth.user')), ], ), ]
44.106383
135
0.569223
209
2,073
5.4689
0.339713
0.11811
0.204724
0.272966
0.593176
0.570429
0.509186
0.509186
0.435696
0.435696
0
0.031821
0.287506
2,073
46
136
45.065217
0.742045
0.020743
0
0.564103
1
0
0.121594
0.018668
0
0
0
0
0
1
0
false
0
0.051282
0
0.153846
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
60cc1908976457ed040e15fb7f078a8195fb4843
456
py
Python
bboard/main/models.py
wiky-avis/bboard
aedcba95acece3d3e679ac269b5983decee80873
[ "BSD-3-Clause" ]
null
null
null
bboard/main/models.py
wiky-avis/bboard
aedcba95acece3d3e679ac269b5983decee80873
[ "BSD-3-Clause" ]
null
null
null
bboard/main/models.py
wiky-avis/bboard
aedcba95acece3d3e679ac269b5983decee80873
[ "BSD-3-Clause" ]
null
null
null
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class AdvUser(AbstractUser): is_activated = models.BooleanField(default=True, db_index=True, verbose_name='Прошел активацию?') send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?') class Meta(AbstractUser.Meta): pass
32.571429
72
0.677632
50
456
6.08
0.64
0.065789
0.164474
0.190789
0
0
0
0
0
0
0
0
0.245614
456
13
73
35.076923
0.883721
0.052632
0
0
0
0
0.127907
0
0
0
0
0
0
1
0
false
0.111111
0.222222
0
0.666667
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
3
60d5b76d9d380a8e1b89faa0c8c1ebe8c6784c00
3,298
py
Python
program/main_sniffer/comss/ComssServiceDevelopment/connectors/udp/multicast.py
MaciejSzaflik/tirt-W4-Project
33b5796db59850f9837b4f40cf57ed614133e099
[ "MIT" ]
null
null
null
program/main_sniffer/comss/ComssServiceDevelopment/connectors/udp/multicast.py
MaciejSzaflik/tirt-W4-Project
33b5796db59850f9837b4f40cf57ed614133e099
[ "MIT" ]
1
2015-03-28T22:07:58.000Z
2015-03-29T13:28:42.000Z
Lib/site-packages/ComssServiceDevelopment/connectors/udp/multicast.py
michaellas/streaming-vid-to-gifs
ee5df22c820d4d631f0437c98a53989ecb76dca3
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import struct import marshal from ComssServiceDevelopment.connectors.base import BaseConnector class OutputMulticastConnector(BaseConnector): TIMEOUT = 0.2 TTL = 2 def __init__(self, service_instance): self._service_instance = service_instance self.sock = None self._params = {} def init(self): pass def close(self): self.__close_socket() def set_params(self, params): self._params = params def get_multicast_ip(self): return self._params['ip'] def get_multicast_port(self): return self._params['port'] def __open_socket(self): if self.sock is None: self.multicast_group = (self.get_multicast_ip(), self.get_multicast_port()) self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.settimeout(OutputMulticastConnector.TIMEOUT) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, struct.pack('b',OutputMulticastConnector.TTL)) def __close_socket(self): try: self.sock.close() except: pass self.sock = None def send(self, msg): self.__open_socket() dumped_msg = marshal.dumps(msg) try: self.sock.sendto(dumped_msg, self.multicast_group) except: pass class InputMulticastConnector(BaseConnector): TIMEOUT = 0.2 TTL = 2 def __init__(self, service_instance): self._service_instance = service_instance self.sock = None self._params = {} def init(self): pass def close(self): self.__close_socket() def set_params(self, params): self._params = params def get_multicast_ip(self): return self._params['ip'] def get_multicast_port(self): return self._params['port'] def __open_socket(self): if self.sock is None: self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except AttributeError: pass # Some systems don't support SO_REUSEPORT self.sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 20) self.sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1) # Bind to the port self.sock.bind((self.get_multicast_ip(), self.get_multicast_port())) # Tell the operating system to add the socket to the multicast group # on all interfaces. group = socket.inet_aton(self.get_multicast_ip()) # mreq = struct.pack('4sL', group, socket.INADDR_ANY) # self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) def __close_socket(self): self.sock.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP, socket.inet_aton(self.address) + socket.inet_aton('0.0.0.0')) self.sock.close() self.sock = None def read(self, buf_size=4096): self.__open_socket() data, sender_addr = self.sock.recvfrom(buf_size) return marshal.loads(data)
30.256881
132
0.637053
405
3,298
4.933333
0.241975
0.084084
0.063063
0.084084
0.548549
0.541041
0.541041
0.541041
0.406406
0.36036
0
0.008649
0.263796
3,298
109
133
30.256881
0.81425
0.093693
0
0.701299
0
0
0.006707
0
0
0
0
0
0
1
0.233766
false
0.064935
0.051948
0.051948
0.428571
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
3
60f43aae59d04a1a2609e3a410e77c35eb861b44
89
py
Python
core/tools/safely_open.py
3b295/FolderDiffTool
fdd014fbdf92e3011b645c89a7c87a8049699e26
[ "Apache-2.0" ]
null
null
null
core/tools/safely_open.py
3b295/FolderDiffTool
fdd014fbdf92e3011b645c89a7c87a8049699e26
[ "Apache-2.0" ]
null
null
null
core/tools/safely_open.py
3b295/FolderDiffTool
fdd014fbdf92e3011b645c89a7c87a8049699e26
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from functools import partial s_open = partial(open, mode='r')
14.833333
32
0.651685
13
89
4.384615
0.846154
0
0
0
0
0
0
0
0
0
0
0.013514
0.168539
89
5
33
17.8
0.756757
0.235955
0
0
0
0
0.015152
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
8809a4b0bfafe5c9cfc931166934f88c98d5ffa6
125
py
Python
btc_tracker_engine/__init__.py
metalerk/4btc
ee9ec1a6fcea1b489bd8afa9c3a25c025e022cb0
[ "MIT" ]
null
null
null
btc_tracker_engine/__init__.py
metalerk/4btc
ee9ec1a6fcea1b489bd8afa9c3a25c025e022cb0
[ "MIT" ]
null
null
null
btc_tracker_engine/__init__.py
metalerk/4btc
ee9ec1a6fcea1b489bd8afa9c3a25c025e022cb0
[ "MIT" ]
null
null
null
from .tracker import CoinDeskTracker from .helper_functions import rate_diff_percentage __all__ = [ 'CoinDeskTracker', ]
20.833333
50
0.8
13
125
7.153846
0.769231
0
0
0
0
0
0
0
0
0
0
0
0.136
125
6
51
20.833333
0.861111
0
0
0
0
0
0.119048
0
0
0
0
0
0
1
0
false
0
0.4
0
0.4
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
715c3e9ce6e40b1d124764f645064e8e628f0a23
134
py
Python
Practice_problems/Pyramid.py
riyabhatia26/Python-Programming
2882728982c15c3b6380033eb2e90761b538dd93
[ "MIT" ]
3
2020-08-07T04:33:19.000Z
2021-10-06T08:58:01.000Z
Practice_problems/Pyramid.py
riyabhatia26/Python-Programming
2882728982c15c3b6380033eb2e90761b538dd93
[ "MIT" ]
null
null
null
Practice_problems/Pyramid.py
riyabhatia26/Python-Programming
2882728982c15c3b6380033eb2e90761b538dd93
[ "MIT" ]
2
2021-10-06T08:58:05.000Z
2021-10-06T09:46:42.000Z
n = int(input("Enter the number of of rows: ")) for i in range(1,n+1): for j in range(1,i+1): print(j,end="") print()
22.333333
47
0.544776
27
134
2.703704
0.592593
0.191781
0.219178
0
0
0
0
0
0
0
0
0.040404
0.261194
134
6
48
22.333333
0.69697
0
0
0
0
0
0.216418
0
0
0
0
0
0
1
0
false
0
0
0
0
0.4
1
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
71822209871a10beba1863a09fb26b7d36f3b8bd
242
py
Python
myTests/Employer.py
Kauanphbbb/analise_e_projeto
8fbcffd232a48e5d2ca8557e88680d48ffffcf12
[ "MIT" ]
null
null
null
myTests/Employer.py
Kauanphbbb/analise_e_projeto
8fbcffd232a48e5d2ca8557e88680d48ffffcf12
[ "MIT" ]
null
null
null
myTests/Employer.py
Kauanphbbb/analise_e_projeto
8fbcffd232a48e5d2ca8557e88680d48ffffcf12
[ "MIT" ]
null
null
null
from PhysicalPerson import PhysicalPerson class Employer(PhysicalPerson): def __init__(self, name, cpf, birthday, rg, vaccinationStatus, monthlyIncome, jobRole): self.monthlyIncome = monthlyIncome self.jobRole = jobRole
30.25
91
0.752066
23
242
7.73913
0.652174
0
0
0
0
0
0
0
0
0
0
0
0.177686
242
7
92
34.571429
0.894472
0
0
0
0
0
0
0
0
0
0
0
0
1
0.2
false
0
0.2
0
0.6
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
3
7186fffe4a4ebf05517b4b566e8bbb48660a6b8f
375
py
Python
bacdive/tests/test_DSMZClient.py
cameronmartino/BacDivePy
b3433ded1328a1e7b5b1cc3858ffd5367a91df89
[ "BSD-2-Clause" ]
4
2021-04-02T13:18:48.000Z
2022-02-04T09:26:32.000Z
bacdive/tests/test_DSMZClient.py
cameronmartino/BacDivePy
b3433ded1328a1e7b5b1cc3858ffd5367a91df89
[ "BSD-2-Clause" ]
1
2019-07-01T14:58:51.000Z
2019-09-24T18:04:03.000Z
bacdive/tests/test_DSMZClient.py
cameronmartino/BacDivePy
b3433ded1328a1e7b5b1cc3858ffd5367a91df89
[ "BSD-2-Clause" ]
1
2019-07-24T10:42:21.000Z
2019-07-24T10:42:21.000Z
import unittest # from bacdive.DSMZClient import retrieve, DSMZ_login, Dive class TestDSMZClient(unittest.TestCase): def setUp(self): pass def test_retrieve(self): # TODO pass def test_DSMZ_login(self): # TODO pass def test_Dive(self): # TODO pass if __name__ == "__main__": unittest.main()
15
59
0.602667
42
375
5.071429
0.5
0.098592
0.15493
0.140845
0.178404
0
0
0
0
0
0
0
0.314667
375
24
60
15.625
0.828794
0.192
0
0.333333
0
0
0.026846
0
0
0
0
0.041667
0
1
0.333333
false
0.333333
0.083333
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
1
0
1
0
0
0
0
0
3
719452b52e7d5d20be403647c29452e81e47f67e
4,274
py
Python
python/generated/test/test_sling_api.py
mbloch1986/swagger-aem
599baa705dd4db5ae2b30a637e5bcd7d3f886e85
[ "Apache-2.0" ]
39
2016-10-02T06:45:12.000Z
2021-09-08T20:39:53.000Z
python/generated/test/test_sling_api.py
mbloch1986/swagger-aem
599baa705dd4db5ae2b30a637e5bcd7d3f886e85
[ "Apache-2.0" ]
35
2016-11-02T05:06:34.000Z
2021-09-03T06:03:08.000Z
python/generated/test/test_sling_api.py
mbloch1986/swagger-aem
599baa705dd4db5ae2b30a637e5bcd7d3f886e85
[ "Apache-2.0" ]
23
2016-11-07T04:14:42.000Z
2021-02-15T09:49:13.000Z
# coding: utf-8 """ Adobe Experience Manager (AEM) API Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API OpenAPI spec version: 2.2.0 Contact: opensource@shinesolutions.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import swaggeraem from swaggeraem.rest import ApiException from swaggeraem.apis.sling_api import SlingApi class TestSlingApi(unittest.TestCase): """ SlingApi unit test stubs """ def setUp(self): self.api = swaggeraem.apis.sling_api.SlingApi() def tearDown(self): pass def test_delete_agent(self): """ Test case for delete_agent """ pass def test_delete_node(self): """ Test case for delete_node """ pass def test_get_agent(self): """ Test case for get_agent """ pass def test_get_agents(self): """ Test case for get_agents """ pass def test_get_authorizable_keystore(self): """ Test case for get_authorizable_keystore """ pass def test_get_keystore(self): """ Test case for get_keystore """ pass def test_get_node(self): """ Test case for get_node """ pass def test_get_package(self): """ Test case for get_package """ pass def test_get_package_filter(self): """ Test case for get_package_filter """ pass def test_get_query(self): """ Test case for get_query """ pass def test_get_truststore(self): """ Test case for get_truststore """ pass def test_get_truststore_informations(self): """ Test case for get_truststore_informations """ pass def test_post_agent(self): """ Test case for post_agent """ pass def test_post_authorizable_keystore(self): """ Test case for post_authorizable_keystore """ pass def test_post_authorizables(self): """ Test case for post_authorizables """ pass def test_post_config_adobe_granite_saml_authentication_handler(self): """ Test case for post_config_adobe_granite_saml_authentication_handler """ pass def test_post_config_apache_felix_jetty_based_http_service(self): """ Test case for post_config_apache_felix_jetty_based_http_service """ pass def test_post_config_apache_sling_dav_ex_servlet(self): """ Test case for post_config_apache_sling_dav_ex_servlet """ pass def test_post_config_apache_sling_get_servlet(self): """ Test case for post_config_apache_sling_get_servlet """ pass def test_post_config_apache_sling_referrer_filter(self): """ Test case for post_config_apache_sling_referrer_filter """ pass def test_post_node(self): """ Test case for post_node """ pass def test_post_node_rw(self): """ Test case for post_node_rw """ pass def test_post_path(self): """ Test case for post_path """ pass def test_post_query(self): """ Test case for post_query """ pass def test_post_tree_activation(self): """ Test case for post_tree_activation """ pass def test_post_truststore(self): """ Test case for post_truststore """ pass def test_post_truststore_pkcs12(self): """ Test case for post_truststore_pkcs12 """ pass if __name__ == '__main__': unittest.main()
16.893281
82
0.542583
451
4,274
4.791574
0.199557
0.08746
0.137436
0.187413
0.652476
0.37205
0.201296
0.131421
0.039796
0
0
0.003048
0.385821
4,274
252
83
16.960317
0.82019
0.287085
0
0.411765
0
0
0.00377
0
0
0
0
0
0
1
0.426471
false
0.411765
0.102941
0
0.544118
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
3
71ab4de453d014d1b92793397adb13810a01a2b4
147
py
Python
shard/strategy/id_generation/base.py
ridi/django-shard-library
405e1c213420e095f776d8d2969a147bb0793d9c
[ "BSD-3-Clause" ]
17
2018-03-12T11:37:14.000Z
2021-12-09T15:30:52.000Z
shard/strategy/id_generation/base.py
ridi/django-shard-library
405e1c213420e095f776d8d2969a147bb0793d9c
[ "BSD-3-Clause" ]
12
2018-03-12T10:39:39.000Z
2018-08-21T03:26:09.000Z
shard/strategy/id_generation/base.py
ridi/django-shard-library
405e1c213420e095f776d8d2969a147bb0793d9c
[ "BSD-3-Clause" ]
3
2018-03-12T10:32:11.000Z
2021-04-02T06:24:14.000Z
__all__ = ('BaseIDGenerationStrategy', ) class BaseIDGenerationStrategy: def get_next_id(self, instance): raise NotImplementedError
18.375
40
0.748299
12
147
8.666667
0.916667
0
0
0
0
0
0
0
0
0
0
0
0.176871
147
7
41
21
0.859504
0
0
0
0
0
0.164384
0.164384
0
0
0
0
0
1
0.25
false
0
0
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
71b296f5b2e96558e10ced398d976a5135d6c017
1,041
py
Python
aiotdlib/api/types/chat_invite_link_counts.py
jraylan/aiotdlib
4528fcfca7c5c69b54a878ce6ce60e934a2dcc73
[ "MIT" ]
null
null
null
aiotdlib/api/types/chat_invite_link_counts.py
jraylan/aiotdlib
4528fcfca7c5c69b54a878ce6ce60e934a2dcc73
[ "MIT" ]
null
null
null
aiotdlib/api/types/chat_invite_link_counts.py
jraylan/aiotdlib
4528fcfca7c5c69b54a878ce6ce60e934a2dcc73
[ "MIT" ]
null
null
null
# =============================================================================== # # # # This file has been generated automatically!! Do not change this manually! # # # # =============================================================================== # from __future__ import annotations from pydantic import Field from .chat_invite_link_count import ChatInviteLinkCount from ..base_object import BaseObject class ChatInviteLinkCounts(BaseObject): """ Contains a list of chat invite link counts :param invite_link_counts: List of invite linkcounts :type invite_link_counts: :class:`list[ChatInviteLinkCount]` """ ID: str = Field("chatInviteLinkCounts", alias="@type") invite_link_counts: list[ChatInviteLinkCount] @staticmethod def read(q: dict) -> ChatInviteLinkCounts: return ChatInviteLinkCounts.construct(**q)
35.896552
83
0.50048
78
1,041
6.5
0.564103
0.098619
0.126233
0.078895
0
0
0
0
0
0
0
0
0.289145
1,041
28
84
37.178571
0.685135
0.539866
0
0
1
0
0.057339
0
0
0
0
0
0
1
0.1
false
0
0.4
0.1
0.9
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
71bf615becfd4f40932753f9255cc44ca6c55885
287
py
Python
pprint_test.py
a2gs/pythonStudy
e790e223a05fd50a5bcaf1240ef24ff60f361cdd
[ "MIT" ]
null
null
null
pprint_test.py
a2gs/pythonStudy
e790e223a05fd50a5bcaf1240ef24ff60f361cdd
[ "MIT" ]
null
null
null
pprint_test.py
a2gs/pythonStudy
e790e223a05fd50a5bcaf1240ef24ff60f361cdd
[ "MIT" ]
null
null
null
import pprint stuff = {1:'abc', 2:'def', 3:['ghi', 'xyz'], 4:'jlm', 5:'nop', 6:["a","b","c","d", {"asd":"123", "cvb":345, "ert":[1,2,3,4,5], "rty":"abcdef"}], 7: "rst", 8:{1:1, 2:2, 3:3, 4:4}} pp = pprint.PrettyPrinter(indent = 2, compact = False, depth = None) pp.pprint(stuff)
41
179
0.519164
54
287
2.759259
0.666667
0.147651
0
0
0
0
0
0
0
0
0
0.113821
0.142857
287
7
180
41
0.49187
0
0
0
0
0
0.163121
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0.75
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
3
71d392b5589888a500ffb2543567f3ea97439128
51
py
Python
ejemplo1.py
albertopinedaorozco/ejerciciospython
a475c5d45a25522ed7b26d7c28cbba7531592505
[ "MIT" ]
null
null
null
ejemplo1.py
albertopinedaorozco/ejerciciospython
a475c5d45a25522ed7b26d7c28cbba7531592505
[ "MIT" ]
null
null
null
ejemplo1.py
albertopinedaorozco/ejerciciospython
a475c5d45a25522ed7b26d7c28cbba7531592505
[ "MIT" ]
null
null
null
nombre = input("Digite su nombre ") print (nombre)
17
35
0.705882
7
51
5.142857
0.714286
0
0
0
0
0
0
0
0
0
0
0
0.156863
51
2
36
25.5
0.837209
0
0
0
0
0
0.333333
0
0
0
0
0
0
1
0
false
0
0
0
0
0.5
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
3
71e6741e41da468635f107f88e4647bd23d7801d
192
py
Python
src/fixed_point/calcpi.py
LagMeester4000/Lum
fb462f93540e6dd3b024f37e7decdd0dcc5aa97e
[ "MIT" ]
null
null
null
src/fixed_point/calcpi.py
LagMeester4000/Lum
fb462f93540e6dd3b024f37e7decdd0dcc5aa97e
[ "MIT" ]
null
null
null
src/fixed_point/calcpi.py
LagMeester4000/Lum
fb462f93540e6dd3b024f37e7decdd0dcc5aa97e
[ "MIT" ]
null
null
null
import math pi = math.pi fix_bit_pow = 65536 run = 1 res = fix_bit_pow * 3; while run: if res / fix_bit_pow > pi: print(res) break res += 1
13.714286
31
0.5
29
192
3.103448
0.517241
0.2
0.3
0.266667
0
0
0
0
0
0
0
0.072072
0.421875
192
14
32
13.714286
0.738739
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.1
0
0.1
0.1
1
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
e0971974dfacb464918dd37993afaa9789854230
3,632
py
Python
pkmodel/tests/test_protocol.py
D-own-T-o-P-rogramme/PK_Model
a413a4c8edc2dc76513afb07b312acb34f3f6729
[ "MIT" ]
1
2020-10-23T17:01:11.000Z
2020-10-23T17:01:11.000Z
pkmodel/tests/test_protocol.py
Down-To-Programme/PK_Model
a413a4c8edc2dc76513afb07b312acb34f3f6729
[ "MIT" ]
39
2020-10-21T15:03:19.000Z
2022-03-12T00:51:00.000Z
pkmodel/tests/test_protocol.py
D-own-T-o-P-rogramme/PK_Model
a413a4c8edc2dc76513afb07b312acb34f3f6729
[ "MIT" ]
1
2021-02-07T17:07:45.000Z
2021-02-07T17:07:45.000Z
import unittest import pkmodel as pk import numpy as np class ProtocolTest(unittest.TestCase): """ Tests the :class:`Protocol` class. """ def test_create(self): """ Tests Protocol creation. """ dosing = pk.Protocol(dose_amount=10, subcutaneous=True, k_a=0.3, continuous=True, continuous_period=[1, 2], instantaneous=True, dose_times=[0, 1, 2, 3]) self.assertEqual(dosing.dose_amount, 10) self.assertEqual(dosing.subcutaneous, True) self.assertEqual(dosing.k_a, 0.3) self.assertEqual(dosing.continuous, True) self.assertEqual(dosing.continuous_period, [1, 2]) self.assertEqual(dosing.instantaneous, True) self.assertEqual(dosing.dose_times, [0, 1, 2, 3]) def test_dose_function(self): dosing = pk.Protocol(dose_amount=10, subcutaneous=True, k_a=0.3, continuous=True, continuous_period=[1, 2], instantaneous=False) dose_0 = dosing.dose_time_function(0) dose_1 = dosing.dose_time_function(0.5) dose_2 = dosing.dose_time_function(1.1) dose_3 = dosing.dose_time_function(1.8) dose_4 = dosing.dose_time_function(4) self.assertEqual(dose_0, 0) self.assertEqual(dose_1, 0) self.assertEqual(dose_2, 10) self.assertEqual(dose_3, 10) self.assertEqual(dose_4, 0) def test_both_dose(self): dosing = pk.Protocol(dose_amount=10, subcutaneous=True, k_a=0.3, continuous=True, continuous_period=[1, 2], instantaneous=True, instant_doses=[10, 20], dose_times=[0.5, 1.5]) dose_0 = dosing.dose_time_function(0.5) dose_1 = dosing.dose_time_function(1.5) self.assertLessEqual(dose_0 - (10 / (0.02 * np.sqrt(2 * np.pi))), 0.0001) self.assertLessEqual(dose_1 - (10 + 20 / (0.02 * np.sqrt(2 * np.pi))), 0.0001) def test_change_dose(self): dosing = pk.Protocol() self.assertEqual(dosing.dose_amount, 1) dosing.change_dose(100) self.assertEqual(dosing.dose_amount, 100) def test_modify_dose_type(self): dosing = pk.Protocol() self.assertEqual(dosing.subcutaneous, False) dosing.modify_dose_type(True, 0.3) self.assertEqual(dosing.subcutaneous, True) self.assertEqual(dosing.k_a, 0.3) def test_make_continuous(self): dosing = pk.Protocol() self.assertEqual(dosing.continuous, False) self.assertEqual(dosing.continuous_period, [0, 0]) dosing.make_continuous(4, 10) self.assertEqual(dosing.continuous, True) self.assertEqual(dosing.continuous_period, [4, 10]) def test_add_dose(self): dosing = pk.Protocol(instantaneous=False, instant_doses=[], dose_times=[]) self.assertEqual(dosing.instantaneous, False) self.assertEqual(dosing.dose_times, []) self.assertEqual(dosing.instant_doses, []) dosing.add_dose(1, 1) self.assertEqual(dosing.instantaneous, True) self.assertEqual(dosing.dose_times, [1]) self.assertEqual(dosing.instant_doses, [1]) dosing.add_dose(5, 1) self.assertEqual(dosing.instantaneous, True) self.assertEqual(dosing.dose_times, [1, 5]) self.assertEqual(dosing.instant_doses, [1, 1])
37.443299
78
0.592786
433
3,632
4.794457
0.12933
0.216763
0.25289
0.084297
0.682563
0.546243
0.491811
0.389692
0.389692
0.371387
0
0.04918
0.294604
3,632
96
79
37.833333
0.761124
0.016244
0
0.306667
0
0
0
0
0
0
0
0
0.426667
1
0.093333
false
0
0.04
0
0.146667
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
0
0
0
0
0
0
3
e0a4638147c0b02325927927b7b3383f43c66ea6
200
py
Python
242. Valid Anagram.py
Jorewang/LeetCode_Solutions
0c483a915e2a8b3bfc4bcb4b5a35df3dd0dbe8ba
[ "Apache-2.0" ]
2
2020-06-13T06:37:50.000Z
2020-06-13T06:37:52.000Z
242. Valid Anagram.py
Jorewang/LeetCode_Solutions
0c483a915e2a8b3bfc4bcb4b5a35df3dd0dbe8ba
[ "Apache-2.0" ]
null
null
null
242. Valid Anagram.py
Jorewang/LeetCode_Solutions
0c483a915e2a8b3bfc4bcb4b5a35df3dd0dbe8ba
[ "Apache-2.0" ]
null
null
null
from collections import Counter class Solution(object): def isAnagram(self, s, t): return Counter(s) == Counter(t) if __name__ == '__main__': print(Solution().isAnagram('a', 'b'))
18.181818
41
0.645
25
200
4.84
0.76
0
0
0
0
0
0
0
0
0
0
0
0.2
200
10
42
20
0.75625
0
0
0
0
0
0.05
0
0
0
0
0
0
1
0.166667
false
0
0.166667
0.166667
0.666667
0.166667
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
3
e0dd1383c27a17a10fa6c07bc5d32a610c5ef0f5
7,279
py
Python
include/wxPython/wx/lib/iewin.py
SWEN-712/screen-reader-brandonp728
e30c25ad2d10ce632fac0548696a61a872328f59
[ "bzip2-1.0.6" ]
3
2019-10-06T15:39:39.000Z
2020-09-29T23:51:50.000Z
include/wxPython/wx/lib/iewin.py
SWEN-712/screen-reader-brandonp728
e30c25ad2d10ce632fac0548696a61a872328f59
[ "bzip2-1.0.6" ]
9
2021-03-18T23:10:27.000Z
2022-03-11T23:43:55.000Z
include/wxPython/wx/lib/iewin.py
SWEN-712/screen-reader-brandonp728
e30c25ad2d10ce632fac0548696a61a872328f59
[ "bzip2-1.0.6" ]
2
2019-03-11T05:06:49.000Z
2019-03-22T21:48:49.000Z
#---------------------------------------------------------------------- # Name: wx.lib.iewin # Purpose: A class that allows the use of the IE web browser # ActiveX control # # Author: Robin Dunn # # Created: 22-March-2004 # Copyright: (c) 2008-2018 by Total Control Software # Licence: wxWindows license #---------------------------------------------------------------------- import wx import wx.lib.activex import comtypes.client as cc import sys if not hasattr(sys, 'frozen'): cc.GetModule('shdocvw.dll') # IWebBrowser2 and etc. from comtypes.gen import SHDocVw clsID = '{8856F961-340A-11D0-A96B-00C04FD705A2}' progID = 'Shell.Explorer.2' # Flags to be used with the RefreshPage method REFRESH_NORMAL = 0 REFRESH_IFEXPIRED = 1 REFRESH_CONTINUE = 2 REFRESH_COMPLETELY = 3 # Flags to be used with LoadUrl, Navigate, Navigate2 methods NAV_OpenInNewWindow = 0x1 NAV_NoHistory = 0x2 NAV_NoReadFromCache = 0x4 NAV_NoWriteToCache = 0x8 NAV_AllowAutosearch = 0x10 NAV_BrowserBar = 0x20 NAV_Hyperlink = 0x40 NAV_EnforceRestricted = 0x80, NAV_NewWindowsManaged = 0x0100, NAV_UntrustedForDownload = 0x0200, NAV_TrustedForActiveX = 0x0400, NAV_OpenInNewTab = 0x0800, NAV_OpenInBackgroundTab = 0x1000, NAV_KeepWordWheelText = 0x2000 #---------------------------------------------------------------------- class IEHtmlWindow(wx.lib.activex.ActiveXCtrl): def __init__(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name='IEHtmlWindow'): wx.lib.activex.ActiveXCtrl.__init__(self, parent, progID, id, pos, size, style, name) self._canGoBack = False self._canGoForward = False def LoadString(self, html): """Load the html document from a string""" if self.ctrl.Document is None: self.LoadUrl('about:blank') doc = self.ctrl.Document doc.write(html) doc.close() def LoadStream(self, stream): """ Load the html document from a Python file-like object. """ if self.ctrl.Document is None: self.LoadUrl('about:blank') doc = self.ctrl.Document for line in stream: doc.write(line) doc.close() def LoadUrl(self, URL, Flags=0): """Load the document from url.""" return self.ctrl.Navigate2(URL, Flags) def GetStringSelection(self, asHTML=True): """ Returns the contents of the selected portion of the document as either html or plain text. """ if self.ctrl.Document is None: return "" if not hasattr(sys, 'frozen'): cc.GetModule('mshtml.tlb') from comtypes.gen import MSHTML doc = self.ctrl.Document.QueryInterface(MSHTML.IHTMLDocument2) sel = doc.selection range = sel.createRange() if asHTML: return range.htmlText else: return range.text def GetText(self, asHTML=True): """ Returns the contents of the the html document as either html or plain text. """ if self.ctrl.Document is None: return "" if not hasattr(sys, 'frozen'): cc.GetModule('mshtml.tlb') from comtypes.gen import MSHTML doc = self.ctrl.Document.QueryInterface(MSHTML.IHTMLDocument2) if not asHTML: # if just fetching the text then get it from the body property return doc.body.innerText # otherwise look in the all property for idx in range(doc.all.length): # the first item with content should be the <html> tag and all its # children. item = doc.all.item(idx) if item is None: continue return item.outerHTML return "" def Print(self, showDialog=False): if showDialog: prompt = SHDocVw.OLECMDEXECOPT_PROMPTUSER else: prompt = SHDocVw.OLECMDEXECOPT_DONTPROMPTUSER self.ctrl.ExecWB(SHDocVw.OLECMDID_PRINT, prompt) def PrintPreview(self): self.ctrl.ExecWB( SHDocVw.OLECMDID_PRINTPREVIEW, SHDocVw.OLECMDEXECOPT_DODEFAULT) def GoBack(self): if self.CanGoBack(): return self.ctrl.GoBack() def GoForward(self): if self.CanGoForward(): return self.ctrl.GoForward() def CanGoBack(self): return self._canGoBack def CanGoForward(self): return self._canGoForward def GoHome(self): return self.ctrl.GoHome() def GoSearch(self): return self.ctrl.GoSearch() def Navigate(self, URL, Flags=0, TargetFrameName=None, PostData=None, Headers=None): return self.ctrl.Navigate2( URL, Flags, TargetFrameName, PostData, Headers) def RefreshPage(self, Level=REFRESH_NORMAL): return self.ctrl.Refresh2(Level) def Stop(self): return self.ctrl.Stop() def Quit(self): return self.ctrl.Quit() # COM Event handlers def CommandStateChange(self, this, command, enable): # watch the command states to know when it is possible to use # GoBack or GoForward if command == SHDocVw.CSC_NAVIGATEFORWARD: self._canGoForward = enable if command == SHDocVw.CSC_NAVIGATEBACK: self._canGoBack = enable # Getters, Setters and properties def _get_Busy(self): return self.ctrl.Busy busy = property(_get_Busy, None) def _get_Document(self): return self.ctrl.Document document = property(_get_Document, None) def _get_LocationName(self): return self.ctrl.LocationName locationname = property(_get_LocationName, None) def _get_LocationURL(self): return self.ctrl.LocationURL locationurl = property(_get_LocationURL, None) def _get_ReadyState(self): return self.ctrl.ReadyState readystate = property(_get_ReadyState, None) def _get_Offline(self): return self.ctrl.Offline def _set_Offline(self, Offline): self.ctrl.Offline = Offline offline = property(_get_Offline, _set_Offline) def _get_Silent(self): return self.ctrl.Silent def _set_Silent(self, Silent): self.ctrl.Silent = Silent silent = property(_get_Silent, _set_Silent) def _get_RegisterAsBrowser(self): return self.ctrl.RegisterAsBrowser def _set_RegisterAsBrowser(self, RegisterAsBrowser): self.ctrl.RegisterAsBrowser = RegisterAsBrowser registerasbrowser = property(_get_RegisterAsBrowser, _set_RegisterAsBrowser) def _get_RegisterAsDropTarget(self): return self.ctrl.RegisterAsDropTarget def _set_RegisterAsDropTarget(self, RegisterAsDropTarget): self.ctrl.RegisterAsDropTarget = RegisterAsDropTarget registerasdroptarget = property(_get_RegisterAsDropTarget, _set_RegisterAsDropTarget) def _get_Type(self): return self.ctrl.Type type = property(_get_Type, None) if __name__ == '__main__': app = wx.App(False) frm = wx.Frame(None, title="AX Test Window") ie = IEHtmlWindow(frm) frm.Show() import wx.lib.inspection wx.lib.inspection.InspectionTool().Show() app.MainLoop()
29.116
89
0.634428
815
7,279
5.53865
0.310429
0.058485
0.058928
0.055826
0.192734
0.156845
0.132477
0.125388
0.108994
0.108994
0
0.018965
0.253881
7,279
249
90
29.232932
0.812189
0.161835
0
0.133758
0
0
0.026549
0.006345
0
0
0.010686
0
0
1
0.210191
false
0
0.050955
0.11465
0.509554
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
e0f2446240c81c0d0ca98e32908e79ec82472a4a
4,239
py
Python
tests/unit/raptiformica/settings/load/test_try_delete_config.py
vdloo/raptiformica
e2807e5e913312034161efcbd74525a4b15b37e7
[ "MIT" ]
21
2016-09-04T11:27:31.000Z
2019-10-30T08:23:14.000Z
tests/unit/raptiformica/settings/load/test_try_delete_config.py
vdloo/raptiformica
e2807e5e913312034161efcbd74525a4b15b37e7
[ "MIT" ]
5
2017-09-17T15:59:37.000Z
2018-02-03T14:53:32.000Z
tests/unit/raptiformica/settings/load/test_try_delete_config.py
vdloo/raptiformica
e2807e5e913312034161efcbd74525a4b15b37e7
[ "MIT" ]
2
2017-11-21T18:14:51.000Z
2017-11-22T01:20:45.000Z
from urllib.error import URLError from raptiformica.settings.load import try_delete_config from tests.testcase import TestCase class TestTryDeleteConfig(TestCase): def setUp(self): self.delete = self.set_up_patch( 'raptiformica.settings.load.consul_conn.delete' ) self.mapping = { "raptiformica/meshnet/cjdns/password": "a_secret", "raptiformica/meshnet/consul/password": "a_different_secret", "raptiformica/meshnet/neighbours/a_pubkey.k/cjdns_ipv6_address": "some_ipv6_address", "raptiformica/meshnet/neighbours/a_pubkey.k/cjdns_port": 4863, "raptiformica/meshnet/neighbours/a_pubkey.k/cjdns_public_key": "a_pubkey.k", "raptiformica/meshnet/neighbours/a_pubkey.k/host": "127.0.0.1", "raptiformica/meshnet/neighbours/a_pubkey.k/ssh_port": "2200", "raptiformica/meshnet/neighbours/a_pubkey.k/uuid": "eb442c6170694b12b277c9e88d714cf2", "raptiformica/meshnet/neighbours/a_different_pubkey.k/cjdns_ipv6_address": "some_other_ipv6_address", "raptiformica/meshnet/neighbours/a_different_pubkey.k/cjdns_port": 4863, "raptiformica/meshnet/neighbours/a_different_pubkey.k/cjdns_public_key": "a_different_pubkey.k", "raptiformica/meshnet/neighbours/a_different_pubkey.k/host": "127.0.0.1", "raptiformica/meshnet/neighbours/a_different_pubkey.k/ssh_port": "2201", "raptiformica/meshnet/neighbours/a_different_pubkey.k/uuid": "eb442c6170694b12b277c9e88d714cf1", } self.get_config = self.set_up_patch( 'raptiformica.settings.load.get_config_mapping', return_value=self.mapping ) self.get_config.return_value = self.mapping self.cache_config = self.set_up_patch( 'raptiformica.settings.load.cache_config_mapping' ) self.sync_shared_config_mapping = self.set_up_patch( 'raptiformica.settings.load.sync_shared_config_mapping' ) def test_try_delete_config_deletes_key_pair_from_distributed_kv_store(self): try_delete_config('some/key') self.delete.assert_called_once_with( 'some/key', recurse=False ) def test_try_delete_config_syncs_shared_config_mapping(self): try_delete_config('some/key') self.sync_shared_config_mapping.assert_called_once_with() def test_try_delete_config_deletes_key_pair_from_distributed_kv_store_recursively_if_specified(self): try_delete_config('some/key', recurse=True) self.delete.assert_called_once_with( 'some/key', recurse=True ) def test_try_delete_config_gets_config_if_can_not_connect_to_shared_key_value_store(self): self.delete.side_effect = URLError('reason') try_delete_config('key') self.get_config.assert_called_once_with() def test_try_delete_config_caches_config_without_key_if_can_not_connect_to_shared_key_value_store(self): self.delete.side_effect = URLError('reason') try_delete_config('raptiformica/meshnet/neighbours/a_pubkey.k/uuid') del self.mapping[ 'raptiformica/meshnet/neighbours/a_pubkey.k/uuid' ] self.cache_config.assert_called_once_with(self.mapping) def test_try_delete_config_caches_config_without_entire_key_tree_if_no_shared_kv_and_recurse_is_specified(self): self.delete.side_effect = URLError('reason') try_delete_config( 'raptiformica/meshnet/neighbours/a_pubkey.k/', recurse=True ) del self.mapping['raptiformica/meshnet/neighbours/a_pubkey.k/uuid'] del self.mapping['raptiformica/meshnet/neighbours/a_pubkey.k/host'] del self.mapping['raptiformica/meshnet/neighbours/a_pubkey.k/ssh_port'] del self.mapping[ 'raptiformica/meshnet/neighbours/a_pubkey.k/cjdns_port' ] del self.mapping[ 'raptiformica/meshnet/neighbours/a_pubkey.k/cjdns_ipv6_address' ] del self.mapping[ 'raptiformica/meshnet/neighbours/a_pubkey.k/cjdns_public_key' ] self.cache_config.assert_called_once_with(self.mapping)
43.255102
116
0.707242
519
4,239
5.39499
0.17341
0.156071
0.2175
0.225
0.788571
0.734286
0.698929
0.588929
0.479643
0.305714
0
0.022647
0.197924
4,239
97
117
43.701031
0.800882
0
0
0.189873
0
0
0.391366
0.353621
0
0
0
0
0.075949
1
0.088608
false
0.025316
0.037975
0
0.139241
0
0
0
0
null
0
1
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
e0f2727a5b9384a2d061b2a573aa7b49a703998c
9,744
py
Python
cellular-automata/conways-game-of-life/conways_game_of_life.py
fraserlove/python
b449259c02e73102e37a4cd42018dbcc6b04d0ba
[ "Apache-2.0" ]
16
2020-06-11T16:54:55.000Z
2022-01-07T01:36:05.000Z
cellular-automata/conways-game-of-life/conways_game_of_life.py
fraserlove/python-projects
b449259c02e73102e37a4cd42018dbcc6b04d0ba
[ "Apache-2.0" ]
null
null
null
cellular-automata/conways-game-of-life/conways_game_of_life.py
fraserlove/python-projects
b449259c02e73102e37a4cd42018dbcc6b04d0ba
[ "Apache-2.0" ]
15
2020-06-14T08:29:50.000Z
2021-08-05T17:25:42.000Z
""" Conway's Game Of Life Cellular Automaton Developed by Fraser Love on 26/09/18 Dependencies: Pygame Ran on CPU - Reccomended to use on High-Range CPU """ import pygame, sys, random from pygame.locals import * pygame.init() session = True cells_x = 70 cells_y = 40 res = 15 cell_size = 13 start_cells = 1000 frame_rate = 30 cells = [[0 for x in range(cells_y)] for y in range(cells_x)] display = pygame.display.set_mode((cells_x*res-res+2, cells_y*res-res+2)) pygame.display.set_caption('Conway\'s Game Of Life') clock = pygame.time.Clock() display.fill(pygame.Color("black")) pygame.font.init() def intro(): heading = pygame.font.Font('freesansbold.ttf',70) TextSurf = heading.render("GAME OF LIFE", True, (255,255,255)) TextRect = TextSurf.get_rect() TextRect.center = ((cells_x*res/2),(cells_y*res/2-100)) display.blit(TextSurf, TextRect) credits = pygame.font.Font('freesansbold.ttf',20) TextSurf = credits.render("FRASER LOVE", True, (255,255,255)) TextRect = TextSurf.get_rect() TextRect.center = ((cells_x*res-90),(cells_y*res-25)) display.blit(TextSurf, TextRect) button_rand = pygame.Rect(0, 0, 150, 45) button_rand.center = ((cells_x*res/2+100),(cells_y*res/2)) button_draw = pygame.Rect(0, 0, 150, 45) button_draw.center = ((cells_x*res/2-100),(cells_y*res/2)) button_text = pygame.font.Font("freesansbold.ttf",20) rand_TextSurf = button_text.render("RANDOM", True, (0,0,0)) rand_TextRect = rand_TextSurf.get_rect() rand_TextRect.center = ((cells_x*res/2+100),(cells_y*res/2)) display.blit(rand_TextSurf, rand_TextRect) draw_TextSurf = button_text.render("DRAW", True, (0,0,0)) draw_TextRect = draw_TextSurf.get_rect() draw_TextRect.center = ((cells_x*res/2-100),(cells_y*res/2)) display.blit(draw_TextSurf, draw_TextRect) while True: rand_colour = (255,255,255) draw_colour = (255,255,255) for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = event.pos if button_rand.collidepoint(mouse_pos): sim_rand() if button_draw.collidepoint(mouse_pos): sim_draw() mouse_pos = pygame.mouse.get_pos() if button_rand.collidepoint(mouse_pos): rand_colour = (66, 134, 244) pygame.draw.rect(display, rand_colour , button_rand) if button_draw.collidepoint(mouse_pos): draw_colour = (66, 134, 244) pygame.draw.rect(display, draw_colour , button_draw) pygame.draw.rect(display, draw_colour , button_draw) pygame.draw.rect(display, rand_colour , button_rand) display.blit(rand_TextSurf, rand_TextRect) display.blit(draw_TextSurf, draw_TextRect) pygame.display.update() clock.tick(frame_rate) def sim_rand(): gen = 0 for c in range(start_cells): rand_x = random.randrange(0,cells_x) rand_y = random.randrange(0,cells_y) cells[rand_x][rand_y] = 1 pygame.draw.rect(display, (255,255,255), (rand_x*res,rand_y*res,cell_size,cell_size), 0) pygame.display.update() while session: gen += 1 pygame.display.set_caption('Conway\'s Game Of Life - Generation '+ str(gen)) clock.tick(frame_rate) display.fill(pygame.Color("black")) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit(); sys.exit(); new = [[0 for x in range(cells_y)] for y in range(cells_x)] for y in range(cells_y-1): for x in range(cells_x-1): if cells[x-1][y-1] + cells[x][y-1] + cells[x+1][y-1] + cells[x-1][y] + cells[x+1][y] + cells[x-1][y+1] + cells[x][y+1] + cells[x+1][y+1] < 2 and cells[x][y] == 1: new[x][y] = 0 elif cells[x-1][y-1] + cells[x][y-1] + cells[x+1][y-1] + cells[x-1][y] + cells[x+1][y] + cells[x-1][y+1] + cells[x][y+1] + cells[x+1][y+1] == 2 or cells[x-1][y-1] + cells[x][y-1] + cells[x+1][y-1] + cells[x-1][y] + cells[x+1][y] + cells[x-1][y+1] + cells[x][y+1] + cells[x+1][y+1] == 3 and cells[x][y] == 1: new[x][y] = cells[x][y] elif cells[x-1][y-1] + cells[x][y-1] + cells[x+1][y-1] + cells[x-1][y] + cells[x+1][y] + cells[x-1][y+1] + cells[x][y+1] + cells[x+1][y+1] > 3 and cells[x][y] == 1: new[x][y] = 0 elif cells[x-1][y-1] + cells[x][y-1] + cells[x+1][y-1] + cells[x-1][y] + cells[x+1][y] + cells[x-1][y+1] + cells[x][y+1] + cells[x+1][y+1] == 3 and cells[x][y] == 0: new[x][y] = 1 for i in range(cells_y): for j in range(cells_x): cells[j][i] = new[j][i] if cells[j][i] == 1: pygame.draw.rect(display, (255,255,255), (j*res+2,i*res+2,cell_size,cell_size), 0) pygame.display.update() def sim_draw(): gen = 0 selection = True rect_obj = [] display.fill((145, 145, 145)) for i in range(cells_y): for j in range(cells_x): cells[j][i] = 0 rect_obj.append(pygame.draw.rect(display, (0,0,0), (j*res+2,i*res+2,cell_size,cell_size), 0)) pygame.display.update() xpos = 0 ypos = 0 while selection: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit(); sys.exit(); pressed = pygame.key.get_pressed() if pressed[pygame.K_w]: pygame.draw.rect(display, (0, 0, 0), (xpos*res+2,ypos*res+2,cell_size,cell_size), 0) ypos -= 1 if pressed[pygame.K_s]: pygame.draw.rect(display, (0, 0, 0), (xpos*res+2,ypos*res+2,cell_size,cell_size), 0) ypos += 1 if pressed[pygame.K_d]: pygame.draw.rect(display, (0, 0, 0), (xpos*res+2,ypos*res+2,cell_size,cell_size), 0) xpos += 1 if pressed[pygame.K_a]: pygame.draw.rect(display, (0, 0, 0), (xpos*res+2,ypos*res+2,cell_size,cell_size), 0) xpos -= 1 if pressed[pygame.K_SPACE]: if cells[xpos][ypos] == 1: cells[xpos][ypos] = 0 elif cells[xpos][ypos] == 0: cells[xpos][ypos] = 1 if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: mouse_pos = event.pos for rect in rect_obj: if rect.collidepoint(mouse_pos): x_sel = int((rect.left-2)/res) y_sel = int((rect.top-2)/res) cells[x_sel][y_sel] = 1 if event.type == pygame.MOUSEBUTTONDOWN and event.button == 3: mouse_pos = event.pos for rect in rect_obj: if rect.collidepoint(mouse_pos): x_sel = int((rect.left-2)/res) y_sel = int((rect.top-2)/res) cells[x_sel][y_sel] = 0 if pressed[pygame.K_RETURN]: selection = False for i in range(cells_y): for j in range(cells_x): if cells[j][i] == 1: pygame.draw.rect(display, (255,255,255), (j*res+2,i*res+2,cell_size,cell_size), 0) if cells[j][i] == 0: rect_obj.append(pygame.draw.rect(display, (0,0,0), (j*res+2,i*res+2,cell_size,cell_size), 0)) pygame.draw.rect(display, Color(255, 43, 74), (xpos*res+2,ypos*res+2,cell_size,cell_size), 0) pygame.display.update() while session: gen += 1 pygame.display.set_caption('Conway\'s Game Of Life - Generation '+ str(gen)) clock.tick(frame_rate) display.fill(pygame.Color("black")) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit(); sys.exit(); new = [[0 for x in range(cells_y)] for y in range(cells_x)] for y in range(cells_y-1): for x in range(cells_x-1): if cells[x-1][y-1] + cells[x][y-1] + cells[x+1][y-1] + cells[x-1][y] + cells[x+1][y] + cells[x-1][y+1] + cells[x][y+1] + cells[x+1][y+1] < 2 and cells[x][y] == 1: new[x][y] = 0 elif cells[x-1][y-1] + cells[x][y-1] + cells[x+1][y-1] + cells[x-1][y] + cells[x+1][y] + cells[x-1][y+1] + cells[x][y+1] + cells[x+1][y+1] == 2 or cells[x-1][y-1] + cells[x][y-1] + cells[x+1][y-1] + cells[x-1][y] + cells[x+1][y] + cells[x-1][y+1] + cells[x][y+1] + cells[x+1][y+1] == 3 and cells[x][y] == 1: new[x][y] = cells[x][y] elif cells[x-1][y-1] + cells[x][y-1] + cells[x+1][y-1] + cells[x-1][y] + cells[x+1][y] + cells[x-1][y+1] + cells[x][y+1] + cells[x+1][y+1] > 3 and cells[x][y] == 1: new[x][y] = 0 elif cells[x-1][y-1] + cells[x][y-1] + cells[x+1][y-1] + cells[x-1][y] + cells[x+1][y] + cells[x-1][y+1] + cells[x][y+1] + cells[x+1][y+1] == 3 and cells[x][y] == 0: new[x][y] = 1 for i in range(cells_y): for j in range(cells_x): cells[j][i] = new[j][i] if cells[j][i] == 1: pygame.draw.rect(display, (255,255,255), (j*res+2,i*res+2,cell_size,cell_size), 0) pygame.display.update() intro()
44.697248
324
0.528838
1,535
9,744
3.257329
0.088599
0.132
0.0868
0.096
0.767
0.7416
0.7054
0.6686
0.6446
0.6178
0
0.060432
0.302032
9,744
217
325
44.903226
0.674754
0.015189
0
0.56044
0
0.005495
0.012485
0
0
0
0
0
0
1
0.016484
false
0
0.010989
0
0.032967
0
0
0
0
null
0
0
0
0
1
1
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
e0fa403dac7bd4a1434305b5e31dcc3256ef37d8
1,396
py
Python
unit1_lesson_00_understanding_assert.py
arajajyothibabu/PythonLearning
53658ba3591e284733ef8a66551dadd515ab8edc
[ "MIT" ]
null
null
null
unit1_lesson_00_understanding_assert.py
arajajyothibabu/PythonLearning
53658ba3591e284733ef8a66551dadd515ab8edc
[ "MIT" ]
null
null
null
unit1_lesson_00_understanding_assert.py
arajajyothibabu/PythonLearning
53658ba3591e284733ef8a66551dadd515ab8edc
[ "MIT" ]
null
null
null
__author__ = 'Kalyan' from placeholders import * notes = ''' This lesson introduces the basic assert statement in python. assert is generally used to 'assert' the truth of an expression. It takes the form assert <expr>, <optional message>. If <expr> evaluates to False an AssertionError is raised with the <optional message>. If is evaluates to True, nothing happens. In the tests below, replace the blanks with values so that the resulting expression is True. ''' def test_assert_true(): assert True #This should be True -- replace ___ with True. def test_assert_true_with_message(): assert True, "This is the failure message Araja Jyothi Babu" # replace ___ with True to stop seeing the assertion error def test_assert_equality(): assert 7 == 2 + 5 #replace __ with the expected value #Fill in __ in the statements below to make the asserts succeed def test_make_assert_true_1(): assert 8 > 7, "Fill in a value greater than 7" #you can use the interpreter to find the value of 2**30 def test_make_assert_true_2(): assert 1073741825 > 2**30, "Fill in value greater than 2**30" def test_make_assert_true_3(): s1 = "Hello, World" s2 = "Hello, World" assert s1 == s2 three_things_i_learnt = """ -usage of Assert statement -checking Strings equality and other logical operations -In python functions don't have {BRACES} to indicate blocks of code """
33.238095
126
0.74212
219
1,396
4.561644
0.479452
0.07007
0.039039
0.051051
0.111111
0.048048
0.048048
0
0
0
0
0.028194
0.186963
1,396
41
127
34.04878
0.851982
0.180516
0
0
0
0.074074
0.608084
0
0
0
0
0
0.555556
1
0.222222
false
0
0.037037
0
0.259259
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
1
0
1
0
0
0
0
0
0
0
3
461b11d07620b154151375da20dff071d562d484
9,027
py
Python
tests/test_gaussian.py
function2-llx/MONAI
4cddaa830b61b88ec78e089bb5f21e05bb1a78f4
[ "Apache-2.0" ]
3
2020-06-22T20:59:14.000Z
2021-04-09T21:24:45.000Z
tests/test_gaussian.py
Borda/MONAI
e0db5a564225a7cb62e7a23df97267019006302f
[ "Apache-2.0" ]
null
null
null
tests/test_gaussian.py
Borda/MONAI
e0db5a564225a7cb62e7a23df97267019006302f
[ "Apache-2.0" ]
1
2020-05-27T12:53:58.000Z
2020-05-27T12:53:58.000Z
# Copyright (c) MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import numpy as np import torch from parameterized import parameterized from monai.networks.layers.convutils import gaussian_1d TEST_CASES_NORM_F = [ [ 0.5, [ [ 0.0000000e00, 0.0000000e00, 3.5762787e-07, 2.0313263e-04, 1.6743928e-02, 2.2280261e-01, 5.2049994e-01, 2.2280261e-01, 1.6743928e-02, 2.0313263e-04, 3.5762787e-07, 0.0000000e00, 0.0000000e00, ], [ 1.3086457e-16, 7.8354033e-12, 6.3491058e-08, 6.9626461e-05, 1.0333488e-02, 2.0755373e-01, 5.6418961e-01, 2.0755373e-01, 1.0333488e-02, 6.9626461e-05, 6.3491058e-08, 7.8354033e-12, 1.3086457e-16, ], [ 2.0750829e-07, 4.9876030e-06, 9.9959565e-05, 1.6043411e-03, 1.9352052e-02, 1.5642078e-01, 6.4503527e-01, 1.5642078e-01, 1.9352052e-02, 1.6043411e-03, 9.9959565e-05, 4.9876030e-06, 2.0750829e-07, ], ], ], [ 1.0, [ [ 2.9802322e-08, 3.3676624e-06, 2.2923946e-04, 5.9770346e-03, 6.0597539e-02, 2.4173033e-01, 3.8292491e-01, 2.4173033e-01, 6.0597539e-02, 5.9770346e-03, 2.2923946e-04, 3.3676624e-06, 2.9802322e-08, ], [ 6.0758829e-09, 1.4867196e-06, 1.3383022e-04, 4.4318484e-03, 5.3990968e-02, 2.4197073e-01, 3.9894229e-01, 2.4197073e-01, 5.3990968e-02, 4.4318484e-03, 1.3383022e-04, 1.4867196e-06, 6.0758829e-09, ], [ 8.2731149e-06, 9.9865720e-05, 1.0069301e-03, 8.1553087e-03, 4.9938772e-02, 2.0791042e-01, 4.6575961e-01, 2.0791042e-01, 4.9938772e-02, 8.1553087e-03, 1.0069301e-03, 9.9865720e-05, 8.2731149e-06, ], ], ], [ 2.0, [ [ 4.81605530e-05, 6.81042671e-04, 5.93280792e-03, 3.18857729e-02, 1.05872214e-01, 2.17414647e-01, 2.76326418e-01, 2.17414647e-01, 1.05872214e-01, 3.18857729e-02, 5.93280792e-03, 6.81042671e-04, 4.81605530e-05, ], [ 3.48132307e-05, 5.44570561e-04, 5.16674388e-03, 2.97325663e-02, 1.03776865e-01, 2.19695643e-01, 2.82094806e-01, 2.19695643e-01, 1.03776865e-01, 2.97325663e-02, 5.16674388e-03, 5.44570561e-04, 3.48132307e-05, ], [ 2.1655980e-04, 1.3297606e-03, 6.8653636e-03, 2.8791221e-02, 9.3239017e-02, 2.1526930e-01, 3.0850834e-01, 2.1526930e-01, 9.3239017e-02, 2.8791221e-02, 6.8653636e-03, 1.3297606e-03, 2.1655980e-04, ], ], ], [ 4.0, [ [ 0.00240272, 0.00924471, 0.02783468, 0.06559062, 0.12097758, 0.17466632, 0.19741265, 0.17466632, 0.12097758, 0.06559062, 0.02783468, 0.00924471, 0.00240272, ], [ 0.00221592, 0.00876415, 0.02699548, 0.0647588, 0.12098537, 0.17603266, 0.19947115, 0.17603266, 0.12098537, 0.0647588, 0.02699548, 0.00876415, 0.00221592, ], [ 0.002829, 0.009244, 0.02594, 0.061124, 0.117627, 0.178751, 0.207002, 0.178751, 0.117627, 0.061124, 0.02594, 0.009244, 0.002829, ], ], ], ] class TestGaussian1d(unittest.TestCase): def test_gaussian(self): np.testing.assert_allclose( gaussian_1d(0.5, 8), torch.tensor( [ 0.0000e00, 2.9802e-07, 1.3496e-03, 1.5731e-01, 6.8269e-01, 1.5731e-01, 1.3496e-03, 2.9802e-07, 0.0000e00, ] ), rtol=1e-4, ) np.testing.assert_allclose(gaussian_1d(1, 1), torch.tensor([0.24173, 0.382925, 0.24173]), rtol=1e-4) np.testing.assert_allclose(gaussian_1d(1, 1, normalize=True), torch.tensor([0.2790, 0.4420, 0.2790]), rtol=1e-4) def test_scalespace_gaussian(self): np.testing.assert_allclose( gaussian_1d(0.5, 8, "scalespace"), torch.tensor( [ 7.9472e-06, 2.5451e-04, 6.1161e-03, 9.8113e-02, 7.9102e-01, 9.8113e-02, 6.1161e-03, 2.5451e-04, 7.9472e-06, ] ), rtol=1e-4, ) np.testing.assert_allclose( gaussian_1d(1, 1, "scalespace"), torch.tensor([0.20791, 0.46576, 0.20791]), rtol=1e-3 ) np.testing.assert_allclose( gaussian_1d(1, 1, "scalespace", normalize=True), torch.tensor([0.2358, 0.5283, 0.2358]), rtol=1e-3 ) np.testing.assert_allclose( gaussian_1d(5, 1, "scalespace"), torch.tensor( [ 0.048225, 0.057891, 0.06675, 0.073911, 0.078576, 0.080197, 0.078576, 0.073911, 0.06675, 0.057891, 0.048225, ] ), rtol=1e-3, ) @parameterized.expand(TEST_CASES_NORM_F) def test_norm_false(self, variance, expected): extent = 6 atol = 1e-4 sigma = np.sqrt(variance) k_erf = gaussian_1d(sigma, truncated=extent / sigma, approx="erf", normalize=False).numpy() k_sampled = gaussian_1d(sigma, truncated=extent / sigma, approx="sampled").numpy() k_scalespace = gaussian_1d(sigma, truncated=extent / sigma, approx="scalespace").numpy() np.testing.assert_allclose(k_erf, expected[0], atol=atol) np.testing.assert_allclose(k_sampled, expected[1], atol=atol) np.testing.assert_allclose(k_scalespace, expected[2], atol=atol) def test_wrong_sigma(self): with self.assertRaises(ValueError): gaussian_1d(1, -10) with self.assertRaises(NotImplementedError): gaussian_1d(1, 10, "wrong_arg") if __name__ == "__main__": unittest.main()
28.657143
120
0.406115
874
9,027
4.136156
0.275744
0.035961
0.041494
0.063624
0.171508
0.141355
0.141355
0.089627
0.089627
0.061411
0
0.407163
0.495846
9,027
314
121
28.748408
0.387168
0.06115
0
0.702422
0
0
0.009097
0
0
0
0
0
0.041522
1
0.013841
false
0
0.017301
0
0.034602
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
461b4de40577a464de3ce0919870835713166688
235
py
Python
backend/studiovisit/serializers.py
visitinc/studiovisit
00845c3dede85624f102fbfbc8d90d253616938f
[ "Apache-2.0" ]
null
null
null
backend/studiovisit/serializers.py
visitinc/studiovisit
00845c3dede85624f102fbfbc8d90d253616938f
[ "Apache-2.0" ]
6
2020-02-12T00:17:17.000Z
2022-01-22T04:54:44.000Z
backend/studiovisit/serializers.py
visitinc/studiovisit
00845c3dede85624f102fbfbc8d90d253616938f
[ "Apache-2.0" ]
1
2019-06-07T20:30:32.000Z
2019-06-07T20:30:32.000Z
from .models import Practice from rest_framework import serializers from django.conf import settings class PracticeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Practice fields = ('name')
26.111111
65
0.761702
24
235
7.416667
0.708333
0
0
0
0
0
0
0
0
0
0
0
0.182979
235
8
66
29.375
0.927083
0
0
0
0
0
0.017021
0
0
0
0
0
0
1
0
false
0
0.428571
0
0.714286
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
1caa0b4643600b9e56fc2a251c3aecb326ef149b
2,376
py
Python
tests/test_shaderlab_parser.py
andburn/chasm
ed0e2e4c27f848de2dec8707c3573d0c4301e7a9
[ "MIT" ]
1
2020-05-01T14:03:52.000Z
2020-05-01T14:03:52.000Z
tests/test_shaderlab_parser.py
andburn/chasm
ed0e2e4c27f848de2dec8707c3573d0c4301e7a9
[ "MIT" ]
null
null
null
tests/test_shaderlab_parser.py
andburn/chasm
ed0e2e4c27f848de2dec8707c3573d0c4301e7a9
[ "MIT" ]
null
null
null
import pytest import shaderlab from helper import * @pytest.fixture def basic_shader(): data = read_text_data("basic.shader") return shaderlab.parse(data) @pytest.fixture def uber_shader(): data = read_text_data("uber.shader") return shaderlab.parse(data) @pytest.fixture def stripped_shader(): data = read_text_data("stripped.shader") return shaderlab.parse(data) def test_basic_shader_name(basic_shader): assert basic_shader.name == "Basic" def test_basic_shader_structure(basic_shader): assert len(basic_shader.subshaders) == 1 assert len(basic_shader.subshaders[0].passes) == 1 assert len(basic_shader.subshaders[0].passes[0].programs) == 2 def test_basic_shader_vp(basic_shader): vp = basic_shader.vertex_programs assert len(vp) == 1 assert vp[0].format == shaderlab.ProgramFormat.D3D9 def test_basic_shader_fp(basic_shader): fp = basic_shader.fragment_programs assert len(fp) == 1 assert fp[0].format == shaderlab.ProgramFormat.D3D9 def test_basic_shader_properties(basic_shader): assert len(basic_shader.properties) == 2 first = basic_shader.properties[0] assert first.name == "_MainTex" assert first.description == "Main Texture" assert first.type == "2D" assert first.value == "white" def test_basic_shader_fallback(basic_shader): assert basic_shader.fallback.value == "Diffuse" def test_uber_shader_name(uber_shader): assert uber_shader.name == "Uber" def test_uber_shader_structure(uber_shader): assert len(uber_shader.subshaders) == 1 assert len(uber_shader.subshaders[0].passes) == 1 assert len(uber_shader.subshaders[0].passes[0].programs) == 2 def test_uber_shader_vp(uber_shader): vp = uber_shader.vertex_programs assert len(vp) == 2 assert vp[1].format == shaderlab.ProgramFormat.D3D9 assert set(["LYR4_COMBINE"]) == set(vp[1].keywords) def test_uber_shader_fp(uber_shader): fp = uber_shader.fragment_programs assert len(fp) == 2 assert fp[1].format == shaderlab.ProgramFormat.D3D9 assert set(["LYR4", "BLENDALPHA_L3"]) == set(fp[1].keywords) def test_uber_shader_properties(uber_shader): assert len(uber_shader.properties) == 4 first = uber_shader.properties[0] assert first.name == "_MainTex" assert first.description == "Portrait (RGB)" assert first.type == "2D" assert first.value == "black" def test_uber_shader_fallback(uber_shader): assert uber_shader.fallback.value == "Diffuse"
25.276596
63
0.764731
343
2,376
5.055394
0.163265
0.145905
0.041522
0.062284
0.737601
0.55248
0.379469
0.341407
0.175317
0.070358
0
0.01851
0.113215
2,376
93
64
25.548387
0.804461
0
0
0.15873
0
0
0.061448
0
0
0
0
0
0.47619
1
0.238095
false
0.063492
0.047619
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
1
0
1
0
0
0
0
0
3
1cbe3352183da3bfd942079b06cc22509c1ab5f2
215
py
Python
events/urls.py
ricksaha2000/StayConnected
f5632cca785d8c4679a2edb8ab33d1321603c658
[ "MIT" ]
null
null
null
events/urls.py
ricksaha2000/StayConnected
f5632cca785d8c4679a2edb8ab33d1321603c658
[ "MIT" ]
5
2021-03-19T11:20:25.000Z
2022-02-10T10:32:50.000Z
events/urls.py
ricksaha2000/StayConnected
f5632cca785d8c4679a2edb8ab33d1321603c658
[ "MIT" ]
1
2020-06-07T11:08:04.000Z
2020-06-07T11:08:04.000Z
from django.conf.urls import url from .views import events_view, event_detail_view urlpatterns = [ url(r'^$', events_view, name='list'), url(r'^(?P<event_id>[\w-]+)/$', event_detail_view, name='detail'), ]
26.875
70
0.674419
32
215
4.3125
0.5625
0.144928
0.217391
0
0
0
0
0
0
0
0
0
0.130233
215
7
71
30.714286
0.737968
0
0
0
0
0
0.162791
0.106977
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
1cc27ac9b31d107d07f2977431a054ee4d0f5ef6
773
py
Python
pipeline/old/genome_digester.py
EndyLab/FreeGenes
1ddfeeebd8186cd2906b9e991378aa7b17ed7146
[ "MIT" ]
1
2018-10-04T16:50:42.000Z
2018-10-04T16:50:42.000Z
pipeline/old/genome_digester.py
EndyLab/FreeGenes
1ddfeeebd8186cd2906b9e991378aa7b17ed7146
[ "MIT" ]
null
null
null
pipeline/old/genome_digester.py
EndyLab/FreeGenes
1ddfeeebd8186cd2906b9e991378aa7b17ed7146
[ "MIT" ]
null
null
null
from Bio import SeqIO import os import glob import datetime import sys import freegenes_fixer import io from config import * from Bio.SeqFeature import SeqFeature, FeatureLocation prefix_genbank = """LOCUS {} {} bp ds-DNA linear BCT {} DEFINITION {} ACCESSION . VERSION . KEYWORDS . SOURCE synthetic DNA sequence ORGANISM {} AUTHORS {} TITLE Direct Submission JOURNAL FreeGenes object {} FEATURES Location/Qualifiers source {} /organism="{}" /mol_type="genomic DNA" CDS {}""" # Locus_name is just the ID # raw number of base pairs #04-APR-2018 #1..753 csv_data = "ecoli_tab.csv" for index, row in csv_data.iterrows():
18.853659
83
0.606727
88
773
5.25
0.761364
0.030303
0
0
0
0
0
0
0
0
0
0.018904
0.315653
773
40
84
19.325
0.854442
0.086675
0
0
0
0
0.614286
0
0
0
0
0
0
0
null
null
0
0.346154
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
3
1cce3139ddd6a24a7af9146590c6efa3e479f8d0
868
py
Python
ggpy/cruft/autocode/SamplePythonGamerStub.py
hobson/ggpy
4e6e6e876c3a4294cd711647051da2d9c1836b60
[ "MIT" ]
1
2015-01-26T19:07:45.000Z
2015-01-26T19:07:45.000Z
ggpy/cruft/autocode/SamplePythonGamerStub.py
hobson/ggpy
4e6e6e876c3a4294cd711647051da2d9c1836b60
[ "MIT" ]
null
null
null
ggpy/cruft/autocode/SamplePythonGamerStub.py
hobson/ggpy
4e6e6e876c3a4294cd711647051da2d9c1836b60
[ "MIT" ]
null
null
null
#!/usr/bin/env python """ generated source for module SamplePythonGamerStub """ # package: org.ggp.base.player.gamer.python.stubs import org.ggp.base.player.gamer.python.PythonGamer # # * SamplePythonGamerStub is a stub pointing to a version of @RandomGamer that # * has been implemented in Python. This stub needs to exist so that the Python # * code can interoperate with the rest of the Java framework (and applications # * like Kiosk and PlayerPanel as a result). # * # * @author Sam # class SamplePythonGamerStub(PythonGamer): """ generated source for class SamplePythonGamerStub """ def getPythonGamerModule(self): """ generated source for method getPythonGamerModule """ return "sample_gamer" def getPythonGamerName(self): """ generated source for method getPythonGamerName """ return "SamplePythonGamer"
36.166667
80
0.726959
100
868
6.3
0.61
0.095238
0.114286
0.050794
0.174603
0.085714
0
0
0
0
0
0
0.185484
868
23
81
37.73913
0.891089
0.652074
0
0
1
0
0.109434
0
0
0
0
0
0
1
0.333333
false
0
0.166667
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
1cd5a995b6c7bb01574decd4379b476e0994f2a2
414
py
Python
Day46/Remove_Duplicates_from_string.py
tushartrip1010/100_days_code_py
ee74b429e98cdd8bdf8661cf987da67c9fee5a3e
[ "Apache-2.0" ]
null
null
null
Day46/Remove_Duplicates_from_string.py
tushartrip1010/100_days_code_py
ee74b429e98cdd8bdf8661cf987da67c9fee5a3e
[ "Apache-2.0" ]
null
null
null
Day46/Remove_Duplicates_from_string.py
tushartrip1010/100_days_code_py
ee74b429e98cdd8bdf8661cf987da67c9fee5a3e
[ "Apache-2.0" ]
null
null
null
import re def Remove_Duplicates(Test_string): Pattern = r"\b(\w+)(?:\W\1\b)+" return re.sub(Pattern, r"\1", Test_string, flags=re.IGNORECASE) Test_string1 = "Good bye bye world world" Test_string2 = "Ram went went to to his home" Test_string3 = "Hello hello world world" print(Remove_Duplicates(Test_string1)) print(Remove_Duplicates(Test_string2)) print(Remove_Duplicates(Test_string3))
27.6
68
0.724638
62
414
4.645161
0.467742
0.222222
0.277778
0.260417
0
0
0
0
0
0
0
0.022792
0.152174
414
14
69
29.571429
0.797721
0
0
0
0
0
0.2375
0
0
0
0
0
0
1
0.1
false
0
0.1
0
0.3
0.3
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
1ce9410f9622a88a6c295daec35f8ee416628331
194
py
Python
rafaels_pizza/blog/cms_apps.py
zerazobz/DjangoCmsDemo
7bb6866fd1d555e4aaa9ba27613460b595c1051f
[ "Apache-2.0" ]
null
null
null
rafaels_pizza/blog/cms_apps.py
zerazobz/DjangoCmsDemo
7bb6866fd1d555e4aaa9ba27613460b595c1051f
[ "Apache-2.0" ]
null
null
null
rafaels_pizza/blog/cms_apps.py
zerazobz/DjangoCmsDemo
7bb6866fd1d555e4aaa9ba27613460b595c1051f
[ "Apache-2.0" ]
null
null
null
from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool class BlogApp(CMSApp): name = "Blog" urls = ["blog.urls"] app_name = "blog" apphook_pool.register(BlogApp)
21.555556
41
0.726804
28
194
4.857143
0.5
0.242647
0
0
0
0
0
0
0
0
0
0
0.170103
194
9
42
21.555556
0.844721
0
0
0
0
0
0.087179
0
0
0
0
0
0
1
0
false
0
0.285714
0
0.857143
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
1ceae06a4ffe526eaef81e56bff296f759fd36ad
50
py
Python
example/__init__.py
divipayhq/drf_model_pusher
37f2d7c61839f641675da8db2bd4ec4932d4bd47
[ "MIT" ]
5
2018-07-23T00:21:29.000Z
2020-01-16T15:42:10.000Z
example/__init__.py
divipayhq/drf_model_pusher
37f2d7c61839f641675da8db2bd4ec4932d4bd47
[ "MIT" ]
39
2018-07-25T03:42:25.000Z
2021-12-20T03:51:13.000Z
example/__init__.py
divipayhq/drf_model_pusher
37f2d7c61839f641675da8db2bd4ec4932d4bd47
[ "MIT" ]
3
2018-10-02T16:29:34.000Z
2022-02-22T03:04:50.000Z
default_app_config = "example.apps.ExampleConfig"
25
49
0.84
6
50
6.666667
1
0
0
0
0
0
0
0
0
0
0
0
0.06
50
1
50
50
0.851064
0
0
0
0
0
0.52
0.52
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
1cf3a037a095980bdd44a7982f75b7501a7beac0
1,921
py
Python
glrm/loss.py
dataronio/GLRM
58bdb64f1aafeb06eb0a0fbf74e49138f0a19da6
[ "MIT" ]
67
2015-03-26T15:52:15.000Z
2018-09-06T17:41:25.000Z
glrm/loss.py
chrinide/GLRM
58bdb64f1aafeb06eb0a0fbf74e49138f0a19da6
[ "MIT" ]
5
2016-02-17T15:29:48.000Z
2018-08-16T20:01:00.000Z
glrm/loss.py
chrinide/GLRM
58bdb64f1aafeb06eb0a0fbf74e49138f0a19da6
[ "MIT" ]
42
2015-03-10T17:02:11.000Z
2018-10-24T19:59:38.000Z
import cvxpy as cp from numpy import ones, maximum, minimum, sign, floor, ceil """ Abstract loss class and canonical loss functions. """ # Abstract Loss class class Loss(object): def __init__(self, A): return def loss(self, A, U): raise NotImplementedError("Override me!") def encode(self, A): return A # default def decode(self, A): return A # default def __str__(self): return "GLRM Loss: override me!" def __call__(self, A, U): return self.loss(A, U) # Canonical loss functions class QuadraticLoss(Loss): def loss(self, A, U): return cp.norm(cp.Constant(A) - U, "fro")/2.0 def __str__(self): return "quadratic loss" class HuberLoss(Loss): a = 1.0 # XXX does the value of 'a' propagate if we update it? def loss(self, A, U): return cp.sum_entries(cp.huber(cp.Constant(A) - U, self.a)) def __str__(self): return "huber loss" # class FractionalLoss(Loss): # PRECISION = 1e-10 # def loss(self, A, U): # B = cp.Constant(A) # U = cp.max_elemwise(U, self.PRECISION) # to avoid dividing by zero # return cp.max_elemwise(cp.mul_elemwise(cp.inv_pos(cp.pos(U)), B-U), \ # return maximum((A - U)/U, (U - A)/A) # class HingeLoss(Loss): def loss(self, A, U): return cp.sum_entries(cp.pos(ones(A.shape)-cp.mul_elemwise(cp.Constant(A), U))) def decode(self, A): return sign(A) # return back to Boolean def __str__(self): return "hinge loss" class OrdinalLoss(Loss): def __init__(self, A): self.Amax, self.Amin = A.max(), A.min() def loss(self, A, U): return cp.sum_entries(sum(cp.mul_elemwise(1*(b >= A),\ cp.pos(U-b*ones(A.shape))) + cp.mul_elemwise(1*(b < A), \ cp.pos(-U + (b+1)*ones(A.shape))) for b in range(int(self.Amin), int(self.Amax)))) def decode(self, A): return maximum(minimum(A.round(), self.Amax), self.Amin) def __str__(self): return "ordinal loss"
38.42
105
0.637168
311
1,921
3.800643
0.279743
0.059222
0.035533
0.060914
0.271574
0.21066
0.145516
0.145516
0.120981
0.094755
0
0.006553
0.205622
1,921
49
106
39.204082
0.768021
0.227486
0
0
0
0
0.059532
0
0
0
0
0
0
1
0.586207
false
0
0.068966
0.517241
0.896552
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
e805b247ce6df01e020753cc0038fe8320ef4535
327
py
Python
pigpio/setup.py
neildavis/drv8835-motor-driver-pigpio-python
551f4bf150cb731acce56d8ec16a25a2e4be26fa
[ "MIT" ]
1
2021-02-26T14:38:40.000Z
2021-02-26T14:38:40.000Z
pigpio/setup.py
neildavis/drv8835-motor-driver-pigpio-python
551f4bf150cb731acce56d8ec16a25a2e4be26fa
[ "MIT" ]
null
null
null
pigpio/setup.py
neildavis/drv8835-motor-driver-pigpio-python
551f4bf150cb731acce56d8ec16a25a2e4be26fa
[ "MIT" ]
1
2021-08-21T14:56:41.000Z
2021-08-21T14:56:41.000Z
from distutils.core import setup setup(name='drv8835_driver_pigpio', version='1.1.2', description=('Library for the Pololu DRV8835 Dual Motor ' 'Driver Kit for Raspberry Pi using pigpio daemon'), url='http://www.pololu.com/product/2753', py_modules=['drv8835_driver_pigpio'], )
36.333333
70
0.657492
42
327
5
0.761905
0.12381
0.180952
0
0
0
0
0
0
0
0
0.075099
0.2263
327
8
71
40.875
0.754941
0
0
0
0
0
0.519878
0.12844
0
0
0
0
0
1
0
true
0
0.125
0
0.125
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
3
e80ff431e9713575125d2ced9c8999d93ee522fd
1,862
py
Python
spacy/tests/regression/test_issue1769.py
algteam/spacy_zh_model
0b0cba1a3964aa426e5f96087849c90e69e2a89d
[ "MIT" ]
5
2019-04-19T06:27:29.000Z
2019-12-02T13:30:47.000Z
spacy/tests/regression/test_issue1769.py
algteam/spacy_zh_model
0b0cba1a3964aa426e5f96087849c90e69e2a89d
[ "MIT" ]
null
null
null
spacy/tests/regression/test_issue1769.py
algteam/spacy_zh_model
0b0cba1a3964aa426e5f96087849c90e69e2a89d
[ "MIT" ]
2
2019-04-19T06:27:18.000Z
2019-10-04T12:39:15.000Z
# coding: utf-8 from __future__ import unicode_literals from ...util import get_lang_class from ...attrs import LIKE_NUM import pytest @pytest.mark.parametrize('word', ['eleven']) def test_en_lex_attrs(word): lang = get_lang_class('en') like_num = lang.Defaults.lex_attr_getters[LIKE_NUM] assert like_num(word) == like_num(word.upper()) @pytest.mark.slow @pytest.mark.parametrize('word', ['elleve', 'første']) def test_da_lex_attrs(word): lang = get_lang_class('da') like_num = lang.Defaults.lex_attr_getters[LIKE_NUM] assert like_num(word) == like_num(word.upper()) @pytest.mark.slow @pytest.mark.parametrize('word', ['onze', 'onzième']) def test_fr_lex_attrs(word): lang = get_lang_class('fr') like_num = lang.Defaults.lex_attr_getters[LIKE_NUM] assert like_num(word) == like_num(word.upper()) @pytest.mark.slow @pytest.mark.parametrize('word', ['sebelas']) def test_id_lex_attrs(word): lang = get_lang_class('id') like_num = lang.Defaults.lex_attr_getters[LIKE_NUM] assert like_num(word) == like_num(word.upper()) @pytest.mark.slow @pytest.mark.parametrize('word', ['elf', 'elfde']) def test_nl_lex_attrs(word): lang = get_lang_class('nl') like_num = lang.Defaults.lex_attr_getters[LIKE_NUM] assert like_num(word) == like_num(word.upper()) @pytest.mark.slow @pytest.mark.parametrize('word', ['onze', 'quadragésimo']) def test_pt_lex_attrs(word): lang = get_lang_class('pt') like_num = lang.Defaults.lex_attr_getters[LIKE_NUM] assert like_num(word) == like_num(word.upper()) @pytest.mark.slow @pytest.mark.parametrize('word', ['одиннадцать']) def test_ru_lex_attrs(word): lang = get_lang_class('ru') like_num = lang.Defaults.lex_attr_getters[LIKE_NUM] assert like_num(word) == like_num(word.upper())
30.032258
59
0.698174
274
1,862
4.434307
0.164234
0.167078
0.126749
0.144033
0.78107
0.78107
0.78107
0.619753
0.619753
0.619753
0
0.000634
0.153061
1,862
61
60
30.52459
0.769816
0.006982
0
0.444444
0
0
0.06327
0
0
0
0
0
0.155556
1
0.155556
false
0
0.088889
0
0.244444
0
0
0
0
null
0
0
0
0
1
1
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
e820ee1b9fa9bb0e5be23971ed6e05526caa5a70
464
py
Python
examples/shapes_from_glsl/defaults.py
szabolcsdombi/zengl
2c9c26784285f2f049fb5d6fc9da0ad65d32d52f
[ "MIT" ]
116
2021-10-31T17:24:18.000Z
2022-02-01T05:47:18.000Z
examples/shapes_from_glsl/defaults.py
szabolcsdombi/zengl
2c9c26784285f2f049fb5d6fc9da0ad65d32d52f
[ "MIT" ]
9
2021-11-12T19:21:33.000Z
2022-01-20T09:48:31.000Z
examples/shapes_from_glsl/defaults.py
szabolcsdombi/zengl
2c9c26784285f2f049fb5d6fc9da0ad65d32d52f
[ "MIT" ]
3
2021-11-12T18:55:05.000Z
2022-01-19T13:58:26.000Z
defaults = ''' const vec4 light = vec4(4.0, 3.0, 10.0, 0.0); const vec4 eye = vec4(4.0, 3.0, 2.0, 0.0); const mat4 mvp = mat4( -0.8147971034049988, -0.7172931432723999, -0.7429299354553223, -0.7427813410758972, 1.0863960981369019, -0.5379698276519775, -0.5571974515914917, -0.5570859909057617, 0.0, 2.2415409088134766, -0.37146496772766113, -0.3713906705379486, 0.0, 0.0, 5.186222076416016, 5.385164737701416 ); '''
42.181818
91
0.648707
61
464
4.934426
0.442623
0.053156
0.039867
0.046512
0.053156
0
0
0
0
0
0
0.665775
0.193966
464
10
92
46.4
0.139037
0
0
0
0
0.2
0.961207
0.045259
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
e8210a650b709d429179b1c916d95d13741ca687
93,930
py
Python
tests/test_task.py
BlueBrain/data-validation-framework
4687912b1c9b5412c97a311205c81f6344d12566
[ "Apache-2.0" ]
3
2022-01-12T13:29:15.000Z
2022-01-18T16:06:48.000Z
tests/test_task.py
BlueBrain/data-validation-framework
4687912b1c9b5412c97a311205c81f6344d12566
[ "Apache-2.0" ]
8
2021-12-16T18:15:15.000Z
2022-03-17T22:33:37.000Z
tests/test_task.py
BlueBrain/data-validation-framework
4687912b1c9b5412c97a311205c81f6344d12566
[ "Apache-2.0" ]
null
null
null
"""Test the data_validation_framework.task module.""" # pylint: disable=missing-class-docstring # pylint: disable=missing-function-docstring # pylint: disable=no-self-use # pylint: disable=redefined-outer-name # pylint: disable=too-many-lines # pylint: disable=unused-argument import json import logging import re import time from pathlib import Path from shutil import which import luigi import luigi_tools import numpy as np import pandas as pd import pause import pytest from diff_pdf_visually import pdfdiff from luigi_tools.parameter import OptionalStrParameter from data_validation_framework import report from data_validation_framework import result from data_validation_framework import target from data_validation_framework import task from . import check_files_exist SKIP_IF_NO_LATEXMK = not which("latexmk") REASON_NO_LATEXMK = "The command latexmk is not available." @pytest.fixture def dataset_df_path(tmpdir): dataset_df_path = tmpdir / "dataset.csv" base_dataset_df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) base_dataset_df.to_csv(dataset_df_path) return str(dataset_df_path) @pytest.mark.filterwarnings("ignore::DeprecationWarning") class TestTagResultOutputMixin: """Test the data_validation_framework.task.TagResultOutputMixin class.""" def test_default(self, tmpdir): """Test the simple case.""" class TestTask(task.TagResultOutputMixin, luigi.Task): with_conflict = luigi.BoolParameter(default=False) def run(self): if not self.tag_output: assert self.output()["without_prefix"].path == str(tmpdir / "file.test") assert self.output()["with_prefix"].path == str(tmpdir / "out" / "file.test") elif not self.with_conflict: assert re.match( f"{tmpdir}/out" + r"_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", self.output()["with_prefix"].path, ) else: assert re.match( f"{tmpdir}/out" + r"_\d{8}-\d{2}h\d{2}m\d{2}s_\d+/file.test", self.output()["with_prefix"].path, ) def output(self): return { "without_prefix": target.TaggedOutputLocalTarget("file.test"), "with_prefix": target.TaggedOutputLocalTarget( "file.test", prefix=self.result_path ), } root = tmpdir / "out" assert luigi.build([TestTask(result_path=str(root))], local_scheduler=True) # Test tag name conflicts pause.until(int(time.time()) + 1.01) t1 = TestTask(result_path=str(root), tag_output=True, with_conflict=False) assert luigi.build([t1], local_scheduler=True) t2 = TestTask(result_path=str(root), tag_output=True, with_conflict=True) assert luigi.build([t2], local_scheduler=True) def test_rerun_interaction_left(self, tmpdir): """Test the data_validation_framework.task.TagResultOutputMixin class.""" # pylint: disable=protected-access # pylint: disable=too-many-statements executed = [] class TestTaskLeft(luigi_tools.task.RerunMixin, task.TagResultOutputMixin, luigi.Task): with_conflict = luigi.BoolParameter(default=False) seed = luigi.IntParameter(default=0, significant=False) root = None def run(self): executed.append( ( self.result_path, self.output().path, self.with_conflict, self.rerun, self.seed, ) ) if not self.tag_output: assert self.output().path == str(self.root / "file.test") elif not self.with_conflict: assert re.match( str(self.root) + r"_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", self.output().path ) else: assert re.match( str(self.root) + r"_\d{8}-\d{2}h\d{2}m\d{2}s_\d+/file.test", self.output().path, ) with self.output().pathlib_path.open("w", encoding="utf-8") as f: f.writelines( [ f"{self.root}\n", f"{self.result_path}\n", f"{self.seed}\n", f"{self.tag_output}\n", f"{self.with_conflict}\n", f"{self.rerun}", ] ) def output(self): return target.TaggedOutputLocalTarget("file.test", prefix=self.result_path) expected_files = [] # ########################################################################### # # #################### TEST WITH RERUN MIXIN ON THE LEFT #################### # # ########################################################################### # # Testing with no tag to create base directory TestTaskLeft.root = tmpdir / "out_left" target.TaggedOutputLocalTarget._already_changed = False t0 = TestTaskLeft(result_path=TestTaskLeft.root, tag_output=False, with_conflict=False) assert luigi.build([t0], local_scheduler=True) expected_files.extend( [ "out_left", "out_left/file.test", ] ) check_files_exist(tmpdir, expected_files) # Testing with tag, no conflict and rerun TestTaskLeft.root = tmpdir / "out_left" target.TaggedOutputLocalTarget._already_changed = False # Wait for the beginning of the next second pause.until(int(time.time()) + 1.01) # There is no conflict here because the tasks are defined before any target is created assert luigi.build( [ TestTaskLeft( result_path=TestTaskLeft.root, seed=0, tag_output=True, with_conflict=False ), TestTaskLeft( result_path=TestTaskLeft.root, seed=1, tag_output=True, with_conflict=False, rerun=True, ), ], local_scheduler=True, ) assert len(executed) == 2 executed.clear() expected_files.extend( [ r"out_left_\d{8}-\d{2}h\d{2}m\d{2}s", r"out_left_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", ] ) check_files_exist(tmpdir, expected_files) with Path( [ i for i in sorted(Path(tmpdir).rglob("*")) if re.match( r"out_left_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", str(i.relative_to(tmpdir)) ) ][0] ).open("r", encoding="utf-8") as f: data = f.read().split("\n") assert data[0] == str(tmpdir / "out_left") assert re.match(str(tmpdir / r"out_left_\d{8}-\d{2}h\d{2}m\d{2}s"), data[1]) assert data[2:] == ["1", "True", "False", "True"] # Testing with tag, no conflict and rerun TestTaskLeft.root = tmpdir / "out_left" target.TaggedOutputLocalTarget._already_changed = False # Wait for the beginning of the next second pause.until(int(time.time()) + 1.01) # There is conflict here because the last task is defined after the Rerun mixin which # created a new directory assert luigi.build( [ TestTaskLeft( result_path=TestTaskLeft.root, seed=0, tag_output=True, with_conflict=True ), TestTaskLeft( result_path=TestTaskLeft.root, seed=1, tag_output=True, with_conflict=True, rerun=True, ), TestTaskLeft( result_path=TestTaskLeft.root, seed=2, tag_output=True, with_conflict=True ), ], local_scheduler=True, ) assert len(executed) == 1 # Note that only the last task is executed here executed.clear() expected_files.extend( [ r"out_left_\d{8}-\d{2}h\d{2}m\d{2}s", r"out_left_\d{8}-\d{2}h\d{2}m\d{2}s_\d+", r"out_left_\d{8}-\d{2}h\d{2}m\d{2}s_\d+/file.test", ] ) check_files_exist( tmpdir, expected_files, ) with Path( [ i for i in sorted(Path(tmpdir).rglob("*")) if re.match( r"out_left_\d{8}-\d{2}h\d{2}m\d{2}s_\d+/file.test", str(i.relative_to(tmpdir)) ) ][0] ).open("r", encoding="utf-8") as f: data = f.read().split("\n") assert data[0] == str(tmpdir / "out_left") assert re.match(str(tmpdir / r"out_left_\d{8}-\d{2}h\d{2}m\d{2}s_\d+"), data[1]) assert data[2:] == ["2", "True", "True", "False"] # Testing with rerun and conflict TestTaskLeft.root = tmpdir / "out_left_with_rerun" target.TaggedOutputLocalTarget._already_changed = False # Wait for the beginning of the next second pause.until(int(time.time()) + 1.01) # The t1 task has no conflict t1 = TestTaskLeft(result_path=TestTaskLeft.root, tag_output=True, with_conflict=False) assert t1.output().path.endswith("s/file.test") # Test warning is raised when TagResultOutputMixin is used with RerunMixin with pytest.warns( UserWarning, match=( "Using 'rerun' with conflicting tag output results in creating a new tag or " r"removing the untagged result directory \(depending on the inheritance order\)." ), ): t2 = TestTaskLeft( result_path=TestTaskLeft.root, tag_output=True, with_conflict=True, rerun=True ) assert t2.output().path.endswith("s_1/file.test") # Build without rerun assert luigi.build([t1], local_scheduler=True) assert len(executed) == 1 executed.clear() expected_files.extend( [ r"out_left_with_rerun_\d{8}-\d{2}h\d{2}m\d{2}s", r"out_left_with_rerun_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", r"out_left_with_rerun_\d{8}-\d{2}h\d{2}m\d{2}s_\d+", ] ) check_files_exist( tmpdir, expected_files, ) with Path( [ i for i in sorted(Path(tmpdir).rglob("*")) if re.match( r"out_left_with_rerun_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", str(i.relative_to(tmpdir)), ) ][0] ).open("r", encoding="utf-8") as f: data = f.read().split("\n") assert data[0] == str(tmpdir / "out_left_with_rerun") assert re.match(str(tmpdir / r"out_left_with_rerun_\d{8}-\d{2}h\d{2}m\d{2}s"), data[1]) assert data[2:] == ["0", "True", "False", "False"] # Build with rerun assert luigi.build([t2], local_scheduler=True) assert len(executed) == 1 executed.clear() expected_files.extend( [ r"out_left_with_rerun_\d{8}-\d{2}h\d{2}m\d{2}s_\d+/file.test", ] ) check_files_exist( tmpdir, expected_files, ) with Path( [ i for i in sorted(Path(tmpdir).rglob("*")) if re.match( r"out_left_with_rerun_\d{8}-\d{2}h\d{2}m\d{2}s_\d+/file.test", str(i.relative_to(tmpdir)), ) ][0] ).open("r", encoding="utf-8") as f: data = f.read().split("\n") assert data[0] == str(tmpdir / "out_left_with_rerun") assert re.match(str(tmpdir / r"out_left_with_rerun_\d{8}-\d{2}h\d{2}m\d{2}s_\d+"), data[1]) assert data[2:] == ["0", "True", "True", "True"] def test_rerun_interaction_right(self, tmpdir): """Test the data_validation_framework.task.TagResultOutputMixin class.""" # pylint: disable=protected-access # pylint: disable=too-many-statements executed = [] class TestTaskRight(task.TagResultOutputMixin, luigi_tools.task.RerunMixin, luigi.Task): with_conflict = luigi.BoolParameter(default=False) seed = luigi.IntParameter(default=0, significant=False) root = None def run(self): executed.append( ( self.result_path, self.output().path, self.with_conflict, self.rerun, self.seed, ) ) if not self.tag_output: assert self.output().path == str(self.root / "file.test") elif self.with_conflict and self.rerun: assert re.match( str(self.root) + r"_\d{8}-\d{2}h\d{2}m\d{2}s_\d+/file.test", self.output().path, ) else: assert re.match( str(self.root) + r"_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", self.output().path, ) with self.output().pathlib_path.open("w", encoding="utf-8") as f: f.writelines( [ f"{self.root}\n", f"{self.result_path}\n", f"{self.seed}\n", f"{self.tag_output}\n", f"{self.with_conflict}\n", f"{self.rerun}", ] ) def output(self): return target.TaggedOutputLocalTarget("file.test", prefix=self.result_path) expected_files = [] # ########################################################################### # # #################### TEST WITH RERUN MIXIN ON THE RIGHT ################### # # ########################################################################### # # Testing with no tag to create base directory TestTaskRight.root = tmpdir / "out_right_no-tag" target.TaggedOutputLocalTarget._already_changed = False t0 = TestTaskRight(result_path=TestTaskRight.root, tag_output=False, with_conflict=False) assert luigi.build([t0], local_scheduler=True) assert len(executed) == 1 executed.clear() expected_files.extend( [ "out_right_no-tag", "out_right_no-tag/file.test", ] ) check_files_exist( tmpdir, expected_files, ) # Testing with tag, no conflict and rerun TestTaskRight.root = tmpdir / "out_right_tag_no-conflict" target.TaggedOutputLocalTarget._already_changed = False # Wait for the beginning of the next second pause.until(int(time.time()) + 1.01) # There is no actual conflict here because the tasks are defined before any target is # created but the Rerun mixin removes the targets BEFORE the tag is created and creates # an empty directory with no tag. assert luigi.build( [ TestTaskRight( result_path=TestTaskRight.root, seed=0, tag_output=True, with_conflict=False ), TestTaskRight( result_path=TestTaskRight.root, seed=1, tag_output=True, with_conflict=False, rerun=True, ), ], local_scheduler=True, ) assert len(executed) == 1 # Note that the first task is not executed here executed.clear() # expected_files.pop() # Expect to not find the target of the task without tag expected_files.extend( [ r"out_right_tag_no-conflict", r"out_right_tag_no-conflict_\d{8}-\d{2}h\d{2}m\d{2}s", r"out_right_tag_no-conflict_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", ] ) check_files_exist( tmpdir, expected_files, ) with Path( [ i for i in sorted(Path(tmpdir).rglob("*")) if re.match( r"out_right_tag_no-conflict_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", str(i.relative_to(tmpdir)), ) ][0] ).open("r", encoding="utf-8") as f: data = f.read().split("\n") assert data[0] == str(tmpdir / "out_right_tag_no-conflict") assert re.match( str(tmpdir / r"out_right_tag_no-conflict_\d{8}-\d{2}h\d{2}m\d{2}s"), data[1] ) assert data[2:] == ["1", "True", "False", "True"] # Testing with tag, no conflict and rerun TestTaskRight.root = tmpdir / "out_right_tag_with-conflict_rerun_3-tasks" target.TaggedOutputLocalTarget._already_changed = False # Wait for the beginning of the next second pause.until(int(time.time()) + 1.01) # There is conflict here because the Rerun mixin is executed BEFORE the new tag is created # (and the Rerun mixin created the parent directory of the targets) assert luigi.build( [ TestTaskRight( result_path=TestTaskRight.root, seed=0, tag_output=True, with_conflict=True ), TestTaskRight( result_path=TestTaskRight.root, seed=1, tag_output=True, with_conflict=True, rerun=True, ), TestTaskRight( result_path=TestTaskRight.root, seed=2, tag_output=True, with_conflict=True ), ], local_scheduler=True, ) assert len(executed) == 1 # Note that only the last task is executed here executed.clear() expected_files.extend( [ r"out_right_tag_with-conflict_rerun_3-tasks", r"out_right_tag_with-conflict_rerun_3-tasks_\d{8}-\d{2}h\d{2}m\d{2}s", r"out_right_tag_with-conflict_rerun_3-tasks_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", ] ) check_files_exist( tmpdir, expected_files, ) with Path( [ i for i in sorted(Path(tmpdir).rglob("*")) if re.match( r"out_right_tag_with-conflict_rerun_3-tasks_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", str(i.relative_to(tmpdir)), ) ][0] ).open("r", encoding="utf-8") as f: data = f.read().split("\n") assert data[0] == str(tmpdir / "out_right_tag_with-conflict_rerun_3-tasks") assert re.match( str(tmpdir / r"out_right_tag_with-conflict_rerun_3-tasks_\d{8}-\d{2}h\d{2}m\d{2}s"), data[1], ) # Note that this time only the task with seed == 2 is executed! assert data[2:] == ["2", "True", "True", "False"] # Testing with rerun and conflict TestTaskRight.root = tmpdir / "out_right_tag_with-conflict_with-rerun" target.TaggedOutputLocalTarget._already_changed = False # Wait for the beginning of the next second pause.until(int(time.time()) + 1.01) # The t1 task has no conflict # Note that we have to specify the prefix in the target to avoid conflict. If we do not, # the default prefix is updated when the task t2 is defined, so when t1 is built the prefix # has been changed and thus the assert fails. t1 = TestTaskRight(result_path=TestTaskRight.root, tag_output=True, with_conflict=True) assert t1.output().path.endswith("s/file.test") # Test warning is raised when TagResultOutputMixin is used with RerunMixin with pytest.warns( UserWarning, match=( "Using 'rerun' with conflicting tag output results in creating a new tag or " r"removing the untagged result directory \(depending on the inheritance order\)." ), ): t2 = TestTaskRight( result_path=TestTaskRight.root, tag_output=True, with_conflict=True, rerun=True ) assert t2.output().path.endswith("s_1/file.test") # Build without rerun assert luigi.build([t1], local_scheduler=True) assert len(executed) == 1 executed.clear() expected_files.extend( [ r"out_right_tag_with-conflict_with-rerun", r"out_right_tag_with-conflict_with-rerun_\d{8}-\d{2}h\d{2}m\d{2}s", r"out_right_tag_with-conflict_with-rerun_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", r"out_right_tag_with-conflict_with-rerun_\d{8}-\d{2}h\d{2}m\d{2}s_\d+", ] ) check_files_exist( tmpdir, expected_files, ) with Path( [ i for i in sorted(Path(tmpdir).rglob("*")) if re.match( r"out_right_tag_with-conflict_with-rerun_\d{8}-\d{2}h\d{2}m\d{2}s/file.test", str(i.relative_to(tmpdir)), ) ][0] ).open("r", encoding="utf-8") as f: data = f.read().split("\n") assert data[0] == str(tmpdir / "out_right_tag_with-conflict_with-rerun") assert re.match( str(tmpdir / r"out_right_tag_with-conflict_with-rerun_\d{8}-\d{2}h\d{2}m\d{2}s"), data[1], ) assert data[2:] == ["0", "True", "True", "False"] # Build with rerun assert luigi.build([t2], local_scheduler=True) assert len(executed) == 1 executed.clear() expected_files.extend( [ r"out_right_tag_with-conflict_with-rerun_\d{8}-\d{2}h\d{2}m\d{2}s_\d+/file.test", ] ) check_files_exist( tmpdir, expected_files, ) with Path( [ i for i in sorted(Path(tmpdir).rglob("*")) if re.match( ( "out_right_tag_with-conflict_with-rerun_" r"\d{8}-\d{2}h\d{2}m\d{2}s_\d+/file.test" ), str(i.relative_to(tmpdir)), ) ][0] ).open("r", encoding="utf-8") as f: data = f.read().split("\n") assert data[0] == str(tmpdir / "out_right_tag_with-conflict_with-rerun") assert re.match( str(tmpdir / r"out_right_tag_with-conflict_with-rerun_\d{8}-\d{2}h\d{2}m\d{2}s"), data[1], ) assert data[2:] == ["0", "True", "True", "True"] def test_propagation(self, tmpdir, dataset_df_path): """Test the propagation of result_path.""" class TestTaskA(task.SetValidationTask): """A test validation task.""" @staticmethod def validation_function(df, output_path, *args, **kwargs): (output_path / "fileA.test").touch() class TestTaskB(task.SetValidationTask): """A test validation task.""" @staticmethod def validation_function(df, output_path, *args, **kwargs): (output_path / "fileB.test").touch() class TestWorkflow(task.ValidationWorkflow): """The global validation workflow.""" with_conflict = luigi.BoolParameter(default=False) def inputs(self): return { TestTaskA: {}, TestTaskB: {}, } def kwargs(self): return { "tag_output": self.tag_output, "with_conflict": self.with_conflict, } @staticmethod def validation_function(df, output_path, *args, tag_output, with_conflict, **kwargs): res_files = sorted(Path(output_path.parent.parent).rglob("*")) if not tag_output: suffix = "" elif not with_conflict: suffix = r"_\d{8}-\d{2}h\d{2}m\d{2}s" else: suffix = r"_\d{8}-\d{2}h\d{2}m\d{2}s_\d+" expected_patterns = [ f"{tmpdir}/out" + suffix + "/TestTaskA", f"{tmpdir}/out" + suffix + "/TestTaskA/data", f"{tmpdir}/out" + suffix + "/TestTaskA/data/fileA.test", f"{tmpdir}/out" + suffix + "/TestTaskA/report.csv", f"{tmpdir}/out" + suffix + "/TestTaskB", f"{tmpdir}/out" + suffix + "/TestTaskB/data", f"{tmpdir}/out" + suffix + "/TestTaskB/data/fileB.test", f"{tmpdir}/out" + suffix + "/TestTaskB/report.csv", f"{tmpdir}/out" + suffix + "/TestWorkflow", f"{tmpdir}/out" + suffix + "/TestWorkflow/data", ] assert len(res_files) == len(expected_patterns) for path, pattern in zip(res_files, expected_patterns): assert re.match(str(pattern), str(path)) root = tmpdir / "out" workflow = TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), tag_output=False, with_conflict=False, ) assert luigi.build([workflow], local_scheduler=True) report_df = pd.read_csv(workflow.result_path / "TestWorkflow" / "report.csv") assert report_df["is_valid"].all() # Test tag name conflicts pause.until(int(time.time()) + 1.01) workflow_1 = TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), tag_output=True, with_conflict=False, ) assert re.match( r"out_\d{8}-\d{2}h\d{2}m\d{2}s/TestWorkflow/report.csv", str(workflow_1.output()["report"].pathlib_path.relative_to(tmpdir)), ) # Create the result directory of workflow_1 so that it appears to have already run for # workflow_2 workflow_1.output()["data"].pathlib_path.mkdir(parents=True, exist_ok=True) workflow_2 = TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), tag_output=True, with_conflict=True, ) assert re.match( r"out_\d{8}-\d{2}h\d{2}m\d{2}s_\d+/TestWorkflow/report.csv", str(workflow_2.output()["report"].pathlib_path.relative_to(tmpdir)), ) assert luigi.build([workflow_1, workflow_2], local_scheduler=True) report_df_1 = pd.read_csv(workflow_1.result_path / "TestWorkflow" / "report.csv") assert report_df_1["is_valid"].all() report_df_2 = pd.read_csv(workflow_2.result_path / "TestWorkflow" / "report.csv") assert report_df_2["is_valid"].all() class TestSetValidationTask: """Test the data_validation_framework.task.SetValidationTask class.""" @pytest.fixture def TestTask(self, tmpdir): class TestTask(task.SetValidationTask): @staticmethod def validation_function(df, output_path, *args, **kwargs): assert df["is_valid"].all() assert (df["ret_code"] == 0).all() assert df["comment"].isnull().all() assert df["exception"].isnull().all() assert df["a"].tolist() == [1, 2] assert df["b"].tolist() == [3, 4] df["a"] *= 10 df[["a", "b"]].to_csv(output_path / "test.csv") return TestTask def test_defaults(self, TestTask, dataset_df_path, tmpdir): # Test defaults assert luigi.build( [TestTask(dataset_df=dataset_df_path, result_path=str(tmpdir / "out_defaults"))], local_scheduler=True, ) result = pd.read_csv(tmpdir / "out_defaults" / "TestTask" / "data" / "test.csv") expected = pd.read_csv(tmpdir / "dataset.csv") expected["a"] *= 10 assert result.equals(expected) def test_no_dataset_no_input(self, TestTask, tmpdir): # Test with no dataset and no input (should fail) class FailingTestTask(TestTask): pass failed_tasks = [] exceptions = [] @FailingTestTask.event_handler(luigi.Event.FAILURE) def check_exception(failed_task, exception): # pylint: disable=unused-variable failed_tasks.append(str(failed_task)) exceptions.append(str(exception)) assert not luigi.build( [FailingTestTask(result_path=str(tmpdir / "out_fail"))], local_scheduler=True ) assert failed_tasks == [str(FailingTestTask(result_path=str(tmpdir / "out_fail")))] assert exceptions == [ str(ValueError("Either the 'dataset_df' parameter or a requirement must be provided.")) ] def test_inputs_outputs(self, TestTask, dataset_df_path, tmpdir): # Test inputs class TestTaskWithOutputs(task.SetValidationTask): output_columns = {"a": None} @staticmethod def validation_function(df, output_path, *args, **kwargs): assert df["is_valid"].all() assert (df["ret_code"] == 0).all() assert df["comment"].isnull().all() assert df["exception"].isnull().all() assert df["a"].tolist() == [1, 2] assert df["b"].tolist() == [3, 4] df["a"] *= 10 df[["a", "b"]].to_csv(output_path / "test.csv") class TestTaskWithInputs(task.SetValidationTask): def inputs(self): return { TestTaskWithOutputs: ( { "dataset_df": dataset_df_path, "result_path": self.result_path, }, {"a": "a_input"}, ) } def kwargs(self): return {"dataset_df": self.dataset_df} @staticmethod def validation_function(df, output_path, *args, **kwargs): assert df["is_valid"].all() assert (df["ret_code"] == 0).all() assert df["comment"].isnull().all() assert df["exception"].isnull().all() assert df["a_input"].tolist() == [10, 20] if kwargs["dataset_df"] is not None: assert df["a"].tolist() == [1, 2] assert df["b"].tolist() == [3, 4] df["a_input"] *= 10 df.to_csv(output_path / "test.csv") # Test with inputs but no dataset assert luigi.build( [TestTaskWithInputs(result_path=str(tmpdir / "out_inputs"))], local_scheduler=True ) result = pd.read_csv(tmpdir / "out_inputs" / "TestTaskWithInputs" / "data" / "test.csv") expected = pd.read_csv(tmpdir / "dataset.csv") expected["a_input"] = expected["a"] * 100 assert (result["a_input"] == expected["a_input"]).all() # Test with inputs and dataset assert luigi.build( [ TestTaskWithInputs( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_inputs_and_outputs") ) ], local_scheduler=True, ) result = pd.read_csv( tmpdir / "out_inputs_and_outputs" / "TestTaskWithInputs" / "data" / "test.csv" ) expected = pd.read_csv(tmpdir / "dataset.csv") expected["a_input"] = expected["a"] * 100 assert result[["a", "b", "a_input"]].equals(expected[["a", "b", "a_input"]]) def test_missing_columns(self, TestTask, dataset_df_path, tmpdir): # Test missing columns in requirements class TestTaskMissingColumns(task.SetValidationTask): def inputs(self): return {TestTask: {"a": "a_input"}} @staticmethod def validation_function(df, output_path, *args, **kwargs): assert df["is_valid"].all() assert (df["ret_code"] == 0).all() assert df["comment"].isnull().all() assert df["exception"].isnull().all() assert df["a_input"].tolist() == [10, 20] df["a_input"] *= 10 df.to_csv(output_path / "test.csv") failed_tasks = [] exceptions = [] @TestTaskMissingColumns.event_handler(luigi.Event.FAILURE) def check_exception(failed_task, exception): # pylint: disable=unused-variable failed_tasks.append(str(failed_task)) exceptions.append(str(exception)) assert not luigi.build( [ TestTaskMissingColumns( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_missing_columns") ) ], local_scheduler=True, ) assert failed_tasks == [ str( TestTaskMissingColumns( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_missing_columns") ) ) ] assert exceptions == [ str( KeyError( "The columns ['a'] are missing from the output columns of " "TestTask(" f"tag_output=False, result_path={tmpdir / 'out_missing_columns'}, " f"dataset_df={dataset_df_path}, input_index_col=, data_dir=data).", ) ) ] def test_wrong_inputs(self, TestTask, dataset_df_path, tmpdir): # Test bad format in inputs class TestTaskMissingColumns(task.SetValidationTask): def inputs(self): return {TestTask: "BAD INPUTS"} @staticmethod def validation_function(df, output_path, *args, **kwargs): pass with pytest.raises( ValueError, match=( "The input values should either be a dict containing the column mapping or a tuple " "with a dict containing the keyword arguments as first element and a dict " r"containing the column mapping as second element\." ), ): luigi.build( [ TestTaskMissingColumns( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_bad_inputs") ) ], local_scheduler=True, ) def test_validation_function_as_method(self, dataset_df_path, tmpdir): class TestTask(task.SetValidationTask): # pylint: disable=no-self-argument def validation_function(df, output_path, *args, **kwargs): df["a"] *= 10 df[["a", "b"]].to_csv(output_path / "test.csv") # Test defaults assert luigi.build( [TestTask(dataset_df=dataset_df_path, result_path=str(tmpdir / "out_defaults"))], local_scheduler=True, ) result = pd.read_csv(tmpdir / "out_defaults" / "TestTask" / "data" / "test.csv") expected = pd.read_csv(tmpdir / "dataset.csv") expected["a"] *= 10 assert result.equals(expected) class TestPropagation: @pytest.fixture def BaseTestTask(self, TestTask): class BaseTestTask(TestTask): def kwargs(self): return { "dataset_df": str(self.dataset_df), "result_path": str(self.result_path), } @staticmethod def validation_function(df, output_path, *args, **kwargs): with open(output_path / "test.json", "w", encoding="utf-8") as f: json.dump(kwargs, f) TestTask.validation_function(df, output_path, *args, **kwargs) return BaseTestTask @pytest.fixture def TestTaskPassDatasetAndResultPath(self, BaseTestTask): class TestTaskPassDatasetAndResultPath(task.SetValidationTask): def inputs(self): return {BaseTestTask: {}} @staticmethod def validation_function(df, output_path, *args, **kwargs): assert df["is_valid"].all() assert (df["ret_code"] == 0).all() assert df["comment"].isnull().all() assert df["exception"].isnull().all() assert df["a"].tolist() == [1, 2] df["a"] *= 100 df.to_csv(output_path / "test.csv") return TestTaskPassDatasetAndResultPath @pytest.fixture def TestTaskPassDatasetAndResultPathWithKwargs(self, BaseTestTask): class TestTaskPassDatasetAndResultPath(task.SetValidationTask): def inputs(self): return {BaseTestTask: ({"result_path": str(self.result_path / "sub_path")}, {})} @staticmethod def validation_function(df, output_path, *args, **kwargs): assert df["is_valid"].all() assert (df["ret_code"] == 0).all() assert df["comment"].isnull().all() assert df["exception"].isnull().all() assert df["a"].tolist() == [1, 2] df["a"] *= 100 df.to_csv(output_path / "test.csv") return TestTaskPassDatasetAndResultPath @pytest.fixture def TestTaskPassDatasetAndResultPathWithInputParameters(self, BaseTestTask): class TestTaskPassDatasetAndResultPath(task.SetValidationTask): def inputs(self): return { BaseTestTask: task.InputParameters( {}, result_path=str(self.result_path / "sub_path") ) } @staticmethod def validation_function(df, output_path, *args, **kwargs): assert df["is_valid"].all() assert (df["ret_code"] == 0).all() assert df["comment"].isnull().all() assert df["exception"].isnull().all() assert df["a"].tolist() == [1, 2] df["a"] *= 100 df.to_csv(output_path / "test.csv") return TestTaskPassDatasetAndResultPath @staticmethod def _check_results(tmpdir, workflow_result_subpath, base_result_subpath=None): if base_result_subpath is None: base_result_subpath = workflow_result_subpath with open( tmpdir / base_result_subpath / "BaseTestTask" / "data" / "test.json", encoding="utf-8", ) as f: params = json.load(f) assert params == { "dataset_df": f"{tmpdir}/dataset.csv", "result_path": f"{tmpdir}/{base_result_subpath}", } result_1 = pd.read_csv( tmpdir / base_result_subpath / "BaseTestTask" / "data" / "test.csv" ) result_2 = pd.read_csv( tmpdir / workflow_result_subpath / "TestTaskPassDatasetAndResultPath" / "data" / "test.csv" ) expected = pd.read_csv(tmpdir / "dataset.csv") expected["a"] *= 10 assert result_1.equals(expected) expected["a"] *= 10 assert result_2[["a", "b"]].equals(expected[["a", "b"]]) def test_dataset_propagation( self, TestTaskPassDatasetAndResultPath, dataset_df_path, tmpdir ): # Test that the dataset is properly passed to the requirements assert luigi.build( [ TestTaskPassDatasetAndResultPath( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_pass_dataset") ) ], local_scheduler=True, ) self._check_results(tmpdir, "out_pass_dataset", "out_pass_dataset") def test_dataset_propagation_with_config( self, TestTaskPassDatasetAndResultPath, dataset_df_path, tmpdir ): # Test that the dataset is not propagated when a value is already given in the config with luigi_tools.util.set_luigi_config( { "BaseTestTask": { "result_path": str(tmpdir / "specific_out_path"), } } ): assert luigi.build( [ TestTaskPassDatasetAndResultPath( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_pass_dataset") ) ], local_scheduler=True, ) self._check_results(tmpdir, "out_pass_dataset", "specific_out_path") def test_dataset_propagation_with_kwargs( self, TestTaskPassDatasetAndResultPathWithKwargs, dataset_df_path, tmpdir ): # Test that the dataset is properly passed to the requirements assert luigi.build( [ TestTaskPassDatasetAndResultPathWithKwargs( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_pass_dataset") ) ], local_scheduler=True, ) self._check_results(tmpdir, "out_pass_dataset", "out_pass_dataset/sub_path") def test_dataset_propagation_with_config_and_kwargs( self, TestTaskPassDatasetAndResultPathWithKwargs, dataset_df_path, tmpdir ): # Test that the dataset is propagated from the constructor even when a value is already # given in the config with luigi_tools.util.set_luigi_config( { "BaseTestTask": { "result_path": str(tmpdir / "specific_out_path"), } } ): assert luigi.build( [ TestTaskPassDatasetAndResultPathWithKwargs( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_pass_dataset") ) ], local_scheduler=True, ) self._check_results(tmpdir, "out_pass_dataset", "out_pass_dataset/sub_path") def test_dataset_propagation_with_input_parameters( self, TestTaskPassDatasetAndResultPathWithInputParameters, dataset_df_path, tmpdir ): # Test that the dataset is properly passed to the requirements assert luigi.build( [ TestTaskPassDatasetAndResultPathWithInputParameters( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_pass_dataset") ) ], local_scheduler=True, ) self._check_results(tmpdir, "out_pass_dataset", "out_pass_dataset/sub_path") def test_dataset_propagation_with_config_and_input_parameters( self, TestTaskPassDatasetAndResultPathWithInputParameters, dataset_df_path, tmpdir ): # Test that the dataset is propagated from the constructor even when a value is already # given in the config with luigi_tools.util.set_luigi_config( { "BaseTestTask": { "result_path": str(tmpdir / "specific_out_path"), } } ): assert luigi.build( [ TestTaskPassDatasetAndResultPathWithInputParameters( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_pass_dataset") ) ], local_scheduler=True, ) self._check_results(tmpdir, "out_pass_dataset", "out_pass_dataset/sub_path") def test_failing_validation_function(self, TestTask, dataset_df_path, tmpdir): # Test with a failing validation function class FailingTestTask(TestTask): @staticmethod def validation_function(*args, **kwargs): raise RuntimeError("This function always fails") assert luigi.build( [ FailingTestTask( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_failing_validation_function"), ) ], local_scheduler=True, ) result = pd.read_csv( tmpdir / "out_failing_validation_function" / "FailingTestTask" / "report.csv" ) assert (~result["is_valid"]).all() assert (result["ret_code"] == 1).all() assert (result["comment"].isnull()).all() assert ( result["exception"].str.split("\n").apply(lambda x: x[5]) == "RuntimeError: This function always fails" ).all() def test_task_name(self, dataset_df_path, tmpdir): # Test with a custom task name class TestTask(task.SetValidationTask): task_name = "test_custom_task_name" @staticmethod def validation_function(*args, **kwargs): pass assert luigi.build( [ TestTask( dataset_df=dataset_df_path, result_path=str(tmpdir), ) ], local_scheduler=True, ) assert (tmpdir / "test_custom_task_name" / "report.csv").exists() def test_duplicated_index(self, tmpdir, TestTask): dataset_df_path = str(tmpdir / "dataset.csv") base_dataset_df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]}, index=[0, 1, 1, 0]) base_dataset_df.to_csv(dataset_df_path, index=True, index_label="index_col") failed_tasks = [] exceptions = [] @TestTask.event_handler(luigi.Event.FAILURE) def check_exception(failed_task, exception): # pylint: disable=unused-variable failed_tasks.append(str(failed_task)) exceptions.append(str(exception)) failing_task = TestTask( dataset_df=dataset_df_path, input_index_col="index_col", result_path=str(tmpdir / "out_failing_duplicated_index"), ) assert not luigi.build([failing_task], local_scheduler=True) assert failed_tasks == [str(failing_task)] assert exceptions == [str(IndexError("The following index values are duplicated: [0, 1]"))] def test_change_index(self, tmpdir, TestTask): dataset_df_path = str(tmpdir / "dataset.csv") base_dataset_df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]}, index=[0, 1, 2, 3]) base_dataset_df.to_csv(dataset_df_path, index=True, index_label="index_col") class TestTaskUpdateIndex(TestTask): @staticmethod def validation_function(df, output_path, *args, **kwargs): df.sort_index(ascending=False, inplace=True) failed_tasks = [] exceptions = [] @TestTaskUpdateIndex.event_handler(luigi.Event.FAILURE) def check_exception(failed_task, exception): # pylint: disable=unused-variable failed_tasks.append(str(failed_task)) exceptions.append(str(exception)) failing_task = TestTaskUpdateIndex( dataset_df=dataset_df_path, input_index_col="index_col", result_path=str(tmpdir / "out_failing_update_index"), ) assert not luigi.build([failing_task], local_scheduler=True) assert failed_tasks == [str(failing_task)] assert exceptions == [ str( IndexError( "The index changed during the process. Please update your validation function " "or your pre/post process functions to avoid this behaviour." ) ) ] def test_missing_retcodes(self, tmpdir, dataset_df_path, TestTask): class TestTaskMissingRetcodes(TestTask): mode = OptionalStrParameter(default=None) def kwargs(self): return {"mode": self.mode} @staticmethod def validation_function(df, output_path, *args, **kwargs): if kwargs["mode"] == "valid": df["is_valid"] = True df["ret_code"] = 1 elif kwargs["mode"] == "not valid": df["is_valid"] = False df["ret_code"] = 0 failed_tasks = [] exceptions = [] @TestTaskMissingRetcodes.event_handler(luigi.Event.FAILURE) def check_exception(failed_task, exception): # pylint: disable=unused-variable failed_tasks.append(str(failed_task)) exceptions.append(str(exception)) failing_task_valid = TestTaskMissingRetcodes( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_missing_retcode"), mode="valid", ) failing_task_notvalid = TestTaskMissingRetcodes( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_missing_retcode"), mode="not valid", ) assert not luigi.build([failing_task_valid], local_scheduler=True) assert not luigi.build([failing_task_notvalid], local_scheduler=True) assert failed_tasks == [str(failing_task_valid), str(failing_task_notvalid)] assert ( exceptions == [ str( task.ValidationError( "The 'ret_code' values are not consistent with the 'is_valid' values." ) ) ] * 2 ) def test_missing_comments(self, tmpdir, dataset_df_path, TestTask): class TestTaskMissingComments(TestTask): mode = OptionalStrParameter(default=None) def kwargs(self): return {"mode": self.mode} @staticmethod def validation_function(df, output_path, *args, **kwargs): if kwargs["mode"] == "valid": df["is_valid"] = True df["ret_code"] = 2 elif kwargs["mode"] == "not valid": df["is_valid"] = False df["ret_code"] = 2 failed_tasks = [] exceptions = [] @TestTaskMissingComments.event_handler(luigi.Event.FAILURE) def check_exception(failed_task, exception): # pylint: disable=unused-variable failed_tasks.append(str(failed_task)) exceptions.append(str(exception)) failing_task_valid = TestTaskMissingComments( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_missing_comments_valid"), mode="valid", ) failing_task_notvalid = TestTaskMissingComments( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_missing_comments_not_valid"), mode="not valid", ) with pytest.warns( UserWarning, match="A comment should be set when the 'ret_code' is greater than 1." ): assert luigi.build([failing_task_valid], local_scheduler=True) with pytest.warns( UserWarning, match="A comment should be set when the 'ret_code' is greater than 1." ): assert luigi.build([failing_task_notvalid], local_scheduler=True) def test_rename_multiindex(self): df_1_level = pd.DataFrame({"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]}, index=[0, 1, 2, 3]) task.BaseValidationTask._rename_cols(df_1_level) # pylint: disable=protected-access assert df_1_level.columns.tolist() == ["a", "b"] df_2_levels = pd.DataFrame( {"a": [1, 2, 3, 4], "b": [5, 6, 7, 8], "Unnamed: c": [9, 10, 11, 12]}, index=[0, 1, 2, 3], ) df_2_levels.columns = pd.MultiIndex.from_tuples( [("level_1", i) for i in df_2_levels.columns.values] ) task.BaseValidationTask._rename_cols(df_2_levels) # pylint: disable=protected-access assert df_2_levels.columns.tolist() == [("level_1", "a"), ("level_1", "b"), ("level_1", "")] def test_check_inputs(self, TestTask): assert not task.BaseValidationTask.check_inputs({}) assert not task.BaseValidationTask.check_inputs(None) with pytest.raises( ValueError, match=( r"The destination column of the task TestTask\(tag_output=False, result_path=, " r"dataset_df=, input_index_col=, data_dir=data\) can not be one of " r"\['is_valid', 'ret_code', 'comment', 'exception'\]\." ), ): task.BaseValidationTask.check_inputs( { TestTask(): {"a": "is_valid"}, } ) class TestConflictingColumns(task.SetValidationTask): pass with pytest.raises( ValueError, match=( r"The destination column 'a_conflict' of the tasks TestConflictingColumns\(" r"tag_output=False, result_path=, dataset_df=, input_index_col=, data_dir=data\) " r"and TestTask\(tag_output=False, result_path=, dataset_df=, input_index_col=, " r"data_dir=data\) are conflicting\." ), ): task.BaseValidationTask.check_inputs( {TestTask(): {"a": "a_conflict"}, TestConflictingColumns(): {"a": "a_conflict"}} ) def test_extra_requires(self, tmpdir, dataset_df_path): class TestTaskA(luigi.Task): def run(self): assert self.output().path == str(tmpdir / "file.test") with open(self.output().path, "w", encoding="utf-8") as f: f.write("result of TestTaskA") def output(self): return target.OutputLocalTarget(tmpdir / "file.test") class TestTaskB(task.SetValidationTask): output_columns = {"extra_path": None, "extra_result": None} def kwargs(self): return {"extra_task_target": self.extra_input().path} def extra_requires(self): return TestTaskA() @staticmethod def validation_function(df, output_path, *args, **kwargs): df["is_valid"] = True df["extra_path"] = kwargs["extra_task_target"] with open(kwargs["extra_task_target"], encoding="utf-8") as f: df["extra_result"] = f.read() assert luigi.build( [TestTaskB(dataset_df=dataset_df_path, result_path=str(tmpdir / "extra_requires"))], local_scheduler=True, ) res = pd.read_csv(tmpdir / "extra_requires" / "TestTaskB" / "report.csv") assert (res["extra_path"] == str(tmpdir / "file.test")).all() assert (res["extra_result"] == "result of TestTaskA").all() def test_static_args_kwargs(self, dataset_df_path): class TestTask(task.ElementValidationTask): args = [1, "a"] kwargs = {"int_value": 1, "str_value": "a"} @staticmethod def validation_function(df, output_path, *args, **kwargs): assert args == [1, "a"] assert kwargs == {"int_value": 1, "str_value": "a"} assert luigi.build( [TestTask(dataset_df=dataset_df_path)], local_scheduler=True, ) class TestFailingArgsTask(task.ElementValidationTask): args = 1 @staticmethod def validation_function(df, output_path, *args, **kwargs): assert args == 1 failed_tasks = [] exceptions = [] @TestFailingArgsTask.event_handler(luigi.Event.FAILURE) def check_exception_args(failed_task, exception): # pylint: disable=unused-variable failed_tasks.append(str(failed_task)) exceptions.append(str(exception)) assert not luigi.build( [TestFailingArgsTask(dataset_df=dataset_df_path)], local_scheduler=True, ) assert failed_tasks == [str(TestFailingArgsTask(dataset_df=dataset_df_path))] assert exceptions == [ str( TypeError( "The 'args' must either be a method returning a list or a tuple, or an actual " "list or tuple." ) ) ] class TestFailingKwargsTask(task.ElementValidationTask): kwargs = 1 @staticmethod def validation_function(df, output_path, *args, **kwargs): assert kwargs == 1 failed_tasks = [] exceptions = [] @TestFailingKwargsTask.event_handler(luigi.Event.FAILURE) def check_exception_kwargs(failed_task, exception): # pylint: disable=unused-variable failed_tasks.append(str(failed_task)) exceptions.append(str(exception)) assert not luigi.build( [TestFailingKwargsTask(dataset_df=dataset_df_path)], local_scheduler=True, ) assert failed_tasks == [str(TestFailingKwargsTask(dataset_df=dataset_df_path))] assert exceptions == [ str( TypeError( "The 'kwargs' must either be a method returning a dict, or an actual dict." ) ) ] def test_different_input_index(self, tmpdir, dataset_df_path, caplog): class TestTask(task.ElementValidationTask): @staticmethod def validation_function(df, output_path, *args, **kwargs): pass class TestDifferentInputIndex(task.ElementValidationTask): def inputs(self): return { TestTask: ( { "dataset_df": dataset_df_path, "input_index_col": self.input_index_col, }, {}, ) } @staticmethod def validation_function(df, output_path, *args, **kwargs): pass updated_dataset = pd.read_csv(dataset_df_path) updated_dataset.index += 1 name_parts = dataset_df_path.rsplit(".", 1) name_parts[0] += "_updated" new_df_path = ".".join(name_parts) updated_dataset.to_csv(new_df_path) caplog.clear() caplog.set_level(logging.DEBUG) assert luigi.build( [ TestDifferentInputIndex( dataset_df=new_df_path, result_path=str(tmpdir / "different_input_index"), input_index_col=0, ) ], local_scheduler=True, ) res = [ i for i in caplog.record_tuples if i[0] == "data_validation_framework.task" and i[1] == logging.WARNING ] assert len(res) == 1 assert res[0][2] == ( "The following inconsistent indexes between the dataset and the inputs are " "ignored: [2]" ) def test_external_function(self, dataset_df_path): def external_function(df, output_path, *args, **kwargs): assert args == [1, "a"] assert kwargs == {"k1": 1, "k2": 2} class TestExternalFunctionTask(task.ElementValidationTask): args = [1, "a"] kwargs = {"k1": 1, "k2": 2} validation_function = external_function assert luigi.build( [TestExternalFunctionTask(dataset_df=dataset_df_path)], local_scheduler=True, ) class TestElementValidationTask: """Test the data_validation_framework.task.ElementValidationTask class.""" @pytest.fixture def TestTask(self, tmpdir): class TestTask(task.ElementValidationTask): @staticmethod # pylint: disable=arguments-differ def validation_function(row, output_path, *args, **kwargs): if row["a"] <= 1: return result.ValidationResult(is_valid=True) if row["a"] <= 2: return result.ValidationResult(is_valid=False, comment="bad value") raise ValueError(f"Incorrect value {row['a']}") return TestTask @pytest.fixture def dataset_df_path(self, tmpdir): dataset_df_path = tmpdir / "dataset.csv" base_dataset_df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) base_dataset_df.to_csv(dataset_df_path) return str(dataset_df_path) def test_defaults(self, TestTask, dataset_df_path, tmpdir): # Test that the dataset is properly passed to the requirements assert luigi.build( [TestTask(dataset_df=dataset_df_path, result_path=str(tmpdir / "out"))], local_scheduler=True, ) result = pd.read_csv(tmpdir / "out" / "TestTask" / "report.csv") assert result["is_valid"].tolist() == [True, False, False] assert result["ret_code"].tolist() == [0, 1, 1] assert result["comment"].tolist() == [np.nan, "bad value", np.nan] assert result.loc[[0, 1], "exception"].isnull().all() assert result.loc[2, "exception"].split("\n")[5] == "ValueError: Incorrect value 3" @pytest.mark.parametrize("nb_processes", [None, 1, 5]) def test_nb_processes(self, TestTask, dataset_df_path, tmpdir, nb_processes): # Test that the number of processes is properly passed to the requirements class TestWorkflow(task.ValidationWorkflow): def inputs(self): return {TestTask: {}} assert ( TestWorkflow( dataset_df=dataset_df_path, result_path=str(tmpdir / "out"), nb_processes=nb_processes, ) .requires()[0] .nb_processes == nb_processes ) @pytest.mark.parametrize("redirect_stdout", [True, False]) def test_redirect_stdout(self, TestTask, dataset_df_path, tmpdir, redirect_stdout): # Test that the number of processes is properly passed to the requirements class TestWorkflow(task.ValidationWorkflow): def inputs(self): return {TestTask: {}} assert ( TestWorkflow( dataset_df=dataset_df_path, result_path=str(tmpdir / "out"), redirect_stdout=redirect_stdout, ) .requires()[0] .redirect_stdout == redirect_stdout ) class TestValidationWorkflow: """Test the data_validation_framework.task.ValidationWorkflow class.""" @pytest.fixture def comment(self): return "This element is not valid" @pytest.fixture def exception(self): return ( "Traceback (most recent call last):" ' File "test.py", line 1, in <module>' ' raise ValueError("This element is not valid")' "ValueError: This element is not valid" ) @pytest.fixture def default_report_config_test_date(self): report._DEFAULT_REPORT_CONFIG["today"] = "TEST DATE" # pylint: disable=protected-access yield None report._DEFAULT_REPORT_CONFIG.pop("today") # pylint: disable=protected-access def test_gather(self, tmpdir, dataset_df_path, comment, exception): class TestTask(task.SetValidationTask): @staticmethod def validation_function(df, output_path, *args, **kwargs): df.loc[1, "is_valid"] = False df.loc[1, "ret_code"] = 1 df.loc[1, "comment"] = comment df.loc[1, "exception"] = exception class TestWorkflow(task.ValidationWorkflow): def inputs(self): return {TestTask: {}} @staticmethod def validation_function(df, output_path, *args, **kwargs): df.to_csv(output_path / "test_gather.csv") assert luigi.build( [TestWorkflow(dataset_df=dataset_df_path, result_path=str(tmpdir))], local_scheduler=True, ) assert (tmpdir / "dataset.csv").exists() assert (tmpdir / "TestTask" / "report.csv").exists() assert (tmpdir / "TestWorkflow" / "report.csv").exists() result = pd.read_csv(tmpdir / "TestWorkflow" / "report.csv") expected = pd.DataFrame( { "__index_label__": [0, 1], "is_valid": [True, False], "ret_code": [0, 1], "('TestTask', 'is_valid')": [True, False], "('TestTask', 'ret_code')": [0, 1], } ) assert result.columns.tolist() == [ "__index_label__", "is_valid", "ret_code", "comment", "exception", "('TestTask', 'is_valid')", "('TestTask', 'ret_code')", "('TestTask', 'comment')", "('TestTask', 'exception')", ] assert result[ # pylint: disable=unsubscriptable-object [ "__index_label__", "is_valid", "ret_code", "('TestTask', 'is_valid')", "('TestTask', 'ret_code')", ] ].equals(expected) assert ( result.loc[ 0, ["comment", "exception", "('TestTask', 'comment')", "('TestTask', 'exception')"] ] .isnull() .all() .all() ) assert (result.loc[1, ["comment", "exception"]].isnull()).all() assert result.loc[1, "('TestTask', 'comment')"] == comment assert result.loc[1, "('TestTask', 'exception')"] == exception def test_no_report(self, tmpdir, dataset_df_path): class TestTask(task.SetValidationTask): @staticmethod def validation_function(*args, **kwargs): pass class TestWorkflow(task.ValidationWorkflow): generate_report = False def inputs(self): return {TestTask: {}} assert luigi.build( [TestWorkflow(dataset_df=dataset_df_path, result_path=str(tmpdir))], local_scheduler=True, ) assert (tmpdir / "TestWorkflow" / "report.csv").exists() assert not (tmpdir / "report.pdf").exists() class TestReport: """Test the report generation after workflow run.""" @pytest.fixture def TestTask(self, comment, exception): class TestTask(task.SetValidationTask): """A test validation task.""" no_exception = luigi.BoolParameter(default=False) mode = OptionalStrParameter(default=None) def kwargs(self): return { "no_exception": self.no_exception, "mode": self.mode, } @staticmethod def validation_function(df, output_path, *args, **kwargs): if kwargs["mode"] == "all_succeed": df["is_valid"] = True df["ret_code"] = 0 elif kwargs["mode"] == "all_fail": df["is_valid"] = False df["ret_code"] = 1 else: df.loc[1, "is_valid"] = False df.loc[1, "ret_code"] = 1 if not kwargs["no_exception"]: df.loc[1, "comment"] = comment df.loc[1, "exception"] = exception return TestTask @pytest.fixture def TestTask_Specifications(self): class TestTask_Specifications(task.SetValidationTask): """A test validation task with a specific report doc.""" __specifications__ = "The specific doc only used in report." @staticmethod def validation_function(*args, **kwargs): pass return TestTask_Specifications @pytest.fixture def TestWorkflow(self, TestTask, TestTask_Specifications): class TestWorkflow(task.ValidationWorkflow): """The global validation workflow.""" no_exception = luigi.BoolParameter(default=False) mode = OptionalStrParameter(default=None) def inputs(self): return { TestTask: ({"no_exception": self.no_exception, "mode": self.mode}, {}), TestTask_Specifications: {}, } return TestWorkflow def test_specifications(self, TestTask, TestTask_Specifications): assert TestTask(dataset_df="", result_path="").__specifications__ == ( "A test validation task." ) assert TestTask_Specifications(dataset_df="", result_path="").__specifications__ == ( "The specific doc only used in report." ) def test_rst2pdf( self, tmpdir, dataset_df_path, data_dir, TestWorkflow, default_report_config_test_date ): root = tmpdir / "rst2pdf" assert luigi.build( [TestWorkflow(dataset_df=dataset_df_path, result_path=str(root))], local_scheduler=True, ) assert (root / "TestWorkflow" / "report.csv").exists() assert (root / "report_TestWorkflow.pdf").exists() assert pdfdiff( root / "report_TestWorkflow.pdf", data_dir / "test_report" / "report_rst2pdf.pdf" ) @pytest.mark.skipif(SKIP_IF_NO_LATEXMK, reason=REASON_NO_LATEXMK) def test_latexpdf( self, tmpdir, dataset_df_path, data_dir, TestWorkflow, default_report_config_test_date ): root = tmpdir / "latexpdf" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), report_type="latexpdf" ) ], local_scheduler=True, ) assert (root / "TestWorkflow" / "report.csv").exists() assert (root / "report_TestWorkflow.pdf").exists() assert pdfdiff( root / "report_TestWorkflow.pdf", data_dir / "test_report" / "report_latexpdf.pdf" ) def test_fail_element_no_exception( self, tmpdir, dataset_df_path, data_dir, TestWorkflow, default_report_config_test_date ): root = tmpdir / "rst2pdf_no_exception" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), no_exception=True ) ], local_scheduler=True, ) assert (root / "TestWorkflow" / "report.csv").exists() assert (root / "report_TestWorkflow.pdf").exists() assert pdfdiff( root / "report_TestWorkflow.pdf", data_dir / "test_report" / "report_no_exception_rst2pdf.pdf", ) def test_exception_levels( self, tmpdir, dataset_df_path, data_dir, TestWorkflow, default_report_config_test_date ): class TestTask_levels(task.SetValidationTask): """A test validation task with a deep level.""" @staticmethod def validation_function(*args, **kwargs): raise ValueError("Bad value") class TestWorkflow_lvl4(task.ValidationWorkflow): """A nested validation workflow with level 3.""" def inputs(self): return { TestTask_levels: {}, } class TestWorkflow_lvl3(task.ValidationWorkflow): """A nested validation workflow with level 3.""" def inputs(self): return { TestWorkflow_lvl4: {}, } class TestWorkflow_lvl2(task.ValidationWorkflow): """A nested validation workflow with level 2.""" def inputs(self): return { TestWorkflow_lvl3: {}, } class TestWorkflow_lvl1(task.ValidationWorkflow): """A nested validation workflow with level 1.""" def inputs(self): return { TestWorkflow_lvl2: {}, } class TestWorkflow_lvl0(task.ValidationWorkflow): """The global validation workflow.""" def inputs(self): return { TestWorkflow_lvl1: {}, } root = tmpdir / "rst2pdf_levels" assert luigi.build( [TestWorkflow_lvl0(dataset_df=dataset_df_path, result_path=str(root))], local_scheduler=True, ) assert (root / "TestWorkflow_lvl0" / "report.csv").exists() assert (root / "report_TestWorkflow_lvl4.pdf").exists() assert (root / "report_TestWorkflow_lvl3.pdf").exists() assert (root / "report_TestWorkflow_lvl2.pdf").exists() assert (root / "report_TestWorkflow_lvl1.pdf").exists() assert (root / "report_TestWorkflow_lvl0.pdf").exists() def test_report_relative_path( self, tmpdir, dataset_df_path, data_dir, TestWorkflow, default_report_config_test_date ): root = tmpdir / "relative_path" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), report_path="report_test_name.pdf", ) ], local_scheduler=True, ) assert (root / "TestWorkflow" / "report.csv").exists() assert (root / "report_test_name.pdf").exists() assert pdfdiff( root / "report_test_name.pdf", data_dir / "test_report" / "report_rst2pdf.pdf" ) def test_report_absolute_path( self, tmpdir, dataset_df_path, data_dir, TestWorkflow, default_report_config_test_date ): root = tmpdir / "absolute_path" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), report_path=str(tmpdir / "report_test_absolute.pdf"), ) ], local_scheduler=True, ) assert (root / "TestWorkflow" / "report.csv").exists() assert (tmpdir / "report_test_absolute.pdf").exists() assert pdfdiff( tmpdir / "report_test_absolute.pdf", data_dir / "test_report" / "report_rst2pdf.pdf" ) def test_report_all_succeed( self, tmpdir, dataset_df_path, data_dir, TestWorkflow, default_report_config_test_date ): root = tmpdir / "all_succeed" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), report_path=str(tmpdir / "report_test_all_success.pdf"), mode="all_succeed", ) ], local_scheduler=True, ) assert (root / "TestWorkflow" / "report.csv").exists() assert (tmpdir / "report_test_all_success.pdf").exists() assert pdfdiff( tmpdir / "report_test_all_success.pdf", data_dir / "test_report" / "report_rst2pdf_all_success.pdf", ) def test_report_all_fail( self, tmpdir, dataset_df_path, data_dir, TestWorkflow, default_report_config_test_date ): root = tmpdir / "all_fail" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), report_path=str(tmpdir / "report_test_all_fail.pdf"), mode="all_fail", ) ], local_scheduler=True, ) assert (root / "TestWorkflow" / "report.csv").exists() assert (tmpdir / "report_test_all_fail.pdf").exists() assert pdfdiff( tmpdir / "report_test_all_fail.pdf", data_dir / "test_report" / "report_rst2pdf_all_fail.pdf", ) def test_report_warnings( self, tmpdir, dataset_df_path, data_dir, default_report_config_test_date ): class TestTask_Warning(task.ElementValidationTask): """A test validation task which can return warnings.""" @staticmethod # pylint: disable=arguments-differ def validation_function(row, output_path, *args, **kwargs): if row["a"] <= 1: return result.ValidationResult( is_valid=True, ret_code=2, comment="a succeeding warning" ) if row["a"] <= 2: return result.ValidationResult( is_valid=False, ret_code=3, comment="a failing warning" ) raise ValueError(f"Incorrect value {row['a']}") class TestWorkflow(task.ValidationWorkflow): """The global validation workflow.""" def inputs(self): return { TestTask_Warning: {}, } root = tmpdir / "with_warnings" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), report_path=str(tmpdir / "report_test_warnings.pdf"), ) ], local_scheduler=True, ) assert (root / "TestWorkflow" / "report.csv").exists() assert (tmpdir / "report_test_warnings.pdf").exists() assert pdfdiff( tmpdir / "report_test_warnings.pdf", data_dir / "test_report" / "report_rst2pdf_warnings.pdf", ) class TestReportBeforeRun: """Test the report generation before workflow run (generate only the specifications).""" @pytest.fixture def TestTask(self): class TestTask(task.SetValidationTask): """A test validation task.""" def run(self): raise RuntimeError("THIS TASK SHOULD NOT BE RUN") return TestTask @pytest.fixture def TestTask_Specifications(self): class TestTask_Specifications(task.SetValidationTask): """A test validation task with a specific report doc.""" __specifications__ = "The specific doc only used in report." def run(self): raise RuntimeError("THIS TASK SHOULD NOT BE RUN") return TestTask_Specifications @pytest.fixture def TestWorkflow(self, TestTask, TestTask_Specifications): class TestWorkflow(task.ValidationWorkflow): """The global validation workflow.""" def inputs(self): return { TestTask: {}, TestTask_Specifications: {}, } return TestWorkflow @pytest.fixture def TestNestedWorkflow(self, TestTask, TestWorkflow): class TestNestedWorkflow(task.ValidationWorkflow): """The global validation workflow.""" def inputs(self): return { TestTask: {}, TestWorkflow: {}, } return TestNestedWorkflow def test_rst2pdf(self, tmpdir, dataset_df_path, data_dir, TestWorkflow): root = tmpdir / "rst2pdf" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), specifications_only=True, ) ], local_scheduler=True, ) assert (root / "TestWorkflow_specifications.pdf").exists() assert pdfdiff( root / "TestWorkflow_specifications.pdf", data_dir / "test_report_before_run" / "report_rst2pdf.pdf", threshold=25, ) def test_rst2pdf_report_path(self, tmpdir, dataset_df_path, data_dir, TestWorkflow): root = tmpdir / "rst2pdf" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), report_path="test_custom_document_name.pdf", specifications_only=True, ) ], local_scheduler=True, ) assert (root / "test_custom_document_name.pdf").exists() assert pdfdiff( root / "test_custom_document_name.pdf", data_dir / "test_report_before_run" / "report_rst2pdf.pdf", threshold=25, ) @pytest.mark.skipif(SKIP_IF_NO_LATEXMK, reason=REASON_NO_LATEXMK) def test_latexpdf(self, tmpdir, dataset_df_path, data_dir, TestWorkflow): root = tmpdir / "latexpdf" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), report_type="latexpdf", specifications_only=True, ) ], local_scheduler=True, ) assert (root / "TestWorkflow_specifications.pdf").exists() assert pdfdiff( root / "TestWorkflow_specifications.pdf", data_dir / "test_report_before_run" / "report_latexpdf.pdf", threshold=15, ) @pytest.fixture def report_config(self): return { "project": "Test title", "version": "999", "author": "Test author", "today": "FIXED DATE FOR TESTS", } def test_rst2pdf_with_config( self, tmpdir, dataset_df_path, data_dir, TestWorkflow, report_config ): root = tmpdir / "rst2pdf" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), specifications_only=True, report_config=report_config, ) ], local_scheduler=True, ) assert (root / "TestWorkflow_specifications.pdf").exists() assert pdfdiff( root / "TestWorkflow_specifications.pdf", data_dir / "test_report_before_run" / "report_rst2pdf_with_config.pdf", ) @pytest.mark.skipif(SKIP_IF_NO_LATEXMK, reason=REASON_NO_LATEXMK) def test_latexpdf_with_config( self, tmpdir, dataset_df_path, data_dir, TestWorkflow, report_config ): root = tmpdir / "latexpdf" assert luigi.build( [ TestWorkflow( dataset_df=dataset_df_path, result_path=str(root), report_type="latexpdf", specifications_only=True, report_config=report_config, ) ], local_scheduler=True, ) assert (root / "TestWorkflow_specifications.pdf").exists() assert pdfdiff( root / "TestWorkflow_specifications.pdf", data_dir / "test_report_before_run" / "report_latexpdf_with_config.pdf", ) def test_nested_workflows( self, tmpdir, dataset_df_path, data_dir, TestNestedWorkflow, report_config ): root = tmpdir / "rst2pdf_nested" assert luigi.build( [ TestNestedWorkflow( dataset_df=dataset_df_path, result_path=str(root), specifications_only=True, report_config=report_config, ) ], local_scheduler=True, ) assert (root / "TestNestedWorkflow_specifications.pdf").exists() assert pdfdiff( root / "TestNestedWorkflow_specifications.pdf", data_dir / "test_report_before_run" / "report_rst2pdf_nested.pdf", threshold=25, ) class TestSkippableMixin: """Test the data_validation_framework.task.SkippableMixin class.""" def test_fail_parent_type(self): err_msg = ( "The SkippableMixin can only be associated with children of ElementValidationTask" " or SetValidationTask" ) class TestTask1(task.SkippableMixin(), luigi.Task): pass with pytest.raises( TypeError, match=err_msg, ): TestTask1() class TestTask2(task.SkippableMixin(), task.ValidationWorkflow): pass with pytest.raises( TypeError, match=err_msg, ): TestTask2() def test_skip_element_task(self, dataset_df_path, tmpdir): class TestSkippableTask(task.SkippableMixin(), task.ElementValidationTask): @staticmethod # pylint: disable=arguments-differ def validation_function(row, output_path, *args, **kwargs): if row["a"] <= 1: return result.ValidationResult(is_valid=True) if row["a"] <= 2: return result.ValidationResult(is_valid=False, comment="bad value") raise ValueError(f"Incorrect value {row['a']}") # Test with no given skip value (should be False by default) assert luigi.build( [ TestSkippableTask( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_default") ) ], local_scheduler=True, ) report_data = pd.read_csv(tmpdir / "out_default" / "TestSkippableTask" / "report.csv") assert (report_data["is_valid"] == [True, False]).all() assert (report_data["comment"].isnull() == [True, False]).all() assert report_data.loc[1, "comment"] == "bad value" assert report_data["exception"].isnull().all() # Test with no given skip value (should be False by default) assert luigi.build( [ TestSkippableTask( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_no_skip"), skip=False ) ], local_scheduler=True, ) report_data = pd.read_csv(tmpdir / "out_no_skip" / "TestSkippableTask" / "report.csv") assert (report_data["is_valid"] == [True, False]).all() assert (report_data["comment"].isnull() == [True, False]).all() assert report_data.loc[1, "comment"] == "bad value" assert report_data["exception"].isnull().all() # Test with no given skip value (should be False by default) assert luigi.build( [ TestSkippableTask( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_skip"), skip=True ) ], local_scheduler=True, ) report_data = pd.read_csv(tmpdir / "out_skip" / "TestSkippableTask" / "report.csv") assert ( report_data["is_valid"] == True # noqa ; pylint: disable=singleton-comparison ).all() assert (report_data["comment"] == "Skipped by user.").all() assert report_data["exception"].isnull().all() def test_skip_set_task(self, dataset_df_path, tmpdir): class TestSkippableTask(task.SkippableMixin(), task.SetValidationTask): @staticmethod def validation_function(df, output_path, *args, **kwargs): # pylint: disable=no-member df["a"] *= 10 df.loc[1, "is_valid"] = False df.loc[1, "ret_code"] = 1 df[["a", "b"]].to_csv(output_path / "test.csv") # Test with no given skip value (should be False by default) assert luigi.build( [ TestSkippableTask( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_default") ) ], local_scheduler=True, ) res = pd.read_csv(tmpdir / "out_default" / "TestSkippableTask" / "data" / "test.csv") expected = pd.read_csv(tmpdir / "dataset.csv") expected["a"] *= 10 assert res.equals(expected) report_data = pd.read_csv(tmpdir / "out_default" / "TestSkippableTask" / "report.csv") assert (report_data["is_valid"] == [True, False]).all() assert report_data["comment"].isnull().all() assert report_data["exception"].isnull().all() # Test with skip = False assert luigi.build( [ TestSkippableTask( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_no_skip"), skip=False ) ], local_scheduler=True, ) res = pd.read_csv(tmpdir / "out_no_skip" / "TestSkippableTask" / "data" / "test.csv") expected = pd.read_csv(tmpdir / "dataset.csv") expected["a"] *= 10 assert res.equals(expected) report_data = pd.read_csv(tmpdir / "out_no_skip" / "TestSkippableTask" / "report.csv") assert (report_data["is_valid"] == [True, False]).all() assert report_data["comment"].isnull().all() assert report_data["exception"].isnull().all() # Test with skip = True assert luigi.build( [ TestSkippableTask( dataset_df=dataset_df_path, result_path=str(tmpdir / "out_skip"), skip=True ) ], local_scheduler=True, ) assert not (tmpdir / "out_skip" / "TestSkippableTask" / "data" / "test.csv").exists() report_data = pd.read_csv(tmpdir / "out_skip" / "TestSkippableTask" / "report.csv") assert ( report_data["is_valid"] == True # noqa ; pylint: disable=singleton-comparison ).all() assert (report_data["comment"] == "Skipped by user.").all() assert report_data["exception"].isnull().all()
37.81401
100
0.527308
9,515
93,930
4.998003
0.051918
0.036904
0.031437
0.022332
0.787892
0.747939
0.700753
0.665784
0.630562
0.612289
0
0.010294
0.361908
93,930
2,483
101
37.829239
0.783152
0.061152
0
0.565369
0
0.021457
0.142669
0.053481
0
0
0
0
0.141717
1
0.076846
false
0.021956
0.009481
0.017964
0.147206
0
0
0
0
null
0
0
0
0
1
1
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
1c27aaba87ff8f916e98642ac68d293ba3145aec
1,577
py
Python
install-appd-machine-agent.py
nvkk-devops/python-automation-scripts
8930dde979124fa8b5812e60243a25952a2c8013
[ "MIT" ]
null
null
null
install-appd-machine-agent.py
nvkk-devops/python-automation-scripts
8930dde979124fa8b5812e60243a25952a2c8013
[ "MIT" ]
null
null
null
install-appd-machine-agent.py
nvkk-devops/python-automation-scripts
8930dde979124fa8b5812e60243a25952a2c8013
[ "MIT" ]
null
null
null
import winrm import os print('\n********************************\n') print(os.environ['winrm_endpoint']) print(os.environ['domain_username']) print('\n********************************\n') s = winrm.Session(os.environ['winrm_endpoint'], auth=(os.environ['domain_username'], os.environ['domain_password']), transport='ntlm') ps_script = """ $machine_agent_url='http://xyz.com/machine-agent/windows/' $machine_agent_file_name='machineagent-bundle-64bit.zip' $machine_agent_dest_root='F:/test/' #### Download machine-agent $machine_agent_final_url = $machine_agent_url + $machine_agent_file_name $machine_agent_dest_path = $machine_agent_dest_root + $machine_agent_file_name $WebClient = New-Object System.Net.WebClient $WebClient.DownloadFile($machine_agent_final_url, $machine_agent_dest_path) #### Extract machine-agent $destination = $machine_agent_dest_root + 'machineagent-bundle-64bit-windows/' if (!$destination) { $destination = [string](Resolve-Path $machine_agent_dest_path) $destination = $destination.Substring(0, $destination.LastIndexOf('.')) mkdir $destination | Out-Null } unzip.exe -o -qq $machine_agent_dest_path -d $destination Remove-Item $machine_agent_dest_path #### Re-install machine-agent, Invoke-Expression:notworking $command_uninstall = $destination + 'UninstallService.vbs' start cscript.exe $command_uninstall $command_install = $destination + 'InstallService.vbs' start cscript.exe $command_install """ r = s.run_ps(ps_script) print(r.status_code) print(r.std_out) print(r.std_err) print('\n********************************\n')
35.044444
134
0.72733
201
1,577
5.41791
0.393035
0.209366
0.117539
0.091827
0.104683
0.05877
0
0
0
0
0
0.003432
0.076094
1,577
45
135
35.044444
0.743995
0
0
0.083333
0
0
0.818124
0.413181
0
0
0
0
0
1
0
false
0.027778
0.055556
0
0.055556
0.222222
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
1c2969c81f21d96b7a740e516fdd647185eba6a4
8,547
py
Python
tests/python/test_mpm88.py
mzmzm/taichi
39129820a922fdd936728d6feb7944ae208345a5
[ "MIT" ]
11,699
2020-01-09T03:02:46.000Z
2022-03-31T20:59:08.000Z
tests/python/test_mpm88.py
mzmzm/taichi
39129820a922fdd936728d6feb7944ae208345a5
[ "MIT" ]
3,589
2020-01-09T03:18:25.000Z
2022-03-31T19:06:42.000Z
tests/python/test_mpm88.py
mzmzm/taichi
39129820a922fdd936728d6feb7944ae208345a5
[ "MIT" ]
1,391
2020-01-09T03:02:54.000Z
2022-03-31T08:44:29.000Z
import os import pytest import taichi as ti from taichi import approx def run_mpm88_test(): dim = 2 N = 64 n_particles = N * N n_grid = 128 dx = 1 / n_grid inv_dx = 1 / dx dt = 2.0e-4 p_vol = (dx * 0.5)**2 p_rho = 1 p_mass = p_vol * p_rho E = 400 x = ti.Vector.field(dim, dtype=ti.f32, shape=n_particles) v = ti.Vector.field(dim, dtype=ti.f32, shape=n_particles) C = ti.Matrix.field(dim, dim, dtype=ti.f32, shape=n_particles) J = ti.field(dtype=ti.f32, shape=n_particles) grid_v = ti.Vector.field(dim, dtype=ti.f32, shape=(n_grid, n_grid)) grid_m = ti.field(dtype=ti.f32, shape=(n_grid, n_grid)) @ti.kernel def substep(): for p in x: base = (x[p] * inv_dx - 0.5).cast(int) fx = x[p] * inv_dx - base.cast(float) w = [0.5 * (1.5 - fx)**2, 0.75 - (fx - 1)**2, 0.5 * (fx - 0.5)**2] stress = -dt * p_vol * (J[p] - 1) * 4 * inv_dx * inv_dx * E affine = ti.Matrix([[stress, 0], [0, stress]]) + p_mass * C[p] for i in ti.static(range(3)): for j in ti.static(range(3)): offset = ti.Vector([i, j]) dpos = (offset.cast(float) - fx) * dx weight = w[i][0] * w[j][1] grid_v[base + offset].atomic_add( weight * (p_mass * v[p] + affine @ dpos)) grid_m[base + offset].atomic_add(weight * p_mass) for i, j in grid_m: if grid_m[i, j] > 0: bound = 3 inv_m = 1 / grid_m[i, j] grid_v[i, j] = inv_m * grid_v[i, j] grid_v[i, j][1] -= dt * 9.8 if i < bound and grid_v[i, j][0] < 0: grid_v[i, j][0] = 0 if i > n_grid - bound and grid_v[i, j][0] > 0: grid_v[i, j][0] = 0 if j < bound and grid_v[i, j][1] < 0: grid_v[i, j][1] = 0 if j > n_grid - bound and grid_v[i, j][1] > 0: grid_v[i, j][1] = 0 for p in x: base = (x[p] * inv_dx - 0.5).cast(int) fx = x[p] * inv_dx - base.cast(float) w = [ 0.5 * (1.5 - fx)**2, 0.75 - (fx - 1.0)**2, 0.5 * (fx - 0.5)**2 ] new_v = ti.Vector.zero(ti.f32, 2) new_C = ti.Matrix.zero(ti.f32, 2, 2) for i in ti.static(range(3)): for j in ti.static(range(3)): dpos = ti.Vector([i, j]).cast(float) - fx g_v = grid_v[base + ti.Vector([i, j])] weight = w[i][0] * w[j][1] new_v += weight * g_v new_C += 4 * weight * g_v.outer_product(dpos) * inv_dx v[p] = new_v x[p] += dt * v[p] J[p] *= 1 + dt * new_C.trace() C[p] = new_C # gui = ti._lib.core.GUI("MPM88", ti.core_veci(512, 512)) # canvas = gui.get_canvas() for i in range(n_particles): x[i] = [i % N / N * 0.4 + 0.2, i / N / N * 0.4 + 0.05] v[i] = [0, -3] J[i] = 1 for frame in range(10): for s in range(50): grid_v.fill([0, 0]) grid_m.fill(0) substep() pos = x.to_numpy() pos[:, 1] *= 2 regression = [ 0.31722742, 0.15826741, 0.10224003, 0.07810827, ] for i in range(4): assert (pos**(i + 1)).mean() == approx(regression[i], rel=1e-2) @ti.test() def test_mpm88(): run_mpm88_test() def _is_appveyor(): # AppVeyor adds `APPVEYOR=True` ('true' on Ubuntu) # https://www.appveyor.com/docs/environment-variables/ return os.getenv('APPVEYOR', '').lower() == 'true' #TODO: Remove exclude of ti.metal @pytest.mark.skipif(_is_appveyor(), reason='Stuck on Appveyor.') @ti.test(require=ti.extension.async_mode, exclude=[ti.metal], async_mode=True) def test_mpm88_async(): # It seems that all async tests on Appveyor run super slow. For example, # on Appveyor, 10+ tests have passed during the execution of # test_fuse_dense_x2y2z. Maybe thread synchronizations are expensive? run_mpm88_test() @ti.test(arch=[ti.cpu, ti.cuda, ti.opengl]) def test_mpm88_numpy_and_ndarray(): import numpy as np dim = 2 N = 64 n_particles = N * N n_grid = 128 dx = 1 / n_grid inv_dx = 1 / dx dt = 2.0e-4 p_vol = (dx * 0.5)**2 p_rho = 1 p_mass = p_vol * p_rho E = 400 @ti.kernel def substep(x: ti.any_arr(element_dim=1), v: ti.any_arr(element_dim=1), C: ti.any_arr(element_dim=2), J: ti.any_arr(), grid_v: ti.any_arr(element_dim=1), grid_m: ti.any_arr()): for p in x: base = (x[p] * inv_dx - 0.5).cast(int) fx = x[p] * inv_dx - base.cast(float) w = [0.5 * (1.5 - fx)**2, 0.75 - (fx - 1)**2, 0.5 * (fx - 0.5)**2] stress = -dt * p_vol * (J[p] - 1) * 4 * inv_dx * inv_dx * E affine = ti.Matrix([[stress, 0], [0, stress]]) + p_mass * C[p] for i in ti.static(range(3)): for j in ti.static(range(3)): offset = ti.Vector([i, j]) dpos = (offset.cast(float) - fx) * dx weight = w[i][0] * w[j][1] grid_v[base + offset].atomic_add( weight * (p_mass * v[p] + affine @ dpos)) grid_m[base + offset].atomic_add(weight * p_mass) for i, j in grid_m: if grid_m[i, j] > 0: bound = 3 inv_m = 1 / grid_m[i, j] grid_v[i, j] = inv_m * grid_v[i, j] grid_v[i, j][1] -= dt * 9.8 if i < bound and grid_v[i, j][0] < 0: grid_v[i, j][0] = 0 if i > n_grid - bound and grid_v[i, j][0] > 0: grid_v[i, j][0] = 0 if j < bound and grid_v[i, j][1] < 0: grid_v[i, j][1] = 0 if j > n_grid - bound and grid_v[i, j][1] > 0: grid_v[i, j][1] = 0 for p in x: base = (x[p] * inv_dx - 0.5).cast(int) fx = x[p] * inv_dx - base.cast(float) w = [ 0.5 * (1.5 - fx)**2, 0.75 - (fx - 1.0)**2, 0.5 * (fx - 0.5)**2 ] new_v = ti.Vector.zero(ti.f32, 2) new_C = ti.Matrix.zero(ti.f32, 2, 2) for i in ti.static(range(3)): for j in ti.static(range(3)): dpos = ti.Vector([i, j]).cast(float) - fx g_v = grid_v[base + ti.Vector([i, j])] weight = w[i][0] * w[j][1] new_v += weight * g_v new_C += 4 * weight * g_v.outer_product(dpos) * inv_dx v[p] = new_v x[p] += dt * v[p] J[p] *= 1 + dt * new_C.trace() C[p] = new_C def run_test(x, v, C, J, grid_v, grid_m): for i in range(n_particles): x[i] = [i % N / N * 0.4 + 0.2, i / N / N * 0.4 + 0.05] v[i] = [0, -3] J[i] = 1 for frame in range(10): for s in range(50): grid_v.fill(0) grid_m.fill(0) substep(x, v, C, J, grid_v, grid_m) pos = x if isinstance(x, np.ndarray) else x.to_numpy() pos[:, 1] *= 2 regression = [ 0.31722742, 0.15826741, 0.10224003, 0.07810827, ] for i in range(4): assert (pos**(i + 1)).mean() == approx(regression[i], rel=1e-2) def test_numpy(): x = np.zeros((n_particles, dim), dtype=np.float32) v = np.zeros((n_particles, dim), dtype=np.float32) C = np.zeros((n_particles, dim, dim), dtype=np.float32) J = np.zeros(n_particles, dtype=np.float32) grid_v = np.zeros((n_grid, n_grid, dim), dtype=np.float32) grid_m = np.zeros((n_grid, n_grid), dtype=np.float32) run_test(x, v, C, J, grid_v, grid_m) def test_ndarray(): x = ti.Vector.ndarray(dim, ti.f32, n_particles) v = ti.Vector.ndarray(dim, ti.f32, n_particles) C = ti.Matrix.ndarray(dim, dim, ti.f32, n_particles) J = ti.ndarray(ti.f32, n_particles) grid_v = ti.Vector.ndarray(dim, ti.f32, (n_grid, n_grid)) grid_m = ti.ndarray(ti.f32, (n_grid, n_grid)) run_test(x, v, C, J, grid_v, grid_m) test_numpy() test_ndarray()
35.46473
78
0.468234
1,386
8,547
2.744589
0.118326
0.047319
0.0347
0.040484
0.754206
0.729232
0.695058
0.663775
0.609096
0.609096
0
0.070639
0.37557
8,547
240
79
35.6125
0.642121
0.048321
0
0.742574
0
0
0.003692
0
0
0
0
0.004167
0.009901
1
0.049505
false
0
0.024752
0.00495
0.079208
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
1c2a807e52645ea45fee8b1da10b4b14d641fdeb
73
py
Python
openpmd_viewer/addons/pic/__init__.py
pordyna/openPMD-viewer
f7b792be58d5dca1af5b36d9875b3d7768a3617d
[ "BSD-3-Clause-LBNL" ]
51
2015-10-08T21:07:28.000Z
2022-01-31T06:16:32.000Z
openpmd_viewer/addons/pic/__init__.py
pordyna/openPMD-viewer
f7b792be58d5dca1af5b36d9875b3d7768a3617d
[ "BSD-3-Clause-LBNL" ]
239
2015-10-09T18:11:00.000Z
2022-03-31T22:45:14.000Z
openpmd_viewer/addons/pic/__init__.py
pordyna/openPMD-viewer
f7b792be58d5dca1af5b36d9875b3d7768a3617d
[ "BSD-3-Clause-LBNL" ]
40
2015-10-08T17:11:36.000Z
2022-03-30T21:21:09.000Z
from .lpa_diagnostics import LpaDiagnostics __all__ = ['LpaDiagnostics']
24.333333
43
0.821918
7
73
7.857143
0.857143
0
0
0
0
0
0
0
0
0
0
0
0.09589
73
2
44
36.5
0.833333
0
0
0
0
0
0.191781
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
1c4177cb554a2f15962cc028608078160d73c8e5
622
py
Python
tests/test_fixtures.py
adammichaelwood/omk_core
9f3a845aeadad0b1de91d7f20da3ae6b686a07d0
[ "MIT" ]
null
null
null
tests/test_fixtures.py
adammichaelwood/omk_core
9f3a845aeadad0b1de91d7f20da3ae6b686a07d0
[ "MIT" ]
3
2019-01-28T16:50:27.000Z
2019-02-20T01:55:19.000Z
tests/test_fixtures.py
adammichaelwood/omk_core
9f3a845aeadad0b1de91d7f20da3ae6b686a07d0
[ "MIT" ]
1
2018-06-04T10:32:05.000Z
2018-06-04T10:32:05.000Z
import pytest import omk_core as omk @pytest.fixture def tonal_tuples(): MS = [ (0, 0), (1, 2), (2, 4), (3, 5), (4, 7), (5, 9), (6,11) ] return [(x[0],(x[1]+m)%12) for m in [0,1,2,-1,-2] for x in MS] @pytest.fixture def tonal_vectors(tonal_tuples): return [omk.TonalVector(x) for x in tonal_tuples] @pytest.fixture def tonal_oct_tuples(tonal_tuples): return [(x[0], x[1], y) for y in [0,1,2,-1,-2] for x in tonal_tuples] @pytest.fixture def tonal_oct_vectors(tonal_oct_tuples): return [omk.TonalVector(x) for x in tonal_oct_tuples]
20.064516
73
0.585209
108
622
3.231481
0.277778
0.157593
0.183381
0.240688
0.535817
0.47851
0.47851
0.47851
0.47851
0.234957
0
0.066955
0.255627
622
30
74
20.733333
0.686825
0
0
0.173913
0
0
0
0
0
0
0
0
0
1
0.173913
false
0
0.086957
0.130435
0.434783
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
0
0
0
3
1c51dcf4a83bfb64408be3ad0db57c870bed455e
11,818
py
Python
nova/tests/unit/test_test.py
bopopescu/nova-token
ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2
[ "Apache-2.0" ]
null
null
null
nova/tests/unit/test_test.py
bopopescu/nova-token
ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2
[ "Apache-2.0" ]
null
null
null
nova/tests/unit/test_test.py
bopopescu/nova-token
ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2
[ "Apache-2.0" ]
2
2017-07-20T17:31:34.000Z
2020-07-24T02:42:19.000Z
begin_unit comment|'# Copyright 2010 United States Government as represented by the' nl|'\n' comment|'# Administrator of the National Aeronautics and Space Administration.' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#' nl|'\n' comment|'# http://www.apache.org/licenses/LICENSE-2.0' nl|'\n' comment|'#' nl|'\n' comment|'# Unless required by applicable law or agreed to in writing, software' nl|'\n' comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT' nl|'\n' comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the' nl|'\n' comment|'# License for the specific language governing permissions and limitations' nl|'\n' comment|'# under the License.' nl|'\n' nl|'\n' string|'"""Tests for the testing base code."""' newline|'\n' nl|'\n' name|'from' name|'oslo_log' name|'import' name|'log' name|'as' name|'logging' newline|'\n' name|'import' name|'oslo_messaging' name|'as' name|'messaging' newline|'\n' name|'import' name|'six' newline|'\n' nl|'\n' name|'import' name|'nova' op|'.' name|'conf' newline|'\n' name|'from' name|'nova' name|'import' name|'rpc' newline|'\n' name|'from' name|'nova' name|'import' name|'test' newline|'\n' name|'from' name|'nova' op|'.' name|'tests' name|'import' name|'fixtures' newline|'\n' nl|'\n' DECL|variable|LOG name|'LOG' op|'=' name|'logging' op|'.' name|'getLogger' op|'(' name|'__name__' op|')' newline|'\n' nl|'\n' DECL|variable|CONF name|'CONF' op|'=' name|'nova' op|'.' name|'conf' op|'.' name|'CONF' newline|'\n' nl|'\n' nl|'\n' DECL|class|IsolationTestCase name|'class' name|'IsolationTestCase' op|'(' name|'test' op|'.' name|'TestCase' op|')' op|':' newline|'\n' indent|' ' string|'"""Ensure that things are cleaned up after failed tests.\n\n These tests don\'t really do much here, but if isolation fails a bunch\n of other tests should fail.\n\n """' newline|'\n' DECL|member|test_service_isolation name|'def' name|'test_service_isolation' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'flags' op|'(' name|'use_local' op|'=' name|'True' op|',' name|'group' op|'=' string|"'conductor'" op|')' newline|'\n' name|'self' op|'.' name|'useFixture' op|'(' name|'fixtures' op|'.' name|'ServiceFixture' op|'(' string|"'compute'" op|')' op|')' newline|'\n' nl|'\n' DECL|member|test_rpc_consumer_isolation dedent|'' name|'def' name|'test_rpc_consumer_isolation' op|'(' name|'self' op|')' op|':' newline|'\n' DECL|class|NeverCalled indent|' ' name|'class' name|'NeverCalled' op|'(' name|'object' op|')' op|':' newline|'\n' nl|'\n' DECL|member|__getattribute__ indent|' ' name|'def' name|'__getattribute__' op|'(' op|'*' name|'args' op|')' op|':' newline|'\n' indent|' ' name|'assert' name|'False' op|',' string|'"I should never get called."' newline|'\n' nl|'\n' dedent|'' dedent|'' name|'server' op|'=' name|'rpc' op|'.' name|'get_server' op|'(' name|'messaging' op|'.' name|'Target' op|'(' name|'topic' op|'=' string|"'compute'" op|',' nl|'\n' name|'server' op|'=' name|'CONF' op|'.' name|'host' op|')' op|',' nl|'\n' name|'endpoints' op|'=' op|'[' name|'NeverCalled' op|'(' op|')' op|']' op|')' newline|'\n' name|'server' op|'.' name|'start' op|'(' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|JsonTestCase dedent|'' dedent|'' name|'class' name|'JsonTestCase' op|'(' name|'test' op|'.' name|'NoDBTestCase' op|')' op|':' newline|'\n' DECL|member|test_json_equal indent|' ' name|'def' name|'test_json_equal' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'expected' op|'=' op|'{' nl|'\n' string|'"employees"' op|':' op|'[' nl|'\n' op|'{' string|'"firstName"' op|':' string|'"Anna"' op|',' string|'"lastName"' op|':' string|'"Smith"' op|'}' op|',' nl|'\n' op|'{' string|'"firstName"' op|':' string|'"John"' op|',' string|'"lastName"' op|':' string|'"Doe"' op|'}' op|',' nl|'\n' op|'{' string|'"firstName"' op|':' string|'"Peter"' op|',' string|'"lastName"' op|':' string|'"Jones"' op|'}' nl|'\n' op|']' op|',' nl|'\n' string|'"locations"' op|':' name|'set' op|'(' op|'[' string|"'Boston'" op|',' string|"'Mumbai'" op|',' string|"'Beijing'" op|',' string|"'Perth'" op|']' op|')' nl|'\n' op|'}' newline|'\n' name|'observed' op|'=' string|'"""{\n "employees": [\n {\n "lastName": "Doe",\n "firstName": "John"\n },\n {\n "lastName": "Smith",\n "firstName": "Anna"\n },\n {\n "lastName": "Jones",\n "firstName": "Peter"\n }\n ],\n "locations": [\n "Perth",\n "Boston",\n "Mumbai",\n "Beijing"\n ]\n}"""' newline|'\n' name|'self' op|'.' name|'assertJsonEqual' op|'(' name|'expected' op|',' name|'observed' op|')' newline|'\n' nl|'\n' DECL|member|test_json_equal_fail_on_length dedent|'' name|'def' name|'test_json_equal_fail_on_length' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'expected' op|'=' op|'{' nl|'\n' string|"'top'" op|':' op|'{' nl|'\n' string|"'l1'" op|':' op|'{' nl|'\n' string|"'l2'" op|':' op|'[' string|"'a'" op|',' string|"'b'" op|',' string|"'c'" op|']' nl|'\n' op|'}' nl|'\n' op|'}' nl|'\n' op|'}' newline|'\n' name|'observed' op|'=' op|'{' nl|'\n' string|"'top'" op|':' op|'{' nl|'\n' string|"'l1'" op|':' op|'{' nl|'\n' string|"'l2'" op|':' op|'[' string|"'c'" op|',' string|"'a'" op|',' string|"'b'" op|',' string|"'d'" op|']' nl|'\n' op|'}' nl|'\n' op|'}' nl|'\n' op|'}' newline|'\n' name|'try' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'assertJsonEqual' op|'(' name|'expected' op|',' name|'observed' op|')' newline|'\n' dedent|'' name|'except' name|'Exception' name|'as' name|'e' op|':' newline|'\n' comment|'# error reported is going to be a cryptic length failure' nl|'\n' comment|'# on the level2 structure.' nl|'\n' indent|' ' name|'self' op|'.' name|'assertEqual' op|'(' name|'e' op|'.' name|'mismatch' op|'.' name|'describe' op|'(' op|')' op|',' string|'"3 != 4"' op|')' newline|'\n' name|'self' op|'.' name|'assertIn' op|'(' nl|'\n' string|'"Matchee: {\'top\': {\'l1\': {\'l2\': [\'c\', \'a\', \'b\', \'d\']}}}"' op|',' nl|'\n' name|'six' op|'.' name|'text_type' op|'(' name|'e' op|')' op|')' newline|'\n' name|'self' op|'.' name|'assertIn' op|'(' nl|'\n' string|'"Matcher: {\'top\': {\'l1\': {\'l2\': [\'a\', \'b\', \'c\']}}}"' op|',' nl|'\n' name|'six' op|'.' name|'text_type' op|'(' name|'e' op|')' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'fail' op|'(' string|'"This should have raised a mismatch exception"' op|')' newline|'\n' nl|'\n' DECL|member|test_json_equal_fail_on_inner dedent|'' dedent|'' name|'def' name|'test_json_equal_fail_on_inner' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'expected' op|'=' op|'{' nl|'\n' string|"'top'" op|':' op|'{' nl|'\n' string|"'l1'" op|':' op|'{' nl|'\n' string|"'l2'" op|':' op|'[' string|"'a'" op|',' string|"'b'" op|',' string|"'c'" op|']' nl|'\n' op|'}' nl|'\n' op|'}' nl|'\n' op|'}' newline|'\n' name|'observed' op|'=' op|'{' nl|'\n' string|"'top'" op|':' op|'{' nl|'\n' string|"'l1'" op|':' op|'{' nl|'\n' string|"'l2'" op|':' op|'[' string|"'c'" op|',' string|"'a'" op|',' string|"'d'" op|']' nl|'\n' op|'}' nl|'\n' op|'}' nl|'\n' op|'}' newline|'\n' name|'try' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'assertJsonEqual' op|'(' name|'expected' op|',' name|'observed' op|')' newline|'\n' dedent|'' name|'except' name|'Exception' name|'as' name|'e' op|':' newline|'\n' comment|'# error reported is going to be a cryptic length failure' nl|'\n' comment|'# on the level2 structure.' nl|'\n' indent|' ' name|'self' op|'.' name|'assertEqual' op|'(' name|'e' op|'.' name|'mismatch' op|'.' name|'describe' op|'(' op|')' op|',' string|'"\'b\' != \'c\'"' op|')' newline|'\n' name|'self' op|'.' name|'assertIn' op|'(' nl|'\n' string|'"Matchee: {\'top\': {\'l1\': {\'l2\': [\'c\', \'a\', \'d\']}}}"' op|',' nl|'\n' name|'six' op|'.' name|'text_type' op|'(' name|'e' op|')' op|')' newline|'\n' name|'self' op|'.' name|'assertIn' op|'(' nl|'\n' string|'"Matcher: {\'top\': {\'l1\': {\'l2\': [\'a\', \'b\', \'c\']}}}"' op|',' nl|'\n' name|'six' op|'.' name|'text_type' op|'(' name|'e' op|')' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'fail' op|'(' string|'"This should have raised a mismatch exception"' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|BadLogTestCase dedent|'' dedent|'' dedent|'' name|'class' name|'BadLogTestCase' op|'(' name|'test' op|'.' name|'NoDBTestCase' op|')' op|':' newline|'\n' indent|' ' string|'"""Make sure a mis-formatted debug log will get caught."""' newline|'\n' nl|'\n' DECL|member|test_bad_debug_log name|'def' name|'test_bad_debug_log' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'assertRaises' op|'(' name|'KeyError' op|',' nl|'\n' name|'LOG' op|'.' name|'debug' op|',' string|'"this is a misformated %(log)s"' op|',' op|'{' string|"'nothing'" op|':' string|"'nothing'" op|'}' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|MatchTypeTestCase dedent|'' dedent|'' name|'class' name|'MatchTypeTestCase' op|'(' name|'test' op|'.' name|'NoDBTestCase' op|')' op|':' newline|'\n' nl|'\n' DECL|member|test_match_type_simple indent|' ' name|'def' name|'test_match_type_simple' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'matcher' op|'=' name|'test' op|'.' name|'MatchType' op|'(' name|'dict' op|')' newline|'\n' nl|'\n' name|'self' op|'.' name|'assertEqual' op|'(' name|'matcher' op|',' op|'{' op|'}' op|')' newline|'\n' name|'self' op|'.' name|'assertEqual' op|'(' name|'matcher' op|',' op|'{' string|'"hello"' op|':' string|'"world"' op|'}' op|')' newline|'\n' name|'self' op|'.' name|'assertEqual' op|'(' name|'matcher' op|',' op|'{' string|'"hello"' op|':' op|'[' string|'"world"' op|']' op|'}' op|')' newline|'\n' name|'self' op|'.' name|'assertNotEqual' op|'(' name|'matcher' op|',' op|'[' op|']' op|')' newline|'\n' name|'self' op|'.' name|'assertNotEqual' op|'(' name|'matcher' op|',' op|'[' op|'{' string|'"hello"' op|':' string|'"world"' op|'}' op|']' op|')' newline|'\n' name|'self' op|'.' name|'assertNotEqual' op|'(' name|'matcher' op|',' number|'123' op|')' newline|'\n' name|'self' op|'.' name|'assertNotEqual' op|'(' name|'matcher' op|',' string|'"foo"' op|')' newline|'\n' nl|'\n' DECL|member|test_match_type_object dedent|'' name|'def' name|'test_match_type_object' op|'(' name|'self' op|')' op|':' newline|'\n' DECL|class|Hello indent|' ' name|'class' name|'Hello' op|'(' name|'object' op|')' op|':' newline|'\n' indent|' ' name|'pass' newline|'\n' nl|'\n' DECL|class|World dedent|'' name|'class' name|'World' op|'(' name|'object' op|')' op|':' newline|'\n' indent|' ' name|'pass' newline|'\n' nl|'\n' dedent|'' name|'matcher' op|'=' name|'test' op|'.' name|'MatchType' op|'(' name|'Hello' op|')' newline|'\n' nl|'\n' name|'self' op|'.' name|'assertEqual' op|'(' name|'matcher' op|',' name|'Hello' op|'(' op|')' op|')' newline|'\n' name|'self' op|'.' name|'assertNotEqual' op|'(' name|'matcher' op|',' name|'World' op|'(' op|')' op|')' newline|'\n' name|'self' op|'.' name|'assertNotEqual' op|'(' name|'matcher' op|',' number|'123' op|')' newline|'\n' name|'self' op|'.' name|'assertNotEqual' op|'(' name|'matcher' op|',' string|'"foo"' op|')' newline|'\n' dedent|'' dedent|'' endmarker|'' end_unit
13.460137
417
0.569386
1,698
11,818
3.919317
0.141343
0.098272
0.08565
0.055898
0.669572
0.603757
0.556424
0.544252
0.534185
0.470173
0
0.003299
0.128025
11,818
877
418
13.475485
0.642504
0
0
0.889396
0
0.004561
0.721526
0.051955
0
0
0
0
0.025086
0
null
null
0.002281
0.007982
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
3
1c5654083154bfc28d524ccd620751c609962eb0
184
py
Python
worker.py
marcolussetti/netinfo
6fcab55eaeabfd005a9192ace0c2b04122ab3df4
[ "MIT" ]
67
2018-12-26T11:10:50.000Z
2022-03-03T09:07:10.000Z
worker.py
marcolussetti/netinfo
6fcab55eaeabfd005a9192ace0c2b04122ab3df4
[ "MIT" ]
4
2019-01-02T20:01:59.000Z
2020-01-27T14:43:21.000Z
worker.py
marcolussetti/netinfo
6fcab55eaeabfd005a9192ace0c2b04122ab3df4
[ "MIT" ]
16
2018-12-26T05:01:04.000Z
2022-01-25T12:13:18.000Z
"""Run the Celery jobs.""" import os from app import celery, create_app import app.tasks flask_app = create_app(os.getenv('FLASK_CONFIG') or 'default') flask_app.app_context().push()
23
62
0.755435
30
184
4.433333
0.566667
0.135338
0
0
0
0
0
0
0
0
0
0
0.108696
184
7
63
26.285714
0.810976
0.108696
0
0
0
0
0.120253
0
0
0
0
0
0
1
0
false
0
0.6
0
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
1c59642bff0a0e1a6c49c07d62bb1225ba15ca08
2,274
py
Python
deep-rl/lib/python2.7/site-packages/OpenGL/raw/GL/ARB/viewport_array.py
ShujaKhalid/deep-rl
99c6ba6c3095d1bfdab81bd01395ced96bddd611
[ "MIT" ]
210
2016-04-09T14:26:00.000Z
2022-03-25T18:36:19.000Z
deep-rl/lib/python2.7/site-packages/OpenGL/raw/GL/ARB/viewport_array.py
ShujaKhalid/deep-rl
99c6ba6c3095d1bfdab81bd01395ced96bddd611
[ "MIT" ]
72
2016-09-04T09:30:19.000Z
2022-03-27T17:06:53.000Z
deep-rl/lib/python2.7/site-packages/OpenGL/raw/GL/ARB/viewport_array.py
ShujaKhalid/deep-rl
99c6ba6c3095d1bfdab81bd01395ced96bddd611
[ "MIT" ]
64
2016-04-09T14:26:49.000Z
2022-03-21T11:19:47.000Z
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import ctypes _EXTENSION_NAME = 'GL_ARB_viewport_array' def _f( function ): return _p.createFunction( function,_p.PLATFORM.GL,'GL_ARB_viewport_array',error_checker=_errors._error_checker) GL_DEPTH_RANGE=_C('GL_DEPTH_RANGE',0x0B70) GL_FIRST_VERTEX_CONVENTION=_C('GL_FIRST_VERTEX_CONVENTION',0x8E4D) GL_LAST_VERTEX_CONVENTION=_C('GL_LAST_VERTEX_CONVENTION',0x8E4E) GL_LAYER_PROVOKING_VERTEX=_C('GL_LAYER_PROVOKING_VERTEX',0x825E) GL_MAX_VIEWPORTS=_C('GL_MAX_VIEWPORTS',0x825B) GL_PROVOKING_VERTEX=_C('GL_PROVOKING_VERTEX',0x8E4F) GL_SCISSOR_BOX=_C('GL_SCISSOR_BOX',0x0C10) GL_SCISSOR_TEST=_C('GL_SCISSOR_TEST',0x0C11) GL_UNDEFINED_VERTEX=_C('GL_UNDEFINED_VERTEX',0x8260) GL_VIEWPORT=_C('GL_VIEWPORT',0x0BA2) GL_VIEWPORT_BOUNDS_RANGE=_C('GL_VIEWPORT_BOUNDS_RANGE',0x825D) GL_VIEWPORT_INDEX_PROVOKING_VERTEX=_C('GL_VIEWPORT_INDEX_PROVOKING_VERTEX',0x825F) GL_VIEWPORT_SUBPIXEL_BITS=_C('GL_VIEWPORT_SUBPIXEL_BITS',0x825C) @_f @_p.types(None,_cs.GLuint,_cs.GLsizei,arrays.GLdoubleArray) def glDepthRangeArrayv(first,count,v):pass @_f @_p.types(None,_cs.GLuint,_cs.GLdouble,_cs.GLdouble) def glDepthRangeIndexed(index,n,f):pass @_f @_p.types(None,_cs.GLenum,_cs.GLuint,arrays.GLdoubleArray) def glGetDoublei_v(target,index,data):pass @_f @_p.types(None,_cs.GLenum,_cs.GLuint,arrays.GLfloatArray) def glGetFloati_v(target,index,data):pass @_f @_p.types(None,_cs.GLuint,_cs.GLsizei,arrays.GLintArray) def glScissorArrayv(first,count,v):pass @_f @_p.types(None,_cs.GLuint,_cs.GLint,_cs.GLint,_cs.GLsizei,_cs.GLsizei) def glScissorIndexed(index,left,bottom,width,height):pass @_f @_p.types(None,_cs.GLuint,arrays.GLintArray) def glScissorIndexedv(index,v):pass @_f @_p.types(None,_cs.GLuint,_cs.GLsizei,arrays.GLfloatArray) def glViewportArrayv(first,count,v):pass @_f @_p.types(None,_cs.GLuint,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat) def glViewportIndexedf(index,x,y,w,h):pass @_f @_p.types(None,_cs.GLuint,arrays.GLfloatArray) def glViewportIndexedfv(index,v):pass
39.894737
115
0.824538
361
2,274
4.789474
0.296399
0.022556
0.040486
0.063621
0.330827
0.24118
0.221515
0.221515
0.18797
0.167727
0
0.022685
0.050132
2,274
56
116
40.607143
0.777778
0.043975
0
0.192308
1
0
0.142593
0.092755
0
0
0.035994
0
0
1
0.211538
false
0.192308
0.115385
0.019231
0.346154
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
3
1c6fda8d5d7c419e3bc3d82c3f8b74ecd95d5543
258
py
Python
Tasks/Community/ts_scriptExamples/simple.py
nneul/Velocity-assets
9be7cd6f483754871c5a541d0083fbe933dfb456
[ "MIT" ]
4
2019-05-27T23:36:34.000Z
2020-11-12T17:08:04.000Z
Tasks/Community/ts_scriptExamples/simple.py
nneul/Velocity-assets
9be7cd6f483754871c5a541d0083fbe933dfb456
[ "MIT" ]
12
2019-04-17T02:47:25.000Z
2021-04-02T09:15:37.000Z
Tasks/Community/ts_scriptExamples/simple.py
nneul/Velocity-assets
9be7cd6f483754871c5a541d0083fbe933dfb456
[ "MIT" ]
15
2018-04-26T05:18:12.000Z
2021-11-06T04:44:58.000Z
from datetime import datetime import sys, getopt print("[WARNING] This is a warning message") print("[ERROR] This is an error message") print("[INFO] Current time: "+ str(datetime.now())) print("Execution issue verified message") print("Finished: PASSED")
25.8
51
0.74031
36
258
5.305556
0.638889
0.188482
0
0
0
0
0
0
0
0
0
0
0.124031
258
10
52
25.8
0.845133
0
0
0
0
0
0.525097
0
0
0
0
0
0
1
0
true
0.142857
0.285714
0
0.285714
0.714286
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
1
0
0
0
1
0
3