Complicator 0.3.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {complicator-0.3.0/complicator.egg-info → complicator-0.4.0}/PKG-INFO +2 -1
  2. {complicator-0.3.0 → complicator-0.4.0}/complicator/autopp93s4.py +20 -31
  3. {complicator-0.3.0 → complicator-0.4.0}/complicator/complicator_fit.py +105 -11
  4. {complicator-0.3.0 → complicator-0.4.0}/complicator/wrm_ligand_abbrv.csv +13 -13
  5. {complicator-0.3.0 → complicator-0.4.0/complicator.egg-info}/PKG-INFO +2 -1
  6. {complicator-0.3.0 → complicator-0.4.0}/complicator.egg-info/requires.txt +1 -0
  7. {complicator-0.3.0 → complicator-0.4.0}/pyproject.toml +2 -1
  8. {complicator-0.3.0 → complicator-0.4.0}/LICENSE.txt +0 -0
  9. {complicator-0.3.0 → complicator-0.4.0}/MANIFEST.in +0 -0
  10. {complicator-0.3.0 → complicator-0.4.0}/README.md +0 -0
  11. {complicator-0.3.0 → complicator-0.4.0}/complicator/CoCl4_activity.py +0 -0
  12. {complicator-0.3.0 → complicator-0.4.0}/complicator/__init__.py +0 -0
  13. {complicator-0.3.0 → complicator-0.4.0}/complicator/example_input_file.csv +0 -0
  14. {complicator-0.3.0 → complicator-0.4.0}/complicator/wrm_data.csv +0 -0
  15. {complicator-0.3.0 → complicator-0.4.0}/complicator.egg-info/SOURCES.txt +0 -0
  16. {complicator-0.3.0 → complicator-0.4.0}/complicator.egg-info/dependency_links.txt +0 -0
  17. {complicator-0.3.0 → complicator-0.4.0}/complicator.egg-info/not-zip-safe +0 -0
  18. {complicator-0.3.0 → complicator-0.4.0}/complicator.egg-info/top_level.txt +0 -0
  19. {complicator-0.3.0 → complicator-0.4.0}/html/complicator/CoCl4_activity.html +0 -0
  20. {complicator-0.3.0 → complicator-0.4.0}/html/complicator/autopp93s4.html +0 -0
  21. {complicator-0.3.0 → complicator-0.4.0}/html/complicator/complicator_fit.html +0 -0
  22. {complicator-0.3.0 → complicator-0.4.0}/html/complicator/index.html +0 -0
  23. {complicator-0.3.0 → complicator-0.4.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: complicator
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Estimate thermodynamic properties of aqueous metal complexes with monovalent ligands.
5
5
  Author-email: Grayson Boyer <gmboyer@asu.edu>
6
6
  License-Expression: MIT
@@ -13,6 +13,7 @@ License-File: LICENSE.txt
13
13
  Requires-Dist: pandas
14
14
  Requires-Dist: wormutils
15
15
  Requires-Dist: chemparse
16
+ Requires-Dist: scipy
16
17
  Dynamic: license-file
17
18
 
18
19
  # The Complicator
@@ -196,43 +196,32 @@ def __write_output(filename, cation, ligand, nth_complex, G, H, S, CP, V,
196
196
  file_exists = os.path.isfile(filename+'.csv')
197
197
 
198
198
  if file_exists:
199
- with open(filename+'.csv', 'a') as f:
199
+ f_df = pd.read_csv(filename+'.csv')
200
+ all_names = set(thermo_data["name"]).union(set(f_df["name"]))
200
201
 
201
- f_df = pd.read_csv(filename+'.csv')
202
-
203
- # check that a monoligand complex without parentheses isn't already
204
- # in the thermodynamic database. Warn or skip.
205
- keep = True
206
- complex_name_no_parentheses = complex_name.replace("(", "").replace(")", "")
207
-
208
- if complex_name_no_parentheses in list(thermo_data["name"]):
209
- if skip_duplicates:
210
- keep = False
211
- duplicate_list.append([complex_name, complex_name_no_parentheses])
212
-
213
- complex_name_organic_abbv = ""
214
- for name,abbv in ligand_name_abbrv_pairs:
202
+ # check that a monoligand complex without parentheses isn't already
203
+ # in the thermodynamic database or the growing output file. Warn or skip.
204
+ keep = True
205
+ complex_name_no_parentheses = complex_name.replace("(", "").replace(")", "")
215
206
 
216
- if name in complex_name:
217
- # replace "Mg(acetate)+" with "Mg(Ac)+", etc. for the sake of
218
- # checking for duplicate entries
219
- complex_name_organic_abbv = complex_name.replace(name, abbv)
220
-
221
- if complex_name_organic_abbv in list(thermo_data["name"]):
207
+ if complex_name in all_names or complex_name_no_parentheses in all_names:
208
+ if skip_duplicates:
209
+ keep = False
210
+ duplicate_list.append([complex_name, complex_name_no_parentheses])
211
+
212
+ complex_name_organic_abbv = ""
213
+ for name,abbv in ligand_name_abbrv_pairs:
214
+ if name in complex_name:
215
+ complex_name_organic_abbv = complex_name.replace(name, abbv)
216
+
217
+ if complex_name_organic_abbv in all_names:
222
218
  if skip_duplicates:
223
219
  keep = False
224
220
  duplicate_list.append([complex_name, complex_name_organic_abbv])
225
-
226
221
  break
227
-
228
- # if keep and replace and complex_name in list(f_df["name"]):
229
- # cols = list(f_df.columns)
230
- # f_df.iloc[f_df["name"]==complex_name, :] = df
231
-
232
- # f_df.to_csv(filename+'.csv', header=True, index=False)
233
-
234
- if keep: # was elif prior to the block above being commented out
235
- df.to_csv(f, header=False, index=False)
222
+
223
+ if keep:
224
+ df.to_csv(filename+'.csv', mode='a', header=False, index=False, lineterminator='\n')
236
225
 
237
226
  else:
238
227
  df.to_csv(filename+'.csv', index=False)
@@ -1,5 +1,6 @@
1
1
  import pandas as pd
2
2
  import math
3
+ from scipy.optimize import minimize
3
4
  from .autopp93s4 import complicate
4
5
  import plotly.express as px
5
6
  import plotly.graph_objects as go
@@ -10,8 +11,8 @@ interact_manual.opts['manual_name'] = 'Calculate'
10
11
  import pychnosz
11
12
  _ = pychnosz.thermo("WORM", messages=False)
12
13
 
13
- @interact_manual(n_complex=(1, 4, 1), metal="Co+2", ligand="Cl-", logK_data="demo.csv", data_path="WORM", log_beta=(-5, 5, 0.001), S=(-1000, 1000, 0.1), Cp=(-1000, 1000, 0.1), V=(-1000, 1000, 0.1))
14
- def complex_fit(n_complex=4, metal="Co+2", ligand="Cl-", logK_data="demo.csv", data_path="WORM", log_beta=0, S=0, Cp=0, V=0):
14
+ @interact_manual(n_complex=(1, 4, 1), metal="Co+2", ligand="Cl-", logK_data="demo.csv", data_path="WORM", log_beta=(-5, 5, 0.001), S=(-1000, 1000, 0.1), Cp=(-1000, 1000, 0.1), V=(-1000, 1000, 0.1), auto_fit=False)
15
+ def complex_fit(n_complex=4, metal="Co+2", ligand="Cl-", logK_data="demo.csv", data_path="WORM", log_beta=0, S=0, Cp=0, V=0, auto_fit=False):
15
16
 
16
17
  if data_path == "WORM":
17
18
  data_path = None
@@ -21,6 +22,95 @@ def complex_fit(n_complex=4, metal="Co+2", ligand="Cl-", logK_data="demo.csv", d
21
22
  df_logK = pd.read_csv(logK_data)
22
23
  df_logK["legendgroup"] = df_logK.apply(lambda x: str(x["P"]) + " bars (" + str(x["ref"]) + ")" if str(x["P"]) != "Psat" else "Psat (" + str(x["ref"]) + ")", axis=1)
23
24
 
25
+ if auto_fit:
26
+ def _get_predicted_logK(lb, s, cp, v):
27
+ """Run complicate + subcrt and return list of predicted logK values, or None on failure."""
28
+ d = {
29
+ "Metal": [metal],
30
+ "Ligand": [ligand],
31
+ "BETA_1": [0], "BETA_2": [0], "BETA_3": [0], "BETA_4": [0],
32
+ "S_"+str(n_complex): [s],
33
+ "Cp_"+str(n_complex): [cp],
34
+ "V_"+str(n_complex): [v],
35
+ }
36
+ d["BETA_"+str(n_complex)] = [lb]
37
+ df_in = pd.DataFrame(d)
38
+ df_o, _, _, _ = complicate(df_in=df_in, data_path=data_path, print_warnings=False)
39
+ if df_o is None or df_o.empty or len(df_o) < n_complex:
40
+ return None
41
+ cname = df_o["name"].iloc[n_complex-1]
42
+ _ = pychnosz.add_OBIGT(df_o, force=True, messages=False)
43
+ predictions = []
44
+ for i in range(len(df_logK)):
45
+ P_val = df_logK["P"].iloc[i]
46
+ if P_val != "Psat":
47
+ P_val = float(P_val)
48
+ try:
49
+ pred = pychnosz.subcrt(
50
+ [metal, ligand, cname], [-1, -n_complex, 1],
51
+ T=df_logK["T,C"].iloc[i], P=P_val,
52
+ show=False, messages=False).out
53
+ if "logK" in pred.columns:
54
+ predictions.append(pred["logK"].values[0])
55
+ else:
56
+ predictions.append(float('nan'))
57
+ except:
58
+ predictions.append(float('nan'))
59
+ return predictions
60
+
61
+ # Fix log_beta from 25°C Psat data point if available
62
+ ref_mask = (df_logK["T,C"] == 25) & (df_logK["P"].astype(str) == "Psat")
63
+ if ref_mask.any():
64
+ log_beta = df_logK.loc[ref_mask, "logK"].iloc[0]
65
+ elif log_beta == 0:
66
+ idx_lowT = df_logK["T,C"].values.argmin()
67
+ log_beta = df_logK["logK"].iloc[idx_lowT]
68
+
69
+ # Test that the model works with the fixed log_beta
70
+ test_pred = _get_predicted_logK(log_beta, S, Cp, V)
71
+ if test_pred is None:
72
+ print("Warning: model cannot be evaluated. Check metal/ligand/data_path settings.")
73
+ else:
74
+ def _objective(params):
75
+ s, cp, v = params
76
+ preds = _get_predicted_logK(log_beta, s, cp, v)
77
+ if preds is None:
78
+ return 1e10
79
+ residuals = 0.0
80
+ n_valid = 0
81
+ for i in range(len(df_logK)):
82
+ if preds[i] is None or math.isnan(preds[i]):
83
+ continue
84
+ err_val = df_logK["err"].iloc[i]
85
+ if pd.isna(err_val) or err_val <= 0:
86
+ err_val = 1.0
87
+ weight = 1.0 / err_val
88
+ residuals += (weight * (df_logK["logK"].iloc[i] - preds[i])) ** 2
89
+ n_valid += 1
90
+ if n_valid == 0:
91
+ return 1e10
92
+ return residuals / n_valid
93
+
94
+ x0 = [S, Cp, V]
95
+ print("Fixing log_beta={:.4f}. Optimizing S, Cp, V...".format(log_beta), end="", flush=True)
96
+
97
+ _iter_count = [0]
98
+ def _callback(xk):
99
+ _iter_count[0] += 1
100
+ if _iter_count[0] % 5 == 0:
101
+ print(".", end="", flush=True)
102
+
103
+ result = minimize(_objective, x0, method='Powell',
104
+ callback=_callback,
105
+ options={'xtol': 0.001, 'ftol': 0.01, 'maxiter': 2000})
106
+ print(" done.")
107
+ S, Cp, V = result.x
108
+ S = max(-1000, min(1000, S))
109
+ Cp = max(-1000, min(1000, Cp))
110
+ V = max(-1000, min(1000, V))
111
+ print("Auto-fit result: log_beta={:.4f}, S={:.2f}, Cp={:.2f}, V={:.2f}".format(
112
+ log_beta, S, Cp, V))
113
+
24
114
  dict_input = {
25
115
  "Metal":[metal],
26
116
  "Ligand":[ligand],
@@ -77,9 +167,9 @@ def complex_fit(n_complex=4, metal="Co+2", ligand="Cl-", logK_data="demo.csv", d
77
167
  Pfloat = P
78
168
 
79
169
  logK_pred = pychnosz.subcrt([metal, ligand, complex_name], [-1, -n_complex, 1],
80
- T=df_logK["T,C"][i], property="logK", P=Pfloat,
170
+ T=df_logK["T,C"][i], P=Pfloat,
81
171
  show=False, messages=False).out
82
- logK_pred = logK_pred.values[0][0]
172
+ logK_pred = logK_pred["logK"].values[0]
83
173
 
84
174
  if df_logK["legendgroup"][i] in legendgroups_added:
85
175
  showlegend = False
@@ -88,13 +178,21 @@ def complex_fit(n_complex=4, metal="Co+2", ligand="Cl-", logK_data="demo.csv", d
88
178
  legendgroups_added.append(df_logK["legendgroup"][i])
89
179
 
90
180
  line_col = plotly.colors.qualitative.D3[len(legendgroups_added)-1]
91
- if math.isclose(df_logK["logK"][i], logK_pred, rel_tol=0.1) or math.isclose(df_logK["logK"][i], logK_pred, abs_tol=df_logK["err"][i]):
181
+ err_val = df_logK["err"][i]
182
+ has_err = not pd.isna(err_val)
183
+ if math.isclose(df_logK["logK"][i], logK_pred, rel_tol=0.1) or (has_err and math.isclose(df_logK["logK"][i], logK_pred, abs_tol=err_val)):
92
184
  # filled circle
93
185
  fill_col = line_col
94
186
  else:
95
187
  # open circle
96
188
  fill_col = 'rgba(255, 0, 0, 0.0)'
97
189
 
190
+ error_y_dict = dict(
191
+ type='data',
192
+ array=[err_val if has_err else 0],
193
+ color=line_col,
194
+ visible=has_err)
195
+
98
196
  fig.add_trace(go.Scatter(
99
197
  x=[df_logK['T,C'][i]],
100
198
  y=[df_logK['logK'][i]],
@@ -103,16 +201,12 @@ def complex_fit(n_complex=4, metal="Co+2", ligand="Cl-", logK_data="demo.csv", d
103
201
  showlegend=showlegend,
104
202
  mode="markers",
105
203
  marker=dict(
106
- size=10,
204
+ size=10,
107
205
  symbol='circle',
108
206
  line_width=2,
109
207
  line_color=line_col,
110
208
  color=fill_col),
111
- error_y=dict(
112
- type='data',
113
- array=[df_logK["err"][i]],
114
- color=line_col,
115
- visible=True),
209
+ error_y=error_y_dict,
116
210
  )
117
211
  )
118
212
 
@@ -1,13 +1,13 @@
1
- ligand,abbrv
2
- formate,For
3
- acetate,Ac
4
- succinate-2,Succ
5
- malonate-2,Mal
6
- glutarate-2,Glut
7
- adipate-2,Adip
8
- pimelate-2,Pime
9
- propanoate,Prop
10
- butanoate,But
11
- pentanoate,Pent
12
- glycolate,Glyc
13
- lactate,Lac
1
+ ligand,abbrv
2
+ formate,For
3
+ acetate,Ac
4
+ succinate-2,Succ
5
+ malonate-2,Mal
6
+ glutarate-2,Glut
7
+ adipate-2,Adip
8
+ pimelate-2,Pime
9
+ propanoate,Prop
10
+ butanoate,But
11
+ pentanoate,Pent
12
+ glycolate,Glyc
13
+ lactate,Lac
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: complicator
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Estimate thermodynamic properties of aqueous metal complexes with monovalent ligands.
5
5
  Author-email: Grayson Boyer <gmboyer@asu.edu>
6
6
  License-Expression: MIT
@@ -13,6 +13,7 @@ License-File: LICENSE.txt
13
13
  Requires-Dist: pandas
14
14
  Requires-Dist: wormutils
15
15
  Requires-Dist: chemparse
16
+ Requires-Dist: scipy
16
17
  Dynamic: license-file
17
18
 
18
19
  # The Complicator
@@ -1,3 +1,4 @@
1
1
  pandas
2
2
  wormutils
3
3
  chemparse
4
+ scipy
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "complicator"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "Estimate thermodynamic properties of aqueous metal complexes with monovalent ligands."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -21,6 +21,7 @@ dependencies = [
21
21
  "pandas",
22
22
  "wormutils",
23
23
  "chemparse",
24
+ "scipy",
24
25
  ]
25
26
 
26
27
  [project.urls]
File without changes
File without changes
File without changes
File without changes