mattbitzesty commited on
Commit
dc36068
·
unverified ·
1 Parent(s): 680d9cb

refactor(vle): move UNIFAC VLE implementation into pino.thermo module

Browse files

Make pino.vle a backward-compatible re-export of pino.thermo.vle.
Keeps existing imports working while isolating thermodynamic code.

Files changed (3) hide show
  1. src/pino/thermo/unifac.py +177 -0
  2. src/pino/thermo/vle.py +122 -0
  3. src/pino/vle.py +5 -102
src/pino/thermo/unifac.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from thermo.unifac import DOUFSG
9
+
10
+ from ..models import IngredientResolutionError
11
+
12
+ logger = logging.getLogger("pino.thermo.unifac")
13
+
14
+ # Import DOUFSG subgroup IDs from the active thermo backend.
15
+ DOUFSG_AVAILABLE_GROUPS = set(DOUFSG.keys())
16
+
17
+ # Fallback map: replace known exotic fragments that are not in DOUFSG with
18
+ # structurally closest saturated/aliphatic/aromatic equivalents.
19
+ # Values are dictionaries of replacement subgroup IDs and their counts.
20
+ STRUCTURAL_FALLBACKS: dict[int, dict[int, int]] = {
21
+ # Example: any exotic unsaturated alkyl chain could map to a saturated CH2 equivalent.
22
+ # Real mappings are populated from audit data as they are discovered.
23
+ }
24
+
25
+ # Name-to-ID map built from thermo DOUFSG for quick lookups.
26
+ _THERMO_NAME_TO_ID = {str(v.group): k for k, v in DOUFSG.items()}
27
+
28
+
29
+ # Aliases for ugropy subgroup names that differ from thermo's labels.
30
+ _UGROPY_TO_THERMO_NAME: dict[str, str] = {
31
+ "HCO": "CHO",
32
+ "CH=O": "CHO",
33
+ "OH (P)": "OH(P)",
34
+ "OH (S)": "OH(S)",
35
+ "OH (T)": "OH(T)",
36
+ }
37
+
38
+ # Hardcoded ID overrides for ambiguous labels.
39
+ _EXPLICIT_THERMO_ID: dict[str, int] = {
40
+ "HCO": 20,
41
+ "CH=O": 20,
42
+ "CHO__ALDEHYDE": 20,
43
+ "CHO__ETHER": 26,
44
+ }
45
+
46
+
47
+ def _map_ugropy_name_to_thermo_id(name: str) -> int | None:
48
+ """Translate a ugropy subgroup name to a thermo DOUFSG subgroup ID."""
49
+ if name in _EXPLICIT_THERMO_ID:
50
+ return _EXPLICIT_THERMO_ID[name]
51
+ normalised = _UGROPY_TO_THERMO_NAME.get(name, name).replace(" ", "")
52
+ if normalised in _EXPLICIT_THERMO_ID:
53
+ return _EXPLICIT_THERMO_ID[normalised]
54
+ return _THERMO_NAME_TO_ID.get(normalised)
55
+
56
+
57
+ def get_dortmund_subgroups(smiles: str) -> dict[str, int]:
58
+ """
59
+ Derive Dortmund UNIFAC subgroup counts from a SMILES string using ugropy.
60
+
61
+ Returns a dict of {subgroup_id_str: count}. Only subgroups that exist in the
62
+ active DOUFSG parameter set are returned. If the molecule cannot be
63
+ fragmented, an empty dict is returned.
64
+ """
65
+ import ugropy
66
+
67
+ try:
68
+ groups_obj = ugropy.Groups(smiles, identifier_type="smiles")
69
+ raw_groups = groups_obj.dortmund.subgroups
70
+ except Exception as exc:
71
+ logger.debug("ugropy fragmentation failed for %s: %s", smiles, exc)
72
+ return {}
73
+
74
+ if not raw_groups:
75
+ return {}
76
+
77
+ result: dict[str, int] = {}
78
+ for name, count in raw_groups.items():
79
+ subgroup_id = _map_ugropy_name_to_thermo_id(name)
80
+ if subgroup_id is None:
81
+ logger.debug("ugropy subgroup '%s' for %s not in DOUFSG", name, smiles)
82
+ continue
83
+ if subgroup_id not in DOUFSG_AVAILABLE_GROUPS:
84
+ logger.debug("Resolved subgroup ID %s for %s not in DOUFSG", subgroup_id, smiles)
85
+ continue
86
+ result[str(subgroup_id)] = int(count)
87
+
88
+ return result
89
+
90
+
91
+ def validate_subgroups(groups: dict[str, int] | dict[int, int]) -> tuple[bool, set[int]]:
92
+ """
93
+ Check whether all subgroup IDs in a group dict are available in DOUFSG.
94
+
95
+ Returns (valid, missing_ids).
96
+ """
97
+ missing: set[int] = set()
98
+ for gid in groups.keys():
99
+ try:
100
+ gid_int = int(gid)
101
+ except (ValueError, TypeError):
102
+ continue
103
+ if gid_int not in DOUFSG_AVAILABLE_GROUPS:
104
+ missing.add(gid_int)
105
+ return len(missing) == 0, missing
106
+
107
+
108
+ def apply_structural_fallback(groups: dict[str, int] | dict[int, int], missing: set[int]) -> dict[str, int]:
109
+ """
110
+ Apply a conservative structural fallback for missing subgroups.
111
+
112
+ If a missing subgroup has a known mapping in STRUCTURAL_FALLBACKS, it is
113
+ replaced. Otherwise, the subgroup is removed and the molecule is treated as
114
+ ideal if nothing remains.
115
+ """
116
+ cleaned: dict[str, int] = {str(k): int(v) for k, v in groups.items()}
117
+ for gid in missing:
118
+ if gid in STRUCTURAL_FALLBACKS:
119
+ logger.warning("Applying structural fallback for missing subgroup %s", gid)
120
+ replacement = STRUCTURAL_FALLBACKS[gid]
121
+ for rep_id, count in replacement.items():
122
+ cleaned[str(rep_id)] = cleaned.get(str(rep_id), 0) + count
123
+ cleaned.pop(str(gid), None)
124
+ else:
125
+ logger.warning("No fallback for missing subgroup %s; using ideal gamma=1", gid)
126
+ cleaned.pop(str(gid), None)
127
+
128
+ # If any missing subgroup remains unmapped, return empty dict to force ideal.
129
+ valid, still_missing = validate_subgroups(cleaned)
130
+ if not valid and still_missing:
131
+ logger.warning("Remaining missing subgroups %s; ideal gamma fallback", still_missing)
132
+ return {}
133
+
134
+ return cleaned
135
+
136
+
137
+ def prepare_unifac_groups(
138
+ groups: dict[str, int] | dict[int, int],
139
+ *,
140
+ allow_fallback: bool = True,
141
+ ) -> dict[str, int]:
142
+ """
143
+ Normalize a group dict and ensure all subgroups are representable in DOUFSG.
144
+
145
+ If allow_fallback is True, missing groups are mapped to structural equivalents
146
+ or removed; if False, an IngredientResolutionError is raised for missing groups.
147
+ """
148
+ valid, missing = validate_subgroups(groups)
149
+ if valid:
150
+ return {str(k): int(v) for k, v in groups.items()}
151
+
152
+ if not allow_fallback:
153
+ raise IngredientResolutionError(
154
+ f"UNIFAC subgroups {missing} not available in DOUFSG"
155
+ )
156
+
157
+ logger.warning("Missing DOUFSG subgroups %s; applying fallback", missing)
158
+ return apply_structural_fallback(groups, missing)
159
+
160
+
161
+ def load_fallbacks_from_audit(path: str | Path) -> None:
162
+ """Load a JSON file of fallback rules and merge into STRUCTURAL_FALLBACKS."""
163
+ p = Path(path)
164
+ if not p.exists():
165
+ return
166
+ data = json.loads(p.read_text())
167
+ for entry in data:
168
+ missing = entry.get("missing_subgroup_id")
169
+ replacement = entry.get("replacement")
170
+ if missing is not None and isinstance(replacement, dict):
171
+ STRUCTURAL_FALLBACKS[missing] = {
172
+ int(k): int(v) for k, v in replacement.items()
173
+ }
174
+
175
+
176
+ # Optional: load any user-defined fallback rules at import time.
177
+ load_fallbacks_from_audit(Path(__file__).parent.parent.parent / "data" / "unifac_fallbacks.json")
src/pino/thermo/vle.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+ from thermo.unifac import DOUFIP2006, DOUFSG, UNIFAC
8
+
9
+ from ..models import Formula
10
+ from .unifac import DOUFSG_AVAILABLE_GROUPS, apply_structural_fallback, validate_subgroups
11
+
12
+ logger = logging.getLogger("pino.thermo.vle")
13
+
14
+
15
+ class VLECalculator:
16
+ """Compute non-ideal VLE via Dortmund-Modified UNIFAC with dynamic fallback."""
17
+
18
+ def __init__(self, formula: Formula) -> None:
19
+ self.formula = formula
20
+ self._cache: dict[tuple[float, ...], np.ndarray] = {}
21
+ self._has_unifac = False
22
+ self.unifac: UNIFAC | None = None
23
+ self._setup_unifac()
24
+
25
+ def _setup_unifac(self) -> None:
26
+ """Build a UNIFAC object from the ingredient DDB UNIFAC groups."""
27
+ groups: list[dict[int, int]] = []
28
+ for ing in self.formula.ingredients:
29
+ raw = ing.unifac_groups or {}
30
+ # Coerce string/int keys to integers for validation.
31
+ int_groups: dict[int, int] = {}
32
+ for gid, count in raw.items():
33
+ try:
34
+ key = int(gid)
35
+ except (ValueError, TypeError):
36
+ logger.warning("Skipping non-integer UNIFAC group id %s", gid)
37
+ continue
38
+ int_groups[key] = int(count)
39
+
40
+ valid, missing = validate_subgroups(int_groups)
41
+ if not valid:
42
+ cleaned = apply_structural_fallback(int_groups, missing)
43
+ if not cleaned:
44
+ logger.warning(
45
+ "UNIFAC unavailable for %s (CAS %s); activity coefficients default to 1.0",
46
+ ing.name, ing.cas
47
+ )
48
+ groups.append({})
49
+ continue
50
+ int_groups = {int(k): int(v) for k, v in cleaned.items()}
51
+
52
+ groups.append(int_groups)
53
+
54
+ # Require every ingredient to have at least one valid UNIFAC group.
55
+ self._has_unifac = all(bool(g) for g in groups) and len(groups) == len(self.formula.ingredients)
56
+ if not self._has_unifac:
57
+ logger.debug("UNIFAC unavailable for formula; activity coefficients default to 1.0")
58
+ return
59
+
60
+ try:
61
+ self.unifac = UNIFAC.from_subgroups(
62
+ T=self.formula.temperature_k,
63
+ xs=[1.0 / len(self.formula.ingredients)] * len(self.formula.ingredients),
64
+ chemgroups=groups,
65
+ version=1,
66
+ interaction_data=DOUFIP2006,
67
+ subgroups=DOUFSG,
68
+ )
69
+ except Exception as exc:
70
+ logger.warning("UNIFAC setup failed (%s); falling back to ideal gammas=1", exc)
71
+ self._has_unifac = False
72
+ self.unifac = None
73
+
74
+ def activity_coefficients(self, x: np.ndarray) -> np.ndarray:
75
+ """Return gamma_i for liquid mole fractions x using UNIFAC."""
76
+ key = tuple(np.round(x, 12).tolist())
77
+ if key in self._cache:
78
+ return self._cache[key]
79
+
80
+ if not self._has_unifac or self.unifac is None:
81
+ gammas = np.ones_like(x, dtype=float)
82
+ else:
83
+ try:
84
+ new_unifac = self.unifac.to_T_xs(
85
+ T=self.formula.temperature_k,
86
+ xs=x.tolist(),
87
+ )
88
+ gammas = np.array(new_unifac.gammas(), dtype=float)
89
+ except Exception as exc:
90
+ logger.warning("UNIFAC gamma calculation failed (%s); using gamma=1", exc)
91
+ gammas = np.ones_like(x, dtype=float)
92
+
93
+ self._cache[key] = gammas
94
+ return gammas
95
+
96
+ def partial_pressures(self, x: np.ndarray) -> np.ndarray:
97
+ """P_i = gamma_i * x_i * P_i^sat (non-ideal Raoult)."""
98
+ gamma = self.activity_coefficients(x)
99
+ p_sat = np.array([i.vapor_pressure_pa for i in self.formula.ingredients], dtype=float)
100
+ return gamma * x * p_sat
101
+
102
+ def gas_mole_fractions(self, x: np.ndarray) -> np.ndarray:
103
+ """y_i = P_i / P_total (assuming gas phase ideal at ambient pressure)."""
104
+ p_partial = self.partial_pressures(x)
105
+ p_total = p_partial.sum()
106
+ if p_total <= 0:
107
+ return np.zeros_like(x)
108
+ return p_partial / p_total
109
+
110
+ def gas_concentrations_mg_m3(self, x: np.ndarray) -> np.ndarray:
111
+ """Convert gas mole fractions to mass concentrations at ambient T and P."""
112
+ y = self.gas_mole_fractions(x)
113
+ # total molar concentration (mol/m3) = P / (R T)
114
+ R = 8.314462618 # J/(mol K)
115
+ c_total = self.formula.ambient_pressure_pa / (R * self.formula.temperature_k) # mol/m3
116
+ mws = np.array([i.molecular_weight for i in self.formula.ingredients], dtype=float) # g/mol
117
+ # mg/m3 = y_i * C_total * MW_i * 1000 mg/g
118
+ return y * c_total * mws * 1000.0
119
+
120
+ def fugacity_ratios(self, x: np.ndarray) -> np.ndarray:
121
+ """Driving force for evaporation: f_i^L / (P * phi_i) ≈ gamma_i * x_i * P_i^sat / P."""
122
+ return self.partial_pressures(x) / self.formula.ambient_pressure_pa
src/pino/vle.py CHANGED
@@ -1,106 +1,9 @@
1
  from __future__ import annotations
