Spaces:
Sleeping
Sleeping
Download modules/compatibility.py from chemenovausa/OrbitChem: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/spaces/chemenovausa/OrbitChem/resolve/main/modules/compatibility.py
- Command line
-
hf download hf://spaces/chemenovausa/OrbitChem/modules/compatibility.py
-
curl -L -o compatibility.py https://huggingface.co/spaces/chemenovausa/OrbitChem/resolve/main/modules/compatibility.py
17.3 kB
| """ | |
| 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), | |
| } | |
| 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 | |
| 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| | |
| 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, | |
| ) | |