Metadata-Version: 2.4
Name: hemoinfo
Version: 0.1.0
Summary: Offline-first cheminformatics profiling engine built on RDKit.
Author: HemoInfo
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: rdkit>=2023.9
Requires-Dist: thermo>=0.4.2
Requires-Dist: chemicals>=1.3.3
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"

# HemoInfo Chem Engine

HemoInfo is an offline-first cheminformatics engine for validation, descriptor
calculation, physicochemical profiling, transparent drug-likeness heuristics,
and conformer generation.

The first implementation uses RDKit for molecular graph handling, ETKDGv3
embedding, and UFF-first 3D pre-optimization with 2000 iterations. xTB and
CREST are supported as optional command-line backends when their executables are
available in `PATH` or passed explicitly.

## CLI

```powershell
hemoinfo profile molecules.smi --out results.json
hemoinfo profile molecules.sdf --out results.csv
hemoinfo profile surfactants.smi --application-profile industrial_surfactant --out surfactants.json
hemoinfo profile chameleons.smi --accuracy-mode high_accuracy --solvent water --solvent-model alpb --out high-accuracy.json
hemoinfo validate molecules.smi --strict-stereo
hemoinfo conformers molecules.smi --n 20 --backend rdkit --out confs.json
hemoinfo conformers molecules.smi --n 20 --backend staged --xtb-solvent water --out staged.json
hemoinfo conformers molecules.smi --n 50 --backend crest --crest-solvent water --out crest.json
hemoinfo conformers molecules.smi --n 10 --backend xtb --xtb-solvent water --xtb-solvent-model alpb --out xtb-water.json
hemoinfo graph molecules.smi --out graph.json
hemoinfo quantum molecules.smi --solvent water --out quantum.json
hemoinfo electronic molecules.smi --backend orca_export --out-dir orca_jobs --out electronic.json
hemoinfo electronic molecules.smi --backend std_xtb --stda-path stda --out stda.json
hemoinfo physical molecules.smi --engine thermo_chemicals --out thermo.json
hemoinfo physical molecules.smi --engine opera_comptox --out opera.json
hemoinfo physical molecules.smi --engine all --run-opera --out physical-with-opera.json
hemoinfo gnn molecules.smi --model-path chemprop_model --with-opera-consensus --out gnn.json
hemoinfo render molecules.smi --out-dir visuals --conformers 10 --backend xtb --manifest visuals.json
```

The shorter `heminfo` alias is also installed for the CLI:

```powershell
heminfo profile molecules.smi --out results.json
```

## Desktop GUI

Install the package in editable mode, then launch the local desktop interface:

```powershell
python -m pip install -e .
hemoinfo-gui
```

The alias also works:

```powershell
heminfo-gui
```

The GUI is aimed at non-specialists: paste a SMILES string or load an SDF/SMILES
file, press **Analyze**, and read the simple summary first. Technical JSON,
warnings, environment fate, liquid/phase handling, reactivity/stability,
3D conformers, xTB quantum details, and SVG visual reports are in separate
tabs/buttons.

Long external engines are opt-in in the GUI. Enable **xTB quantum** for xTB
single-point calculations, or **OPERA/EPA** to run the local OPERA/EPA CompTox
CLI in the background. OPERA results such as `opera_boiling_point`,
`opera_logp`, `opera_water_solubility_logs`, `opera_pka_acid`, and
`opera_logd7_4` appear in the **Physical engines** tab and Technical JSON.
With OPERA unchecked, the GUI only reports OPERA readiness, for example
`ready_not_executed`, so routine analysis stays responsive.

## Python API