2
 
3
- import logging
4
- from typing import Any
 
5
 
6
- import numpy as np
7
- from thermo.unifac import DOUFIP2006, DOUFSG, UNIFAC
8
 
9
- from .models import Formula
10
-
11
- logger = logging.getLogger("pino.vle")
12
-
13
-
14
- class VLECalculator:
15
- """Compute non-ideal VLE via Dortmund-Modified UNIFAC."""
16
-
17
- def __init__(self, formula: Formula) -> None:
18
- self.formula = formula
19
- self._cache: dict[tuple[float, ...], np.ndarray] = {}
20
- self._has_unifac = False
21
- self.unifac: UNIFAC | None = None
22
- self._setup_unifac()
23
-
24
- def _setup_unifac(self) -> None:
25
- """Build a UNIFAC object from the ingredient DDB UNIFAC groups."""
26
- # Convert group ids to integer keys. ugropy emits DDB UNIFAC (Dortmund) group ids.
27
- groups = []
28
- for ing in self.formula.ingredients:
29
- grp = {}
30
- for gid, count in ing.unifac_groups.items():
31
- try:
32
- key = int(gid)
33
- except ValueError:
34
- logger.warning("Skipping non-integer UNIFAC group id %s", gid)
35
- continue
36
- grp[key] = count
37
- groups.append(grp)
38
-
39
- self._has_unifac = any(groups)
40
- if not self._has_unifac:
41
- logger.warning("No UNIFAC groups available; activity coefficients default to 1.0")
42
- return
43
-
44
- try:
45
- self.unifac = UNIFAC.from_subgroups(
46
- T=self.formula.temperature_k,
47
- xs=[1.0 / len(self.formula.ingredients)] * len(self.formula.ingredients),
48
- chemgroups=groups,
49
- version=1,
50
- interaction_data=DOUFIP2006,
51
- subgroups=DOUFSG,
52
- )
53
- except Exception as exc:
54
- logger.warning("UNIFAC setup failed (%s); falling back to ideal gammas=1", exc)
55
- self._has_unifac = False
56
- self.unifac = None
57
-
58
- def activity_coefficients(self, x: np.ndarray) -> np.ndarray:
59
- """Return gamma_i for liquid mole fractions x using UNIFAC."""
60
- key = tuple(np.round(x, 12).tolist())
61
- if key in self._cache:
62
- return self._cache[key]
63
-
64
- if not self._has_unifac or self.unifac is None:
65
- gammas = np.ones_like(x, dtype=float)
66
- else:
67
- try:
68
- new_unifac = self.unifac.to_T_xs(
69
- T=self.formula.temperature_k,
70
- xs=x.tolist(),
71
- )
72
- gammas = np.array(new_unifac.gammas(), dtype=float)
73
- except Exception as exc:
74
- logger.warning("UNIFAC gamma calculation failed (%s); using gamma=1", exc)
75
- gammas = np.ones_like(x, dtype=float)
76
-
77
- self._cache[key] = gammas
78
- return gammas
79
-
80
- def partial_pressures(self, x: np.ndarray) -> np.ndarray:
81
- """P_i = gamma_i * x_i * P_i^sat (non-ideal Raoult)."""
82
- gamma = self.activity_coefficients(x)
83
- p_sat = np.array([i.vapor_pressure_pa for i in self.formula.ingredients], dtype=float)
84
- return gamma * x * p_sat
85
-
86
- def gas_mole_fractions(self, x: np.ndarray) -> np.ndarray:
87
- """y_i = P_i / P_total (assuming gas phase ideal at ambient pressure)."""
88
- p_partial = self.partial_pressures(x)
89
- p_total = p_partial.sum()
90
- if p_total <= 0:
91
- return np.zeros_like(x)
92
- return p_partial / p_total
93
-
94
- def gas_concentrations_mg_m3(self, x: np.ndarray) -> np.ndarray:
95
- """Convert gas mole fractions to mass concentrations at ambient T and P."""
96
- y = self.gas_mole_fractions(x)
97
- # total molar concentration (mol/m3) = P / (R T)
98
- R = 8.314462618 # J/(mol K)
99
- c_total = self.formula.ambient_pressure_pa / (R * self.formula.temperature_k) # mol/m3
100
- mws = np.array([i.molecular_weight for i in self.formula.ingredients], dtype=float) # g/mol
101
- # mg/m3 = y_i * C_total * MW_i * 1000 mg/g
102
- return y * c_total * mws * 1000.0
103
-
104
- def fugacity_ratios(self, x: np.ndarray) -> np.ndarray:
105
- """Driving force for evaporation: f_i^L / (P * phi_i) ≈ gamma_i * x_i * P_i^sat / P."""
106
- return self.partial_pressures(x) / self.formula.ambient_pressure_pa
 
1
  from __future__ import annotations
2
 
3
+ # Backward-compatible re-export of the thermodynamic VLE module.
4
+ # Legacy code can continue to import from pino.vle; new code should use
5
+ # pino.thermo.vle directly.
6
 
7
+ from pino.thermo.vle import VLECalculator
 
8
 
9
+ __all__ = ["VLECalculator"]