Spaces:
Sleeping
Sleeping
File size: 17,268 Bytes
8c867c9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | """
modules/compatibility.py
Molecular compatibility engine for IntelliForm Enterprise.
Uses SMILES strings + function categories to compute pairwise ingredient
compatibility using quantum-chemistry-inspired molecular descriptors:
- Ionic character (cationic / anionic / nonionic / amphoteric)
- Hydrophobicity index (estimated log P from carbon chain length)
- Functional group flags (aldehyde, amine, peroxide, acid, base, metal ion)
- pH operating window
- HLB value (Davies method from SMILES functional groups)
- DLVO-based colloidal stability score
No external chemistry libraries required β all analysis via SMILES regex.
"""
from __future__ import annotations
import re
import math
from dataclasses import dataclass, field
from typing import Dict, List, Tuple, Optional
import numpy as np
import pandas as pd
# ββ Molecular descriptor extraction ββββββββββββββββββββββββββββββββββββββββββ
# HLB group contributions (Davies method)
_HLB_GROUPS = {
# Hydrophilic
r"-SO4": 38.7,
r"SO3": 38.7,
r"N\+": 9.4, # quaternary amine / cationic
r"COO-": 21.2,
r"COOH": 2.1,
r"OH(?!C)": 1.9, # free hydroxyl
r"OC": 1.3, # ether oxygen
r"C\(=O\)O": 2.4, # ester
r"C1OC": 0.33, # glucoside ring (per unit, multiply by 4)
# Hydrophobic
r"CH3": -0.475,
r"CH2": -0.475,
r"CH": -0.475,
}
_IONIC_PATTERNS = {
"cationic": [r"\[N\+\]", r"N\+", r"\[NH4\+\]", r"quaternary"],
"anionic": [r"SO3", r"SO4", r"COO\-", r"\[O\-\]", r"PO4", r"phosphate"],
"amphoteric": [r"N.*COO", r"NH.*SO3", r"betaine", r"Betaine"],
"nonionic": [], # default if none of the above match
}
_FUNCTIONAL_FLAGS = {
"aldehyde": r"C=O(?!.*\[O\-\])", # RCHO
"amine": r"[NX3;H]",
"peroxide": r"OO",
"strong_acid": r"S\(=O\)\(=O\)O[H]?(?!\w)",
"strong_base": r"\[OH\-\]|\[Na\+\].*O|\bNaOH\b",
"metal_ion": r"\[Fe|Cu|Zn|Mn|Ca|Mg",
"thiol": r"[SH]",
"phenol": r"c1ccc.*O",
"glucoside": r"OC[C@@H]1O|OCC1O|C1OC",
}
# Known incompatible function-category pairs
_FUNCTION_INCOMPATIBILITIES: List[Tuple[str, str, str, int]] = [
# (fn_a, fn_b, reason, severity 1-10)
("Cationic Surfactant", "Anionic Surfactant", "Ion-pair precipitation β cloudiness/separation", 10),
("Cationic Surfactant", "Primary Surfactant", "Possible interference β check anionic content", 5),
("Preservative", "Cationic Surfactant", "Quat preservatives may be inactivated", 7),
("Chelating Agent", "Metal Ion Source", "Chelation reaction β intended or adverse?", 4),
("Oxidizing Agent", "Reducing Agent", "Redox reaction β exothermic risk", 10),
("Oxidizing Agent", "Amine", "N-nitrosamine formation risk", 9),
("Acid Activator", "Alkali Builder", "Neutralisation β pH instability", 8),
("Fragrance", "Oxidizing Agent", "Fragrance oxidation / rancidity", 6),
("Protein", "Anionic Surfactant", "Protein denaturation possible", 6),
("Enzyme", "Preservative", "Enzyme inhibition by biocides", 7),
("Enzyme", "Chelating Agent", "Metal co-factor stripping", 5),
]
# pH windows per function (min_pH, max_pH)
_PH_WINDOWS: Dict[str, Tuple[float, float]] = {
"Primary Surfactant": (4.0, 9.5),
"Secondary Surfactant": (4.0, 9.5),
"Cationic Surfactant": (2.0, 7.0),
"Preservative": (3.0, 6.5),
"Chelating Agent": (3.0, 12.0),
"Thickener": (4.0, 9.0),
"Emollient": (4.0, 10.0),
"Emulsifier": (4.0, 9.0),
"Fragrance": (4.0, 8.5),
"Enzyme": (6.0, 9.5),
"Bleach Activator": (9.0, 12.0),
"Alkali Builder": (8.0, 13.0),
"Acid Activator": (1.0, 5.0),
"Optical Brightener": (7.0, 12.0),
"Antioxidant": (3.5, 8.5),
"default": (3.0, 11.0),
}
@dataclass
class MolDescriptor:
"""Quantum-chemistry-inspired molecular descriptor for one ingredient."""
name: str
smiles: str
function: str
ionic_type: str # cationic | anionic | amphoteric | nonionic
logP_est: float # estimated log octanol-water partition coefficient
hlb: float # HLB value (Davies)
ph_min: float
ph_max: float
flags: List[str] # aldehyde, amine, peroxide, β¦
charge_density: float # 0-1 estimate of charge surface density
@dataclass
class CompatPair:
"""Compatibility assessment between two ingredients."""
ingredient_a: str
ingredient_b: str
score: int # 0 (incompatible) β 100 (fully compatible)
risk_level: str # low | medium | high | critical
issues: List[str]
hlb_delta: float # |HLB_a - HLB_b|
@dataclass
class CompatibilityReport:
"""Full compatibility analysis for a blend."""
success: bool
overall_score: int # 0-100 weighted blend compatibility
risk_summary: str # one-line verdict
pairs: List[CompatPair]
critical_pairs: List[CompatPair]
ph_window: Tuple[float, float] # intersection of all pH windows
hlb_blend: float # weighted HLB of blend
emulsion_type: str # o/w | w/o | unclear | not applicable
descriptors: List[MolDescriptor]
warnings: List[str]
error_msg: Optional[str] = None
# ββ SMILES parsing helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _count_pattern(smiles: str, pattern: str) -> int:
return len(re.findall(pattern, smiles or ""))
def _estimate_logP(smiles: str) -> float:
"""Simplified Wildman-Crippen log P estimate from SMILES carbon chain."""
if not smiles:
return 0.0
# Count aliphatic carbons (each ~0.53 log P units)
n_C = len(re.findall(r"C(?![a-z])", smiles))
# Count strongly hydrophilic atoms
n_O = smiles.count("O")
n_N = smiles.count("N")
n_SO = smiles.count("S")
logP = 0.53 * n_C - 1.03 * n_O - 0.68 * n_N + 0.39 * n_SO
return round(logP, 2)
def _estimate_hlb(smiles: str, function: str) -> float:
"""Davies HLB estimate from SMILES functional groups."""
if not smiles:
# Fall back to function-based heuristics
hlb_by_fn = {
"Primary Surfactant": 12.0,
"Secondary Surfactant": 11.0,
"Cationic Surfactant": 13.0,
"Emulsifier": 10.0,
"Emollient": 5.0,
"Oil": 3.0,
"Wax": 4.0,
"Thickener": 8.0,
}
return hlb_by_fn.get(function, 7.0)
total = 7.0 # Davies base
for pat, contribution in _HLB_GROUPS.items():
count = len(re.findall(pat, smiles))
if "C1OC" in pat and count > 0:
count *= 4 # glucoside ring contributes 4 units
total += contribution * count
return round(max(0.0, min(20.0, total)), 1)
def _get_ionic(smiles: str, function: str) -> str:
if not smiles:
if "Cationic" in function:
return "cationic"
if "Anionic" in function:
return "anionic"
return "nonionic"
for ionic_type, patterns in _IONIC_PATTERNS.items():
if ionic_type == "nonionic":
continue
for p in patterns:
if re.search(p, smiles):
return ionic_type
return "nonionic"
def _get_flags(smiles: str) -> List[str]:
found = []
for flag, pat in _FUNCTIONAL_FLAGS.items():
if smiles and re.search(pat, smiles):
found.append(flag)
return found
def _charge_density(smiles: str, ionic_type: str) -> float:
"""Estimate 0-1 charge surface density (proxy for ionic strength)."""
if ionic_type == "nonionic":
return 0.0
if not smiles:
return 0.5
n_charge_groups = (
_count_pattern(smiles, r"SO3|SO4|COO\-|\[O\-\]") +
_count_pattern(smiles, r"\[N\+\]|N\+")
)
n_heavy = max(1, len(re.findall(r"[BCNOFPSICL]", smiles, re.IGNORECASE)))
return round(min(1.0, n_charge_groups / (n_heavy * 0.15)), 2)
def _build_descriptor(row: pd.Series) -> MolDescriptor:
sm = str(row.get("SMILES", "") or "")
fn = str(row.get("Function", "default"))
ionic = _get_ionic(sm, fn)
ph_range = _PH_WINDOWS.get(fn, _PH_WINDOWS["default"])
# row.name is the index (ingredient name) when set_index("Ingredient") is used
return MolDescriptor(
name=row.name,
smiles=sm,
function=fn,
ionic_type=ionic,
logP_est=_estimate_logP(sm),
hlb=_estimate_hlb(sm, fn),
ph_min=ph_range[0],
ph_max=ph_range[1],
flags=_get_flags(sm),
charge_density=_charge_density(sm, ionic),
)
# ββ Pairwise compatibility scorer βββββββββββββββββββββββββββββββββββββββββββββ
def _score_pair(a: MolDescriptor, b: MolDescriptor,
pct_a: float, pct_b: float) -> CompatPair:
score = 100
issues = []
# ββ 1. Ionic charge clash ββββββββββββββββββββββββββββββββββββββββββββββ
if {a.ionic_type, b.ionic_type} == {"cationic", "anionic"}:
severity = int(50 * (a.charge_density + b.charge_density))
score -= min(severity, 60)
issues.append(f"Cationic/anionic pair β ion-pair complex formation risk "
f"(charge density: {a.charge_density:.2f} Γ {b.charge_density:.2f})")
# ββ 2. Function incompatibility lookup ββββββββββββββββββββββββββββββββ
for fn_a, fn_b, reason, sev in _FUNCTION_INCOMPATIBILITIES:
if ({a.function, b.function} == {fn_a, fn_b} or
(fn_a in a.function and fn_b in b.function) or
(fn_a in b.function and fn_b in a.function)):
score -= sev * 4
issues.append(reason)
# ββ 3. SMILES functional-group clash βββββββββββββββββββββββββββββββββ
combined_flags = set(a.flags + b.flags)
if "aldehyde" in a.flags and "amine" in b.flags:
score -= 20
issues.append("Aldehyde + amine β Schiff base formation (yellowing, viscosity change)")
if "aldehyde" in b.flags and "amine" in a.flags:
score -= 20
issues.append("Aldehyde + amine β Schiff base formation")
if "peroxide" in combined_flags and ("fragrance" in a.function.lower()
or "fragrance" in b.function.lower()):
score -= 15
issues.append("Peroxide can oxidise fragrance components (rancidity)")
if "thiol" in combined_flags and "peroxide" in combined_flags:
score -= 25
issues.append("Thiol + peroxide β disulfide / exothermic oxidation risk")
if "metal_ion" in combined_flags and "peroxide" in combined_flags:
score -= 30
issues.append("Metal ions catalyse peroxide decomposition (Fenton-type)")
# ββ 4. pH window overlap βββββββββββββββββββββββββββββββββββββββββββββββ
ph_lo = max(a.ph_min, b.ph_min)
ph_hi = min(a.ph_max, b.ph_max)
if ph_hi < ph_lo:
score -= 20
issues.append(
f"pH windows don't overlap: {a.name} ({a.ph_min}β{a.ph_max}) "
f"vs {b.name} ({b.ph_min}β{b.ph_max})"
)
elif ph_hi - ph_lo < 1.0:
score -= 8
issues.append(f"Narrow shared pH window ({ph_lo:.1f}β{ph_hi:.1f}) β tight pH control needed")
# ββ 5. HLB delta penalty ββββββββββββββββββββββββββββββββββββββββββββββ
hlb_delta = abs(a.hlb - b.hlb)
if hlb_delta > 8:
score -= int(hlb_delta * 2)
issues.append(f"HLB mismatch ({a.hlb} vs {b.hlb}) β phase separation risk")
elif hlb_delta > 4:
score -= int(hlb_delta * 0.8)
# ββ 6. Concentration-weighted boost for low-concentration ingredients β
# High-risk ingredients at <2% lower actual impact
min_pct = min(pct_a, pct_b)
if min_pct < 2.0 and score < 60:
score = int(score * (1 + (2.0 - min_pct) * 0.08))
score = max(0, min(100, score))
hlb_delta = round(abs(a.hlb - b.hlb), 1)
if score >= 80:
risk = "low"
elif score >= 60:
risk = "medium"
elif score >= 35:
risk = "high"
else:
risk = "critical"
return CompatPair(
ingredient_a=a.name,
ingredient_b=b.name,
score=score,
risk_level=risk,
issues=issues,
hlb_delta=hlb_delta,
)
# ββ Public interface βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def compute_compatibility(
blend: Dict[str, float],
db: pd.DataFrame,
) -> CompatibilityReport:
"""
Compute full pairwise compatibility matrix for a blend.
blend: {ingredient_name: weight_percent, ...}
db: ingredients DataFrame with SMILES, Function columns
"""
if not blend:
return CompatibilityReport(
success=False, overall_score=0, risk_summary="Empty blend",
pairs=[], critical_pairs=[], ph_window=(5.0, 7.0),
hlb_blend=0.0, emulsion_type="n/a",
descriptors=[], warnings=[],
error_msg="No ingredients provided."
)
idx = db.set_index("Ingredient")
names = [n for n in blend if n in idx.index]
missing = [n for n in blend if n not in idx.index]
warnings = []
if missing:
warnings.append(f"Ingredients not in DB (skipped): {', '.join(missing)}")
descriptors = [_build_descriptor(idx.loc[n]) for n in names]
desc_map = {d.name: d for d in descriptors}
# Pairwise scoring
pairs: List[CompatPair] = []
total_pct = sum(blend.get(n, 0) for n in names)
for i in range(len(names)):
for j in range(i + 1, len(names)):
na, nb = names[i], names[j]
pair = _score_pair(
desc_map[na], desc_map[nb],
blend.get(na, 0), blend.get(nb, 0)
)
pairs.append(pair)
critical_pairs = [p for p in pairs if p.risk_level == "critical"]
high_pairs = [p for p in pairs if p.risk_level == "high"]
# Overall score β weight by pair concentration product
if pairs:
weights = []
scores_w = []
for p in pairs:
wt = (blend.get(p.ingredient_a, 1) * blend.get(p.ingredient_b, 1)) ** 0.5
weights.append(wt)
scores_w.append(p.score * wt)
overall = int(sum(scores_w) / max(sum(weights), 1e-9))
else:
overall = 100
# Blend pH window (intersection of all windows)
ph_lo = max(d.ph_min for d in descriptors)
ph_hi = min(d.ph_max for d in descriptors)
if ph_hi < ph_lo:
ph_lo, ph_hi = ph_lo, ph_lo + 0.5
warnings.append("pH windows of all ingredients don't share common range β formulation instability likely")
# Weighted HLB
norm = total_pct or 1
hlb_blend = round(
sum(desc_map[n].hlb * blend.get(n, 0) / norm for n in names), 1
)
# Emulsion type from HLB
if hlb_blend < 6:
emulsion_type = "w/o (water-in-oil)"
elif hlb_blend > 11:
emulsion_type = "o/w (oil-in-water)"
elif 6 <= hlb_blend <= 11:
emulsion_type = "transitional / bi-continuous"
else:
emulsion_type = "not applicable"
# Risk summary
if critical_pairs:
risk_summary = f"β CRITICAL β {len(critical_pairs)} critical incompatibilit{'y' if len(critical_pairs)==1 else 'ies'} detected"
elif high_pairs:
risk_summary = f"β οΈ HIGH RISK β {len(high_pairs)} high-risk pair(s), formulation review required"
elif overall >= 80:
risk_summary = "β
COMPATIBLE β blend is chemically stable across all pairs"
else:
risk_summary = f"π‘ MODERATE β some caution needed (score {overall}/100)"
return CompatibilityReport(
success=True,
overall_score=overall,
risk_summary=risk_summary,
pairs=sorted(pairs, key=lambda p: p.score),
critical_pairs=critical_pairs,
ph_window=(round(ph_lo, 1), round(ph_hi, 1)),
hlb_blend=hlb_blend,
emulsion_type=emulsion_type,
descriptors=descriptors,
warnings=warnings,
)
|