```python
from rdkit import Chem
from hemoinfo import (
    analyze_molecule,
    compute_electronic_spectrum,
    compute_chemprop_predictions,
    compute_opera_comptox_properties,
    compute_thermo_chemicals_properties,
    ElectronicOptions,
    ChempropOptions,
    generate_conformers,
)

smiles = "CC(=O)Oc1ccccc1C(=O)O"
mol = Chem.MolFromSmiles(smiles)
report = analyze_molecule(smiles)
ensemble = generate_conformers(mol, n=20)
orca_inputs = compute_electronic_spectrum(mol, ElectronicOptions(backend="orca_export", output_dir="orca_jobs"))
gnn_report = compute_chemprop_predictions(mol, ChempropOptions(model_path="chemprop_model"))
thermo_report = compute_thermo_chemicals_properties(mol)
opera_report = compute_opera_comptox_properties(mol, opera_path="OPERA.exe")
```

The project intentionally reports method names, units, warnings, confidence,
and out-of-domain flags. Local pKa, LogD7.4, and solubility values are estimates,
not replacements for validated experimental or proprietary prediction systems.

## Added graphical and realistic calculations

- Molecular graph descriptors: Wiener index, diameter, radius, graph density,
  degree sequence, cyclomatic number, ring topology, Balaban J, BertzCT,
  Hall-Kier alpha, kappa, chi, spiro/bridgehead counts, and Labute ASA.
- Visual reports: 2D molecule SVG/PNG, Gasteiger charge-map SVG,
  physicochemical radar SVG, pharmacophore 2D/3D SVG, and conformer
  relative-energy SVG.
- Spectral plots: visual report folders include rule-based IR, UV/Vis, mass
  spectrum, and 1H NMR SVG charts derived from HemoInfo spectral hints.
- xTB single-point profile: total energy, gradient norm, HOMO/LUMO,
  HOMO-LUMO gap, Fermi level, total charge, dipole moment, polarizability,
  and atom-level printed charge/covalent coordination values.
- Local ADMET heuristics: BBB permeability, GI absorption, P-gp substrate risk,
  CYP inhibition alerts, hERG risk, and plasma protein binding tendency.
- Pharmacophore features: H-bond donors, H-bond acceptors, hydrophobic centers,
  aromatic centers, and positive/negative ionizable centers.
- Conformer ensemble analysis: RMSD matrix, diverse conformer subset,
  low-energy windows, strain-energy summary, and intramolecular H-bond
  persistence across conformers.
- Staged conformer backend: `--backend staged` runs a large RDKit ETKDGv3/UFF
  pool, selects a low-energy/diverse subset for xTB refinement, and attempts
  CREST only for flexible/high-risk cases where the extra conformer search is
  justified.
- pH microstate profile: RDKit tautomer enumeration, ranked tautomer candidates,
  independent Henderson-Hasselbalch protonation states at pH 7.4, expected net
  charge, neutral/unionized fraction, and microstate-aware local LogD7.4.
- CREST conformer backend: optional GFN2-xTB metadynamics ensemble search for
  flexible amphiphiles and "molecular chameleons"; missing/non-converged CREST
  runs fall back to the RDKit ensemble with explicit diagnostics.
- Electronic-spectrum backends: optional sTD-xTB/sTDA transition parsing and
  ORCA `.inp` export for user-controlled r2SCAN-3c or TDDFT validation on the
  top conformers.
- GNN/QSAR consensus: optional Chemprop predictions from a user-supplied model
  checkpoint and arithmetic OPERA/Chemprop consensus for overlapping numeric
  endpoints.
- 3D descriptor panel: ensemble-aware RDKit PMI1/PMI2/PMI3, NPR1/NPR2,
  radius of gyration, inertial shape factor, asphericity, eccentricity,
  spherocity index, PBF, and persistent strong intramolecular H-bond shielding
  calculated over the shared RDKit/xTB/CREST conformer engine.
- Blood-pH LogD screen: `LogD7.4_blood_pH` uses pH 7.4 plus the same
  ionization model as local LogD and applies an intramolecular H-bond
  exposed-polarity correction when a strong persistent 3D H-bond is detected.
  It is explicitly not reported as an experimental whole-blood/plasma partition
  coefficient.
- Synthetic accessibility: RDKit SA score, ring complexity, stereochemical
  complexity, and a plain-language synthesis difficulty label.
- Spectral hints: rule-based IR bands, UV/Vis region, exact/adduct MS peaks,
  and approximate 1H NMR regions.
- Surface activity and formulation screening: HLB index by Davies group
  contributions, Griffin-style hydrophilic mass-fraction cross-check,
  surfactant-like amphiphile detection, Klevens-style CMC estimate, and
  micellization free energy from `Delta G = RT ln(X_CMC)`.
- Interface/formulation geometry: minimum-energy 3D conformer footprint
  (`cross_sectional_area`) as a van-der-Waals inflated projected convex hull,
  using a polar-head/hydrophobic-tail axis when detected.
- Foam screening: empirical `foam_stability_score` and class from hydrophobic
  tail length, polar head type, HLB range, and polar-head charge.
- Physical engines: separate RDKit/local, `thermo`/`chemicals`, OPERA adapter,
  surface/interfacial, thermodynamics/phase, and ionicity/electrostatics
  sections. Outputs include boiling point, melting point, density, molar
  volume, vapor pressure, surface tension, critical constants, phase label,
  packing parameter, Gasteiger charge span, dipole estimate, polarizability,
  and OPERA availability/status.
- Environmental fate profile: OPERA/EPA endpoints for LogBCF, ready
  biodegradability, biodegradation half-life, LogKoc, LogKoa, Henry-law
  constant, atmospheric OH-rate, and HPLC retention time when OPERA is enabled;
  otherwise transparent low-confidence fallback screens from RDKit cLogP and
  surfactant structural classes.
- Extended liquid/phase handling: `thermo.Chemical` values for liquid/gas
  viscosity, kinematic viscosity, refractive index, flash point, autoignition,
  flammability limits, heat capacities, thermal conductivity, enthalpy of
  vaporization, Hildebrand solubility parameter, dielectric constant, vapor
  pressure, surface tension, and practical handling classes.
- Reactivity/stability screening: RDKit SMARTS alerts for hydrolysis-prone
  acyl/sulfonyl/carbonyl motifs, oxidation-prone aldehydes/phenols/anilines/
  sulfur/alkenes, photolabile chromophores, peroxide-former motifs, and
  reactive electrophiles such as epoxides, aziridines, isocyanates, alkyl
  halides, Michael acceptors, and vinyl sulfones.
- Skin safety profile: Potts-Guy skin permeability `logKp`, permeability class,
  structural alerts for reactive sensitization/irritation motifs, and an
  integrated `favorable_screen / caution / elevated_concern` triage label.
- Application profiles: `pharmaceutical` keeps oral drug-likeness/ADMET rule
  assessments active; `cosmetic_formulation` and `industrial_surfactant` keep
  QED, MW, Lipinski/Veber/Ghose/Egan/Muegge, GI absorption, and BBB values as
  informational descriptors instead of treating them as bad non-pharma alerts.

## Scientific traceability

HemoInfo reports method names, units, confidence labels, and warnings next to
each estimate. The new surface/skin calculations are meant to be scientifically
traceable, not magically exact:

- HLB uses the published Griffin/Davies hydrophilic-lipophilic balance ideas.
  Davies HLB is implemented as `7 + sum(hydrophilic group numbers) -
  0.475 * n_lipophilic_groups`; Griffin-style HLB is approximated as
  `20 * hydrophilic mass fraction`.
- Micellization uses a Klevens-style alkyl-chain relation to estimate CMC only
  for single-tail amphiphiles, then computes the standard free-energy screen as
  `Delta G_mic = R*T*ln(X_CMC)`, where `X_CMC = CMC / (CMC + 55.5)`.
- Skin permeability uses the Potts-Guy correlation
  `logKp = 0.71*cLogP - 0.0061*MW - 2.72`.
- Skin safety alerts are transparent SMARTS structural alerts. They are useful
  for triage and documentation, but they are not regulatory toxicology models.
- Michael-acceptor sensitization alerts use curated alpha,beta-unsaturated
  electrophile SMARTS. Beta-aryl Michael acceptors are suppressed when the
  adjacent aromatic ring has donor O/N/S substitution, and the suppressed match
  is retained in technical JSON.
- Ionic surfactant irritation alerts require a single-tail amphiphile with an
  unbalanced anionic or cationic polar head. Close, formally balanced
  zwitterions such as betaines/sulfobetaines are excluded.
- Environmental fate uses OPERA/EPA CompTox predictions when the local OPERA
  executable is explicitly run. PBT-style labels use documented screening
  thresholds such as BCF 2000/5000 and biodegradation half-life checks, but
  HemoInfo reports them as screening diagnostics, not regulatory conclusions.
- Extended liquid properties come from the open-source `thermo`/`chemicals`
  stack when a compound is recognized by its local identifiers; unavailable
  values remain `out_of_domain` or fall back to explicitly labelled
  Joback/Fedors/Bondi estimates. If Bondi fragment-table volume fails,
  HemoInfo can use an xTB-optimized conformer and deterministic Monte Carlo
  integration of intersecting Bondi VdW spheres to report a geometric fallback
  molecular volume.
- Reactivity/stability uses structural-alert chemistry only. It is
  reproducible and auditable through SMARTS patterns, but it does not model
  pH, water activity, oxygen, light intensity, catalysts, impurities,
  formulation matrix, or reaction kinetics.
- Applicability guards are intentionally conservative:
  - RDKit tautomer scores are used as deterministic ranking priors for local
    microstate enumeration; they are not treated as quantum energies or
    experimental tautomer populations;
  - separated zwitterions are flagged as high-dipole charge-transfer-artifact
    risks, and xTB HOMO-LUMO gaps are not converted into UV/Vis chromophore
    transitions for those structures;
  - quaternary ammonium/internal-salt centers are not reported as basic pKa
    sites in pH 1-14, and OPERA `pKa_b` values are suppressed when no local
    protonatable basic center is detected;
  - close charge-balanced zwitterionic heads get a Davies HLB internal-salt
    correction instead of summing cationic and anionic groups as independent
    ionic heads;
  - Joback is not applied to charged or zwitterionic structures;
  - disconnected neutral dimers/aggregates do not receive cLogP, LogD, or ESOL
    solubility as if they were one condensed-phase molecule;
  - 3D-dependent estimates use the shared conformer engine with Boltzmann
    weighting where practical. RDKit/UFF is the fast baseline; high-accuracy
    mode switches the profile toward CREST/GFN2-xTB with implicit
    solvent by default because force-field distance geometry can miss relevant
    folded conformers;
  - local RDKit/ESOL/LogD calculations do not use PCM/COSMO/ALPB continuum
    solvent. xTB and CREST conformer workflows use ALPB/GBSA only when solvent
    options are set, for example `--solvent water`, `--xtb-solvent water`, or
    `--crest-solvent water`;
  - continuum solvent models still do not include specific water-solute
    hydrogen bonds. HemoInfo reports this explicitly and only models persistent
    intramolecular H-bonds as an exposed-polarity shielding screen;
  - polymer-like repeat-unit inputs are not extrapolated to polymer-chain
    properties;
  - formula molecular weight is explicitly not a GPC/SEC molecular weight,
    because SEC/GPC requires calibration against a chemically similar standard;
  - achiral scalar properties are not split for enantiomers unless a chiral
    environment/model is introduced, while diastereomer/E-Z stereochemistry is
    preserved for 3D-sensitive workflows;
  - non-counterion mixtures are rejected from the single-molecule profile, and
    HemoInfo does not apply Raoult-law ideal-mixture assumptions to nonideal
    binary mixtures.
- Transition-metal spin-state energetics are not silently computed with a
  default spin/basis choice. The xTB command stops by default for transition
  metals; explicit opt-in requires the user to provide the unpaired-electron
  count and still reports that high-spin/low-spin DFT comparisons need a
  validated functional/basis/ECP/dispersion/solvation protocol.

Useful references:

- OPERA/EPA CompTox overview:
  https://ntp.niehs.nih.gov/whatwestudy/niceatm/comptox/ct-opera/opera
- OPERA open-source command-line project and model outputs:
  https://github.com/kmansouri/OPERA
- OPERA QSAR model publication:
  https://link.springer.com/article/10.1186/s13321-018-0263-1
- `thermo` documentation:
  https://thermo.readthedocs.io/
- `chemicals` documentation:
  https://chemicals.readthedocs.io/
- OECD Test Guideline 301 ready biodegradability:
  https://www.oecd.org/en/publications/1992/07/test-no-301-ready-biodegradability_g1gh2913.html
- ECHA Chapter R.11 PBT/vPvB assessment guidance:
  https://echa.europa.eu/documents/10162/13632/information_requirements_r11_en.pdf/a8cce23f-a65a-46d2-ac68-92fee1f9e54f
- HLB formulas and Davies group numbers:
  https://en.wikipedia.org/wiki/Hydrophilic-lipophilic_balance
- CMC definition and SDS reference CMC values:
  https://en.wikipedia.org/wiki/Critical_micelle_concentration
- Klevens-style CMC chain-length relation:
  https://link.springer.com/article/10.1007/s00706-020-02581-x
- Micellization free energy via `Delta G = RT ln X_CMC`:
  https://pmc.ncbi.nlm.nih.gov/articles/PMC8872345/
- Potts-Guy skin permeability correlation context:
  https://www.nature.com/articles/s41597-022-01698-4
- CREST conformer/rotamer ensemble sampling:
  https://crest-lab.github.io/crest-docs/
- sTDA/sTD-xTB project:
  https://github.com/grimme-lab/stda
- ORCA input and method documentation:
  https://www.faccts.de/docs/orca/
- Chemprop documentation:
  https://chemprop.readthedocs.io/

## CREST, Electronic Spectroscopy, and GNN Consensus

CREST is the recommended optional conformer backend for highly flexible
surfactants, amphiphiles, and structures where hidden intramolecular hydrogen
bonds can control the exposed polarity. HemoInfo still generates an RDKit start
geometry, then calls CREST/GFN2-xTB when requested:

```powershell
heminfo conformers molecules.smi --backend crest --n 50 --crest-solvent water --crest-solvent-model gbsa --out crest.json
```

If CREST is not installed or fails to converge, the result keeps the RDKit
ensemble and adds `CREST_NOT_FOUND`, `CREST_TIMEOUT`, or `CREST_FAILED`
diagnostics instead of silently pretending the metadynamics search ran.

For electronic spectra, HemoInfo separates two reproducible paths:

- `std_xtb` runs an installed sTD-xTB/sTDA executable and parses transition
  energies, wavelengths, and oscillator strengths.
- `orca_export` writes ORCA input files for the top conformers. ORCA is not
  bundled or run automatically, because licensing, spin state, functional,
  basis/ECP, dispersion, and solvent choices must be validated for the system.

```powershell
heminfo electronic molecules.smi --backend std_xtb --stda-path stda --out stda.json
heminfo electronic molecules.smi --backend orca_export --orca-functional r2SCAN-3c --out-dir orca_jobs --out orca.json
heminfo electronic molecules.smi --backend orca_export --orca-template tddft --nroots 20 --solvent water --out-dir orca_tddft
```

Chemprop support is an adapter, not a bundled black-box ADMET oracle. You must
provide a trained Chemprop checkpoint/model path. When OPERA is also available,
HemoInfo can compute an auditable consensus for overlapping numeric endpoint
names:

```powershell
heminfo gnn molecules.smi --model-path chemprop_model --out chemprop.json
heminfo gnn molecules.smi --model-path chemprop_model --with-opera-consensus --out gnn-opera.json
```

The consensus is a transparent arithmetic average of OPERA classical QSAR and
Chemprop GNN predictions; it is useful for disagreement screening, not a claim
of validated experimental accuracy without endpoint-specific calibration.

### Local Windows/WSL engine wiring

On this workstation, Linux-first engines are exposed to the Windows GUI/CLI via
small wrappers in the Python user `Scripts` directory:

- `xtb.cmd` -> WSL Ubuntu `~/.local/share/hemoinfo-chem/bin/xtb`
- `crest.cmd` -> WSL Ubuntu `~/.local/share/hemoinfo-chem/bin/crest`
- `stda.cmd` / `std2.cmd` -> WSL Ubuntu `~/.local/share/hemoinfo-chem/bin/std2`
- `chemprop.exe` is installed as the native Chemprop v2 CLI; `chemprop_predict.cmd`
  is only a compatibility alias to `chemprop predict`.

ORCA is intentionally not bundled. Install ORCA from the official FACCTs/ORCA
download after accepting its license, then either add `orca.exe` to `PATH` or
set `ORCA_PATH`. HemoInfo will show `orca: ok` and can continue exporting ORCA
input files with `hemoinfo electronic --backend orca_export`.

## External Physical Engines

`thermo` and `chemicals` are package dependencies and are used locally. For
known compounds, `thermo.Chemical` provides database/model-backed values. For
arbitrary small molecules, HemoInfo falls back to transparent estimates such as
Joback, Fedors/Bondi, RDKit volume, and Clausius-Clapeyron vapor pressure from
Joback boiling point/enthalpy of vaporization.

OPERA/EPA CompTox is treated as an optional external command-line backend.
HemoInfo auto-detects standard Windows installs such as
`C:\Program Files\OPERA\application\OPERA.exe`; `OPERA_PATH` or `OPERA_CLI` can
still be used to point to a custom executable. It also adds MATLAB Runtime v912
and the bundled OPERA/KNIME Java runtime to the child-process `PATH` when
running OPERA, without changing the system PATH.

`opera_comptox.status` meanings:

- `not_installed`: no real OPERA executable was found.
- `runtime_missing`: OPERA was found, but MATLAB Runtime v912/R2022a was not visible.
- `java_missing`: OPERA and MATLAB Runtime were found, but Java for PaDEL descriptors was not visible.
- `ready_not_executed`: OPERA, MATLAB Runtime, and Java were found; the normal profile did not run the slower external engine.
- `ok`: OPERA CLI ran and HemoInfo parsed its prediction CSV.

The explicit adapter runs OPERA by default:

The physical backends are also exposed as explicit adapters:

```powershell
heminfo physical molecules.smi --engine thermo_chemicals --out thermo.json
heminfo physical molecules.smi --engine opera_comptox --out opera.json
heminfo physical molecules.smi --engine opera_comptox --opera-endpoints BP logP WS pKa logD --out opera.json
```

```python
from hemoinfo import compute_thermo_chemicals_properties, compute_opera_comptox_properties

thermo_report = compute_thermo_chemicals_properties(mol)
opera_report = compute_opera_comptox_properties(mol, opera_path="OPERA.exe")
```

`thermo_chemicals` runs local `thermo`/`chemicals` lookups and transparent
Joback/Fedors/Bondi fallbacks. If Bondi fragmentation fails, the Bondi volume
path attempts a hard fallback through an xTB conformer and Monte Carlo
sphere-union VdW volume instead of silently relying on fixed fragment tables.
If `thermo.Chemical` does not recognize a molecule but fallback estimates are available, HemoInfo reports
`thermo_chemicals.status = partial_ok` and keeps the database lookup status
separate. `opera_comptox` resolves OPERA availability, runs explicit CLI
requests, parses OPERA prediction CSV columns such as BP, LogP, LogWS, pKa, and
LogD7.4, and keeps OPERA output separate from RDKit/local estimates.
