Chemistry

Chemistry — `.hc`

Write chemistry as a rewriting system. Reactions are laws the build balances, syntheses are theorems it establishes, and every claim is checked by the proof kernel.

A .hc file is chemistry written the way Hilbert writes mathematics. A reaction rewrites a mixture exactly as a law rewrites a term, so the vocabulary is the image of Hilbert’s own:

.hc is, in Hilbert the build
element, substance a constant, a definition reads the periodic table and binds names to formulas
reaction a law balances it — a reaction that cannot be balanced does not build
network { … }, organic { … }, inorganic { … } a model groups reactions under one generated class, and records the kernel
synthesis … by [steps] a theorem … by rewrite [laws] composes the target from the steps, as a route or a Hess cycle
analysis … a theorem decided by computation takes a substance apart by a functor: atoms, charge, molar mass, amounts

Conservation is not a rule you write: atoms and charge are functors every reaction must send to an identity, and Hess’s law is the statement that ΔH preserves composition.

open Physis.Quantities
open Chemistry.Elements

substance methane ≔ CH₄(g)

reaction burning : CH₄ + O₂ → CO₂ + H₂O                      -- the build writes 1, 2, 1, 2

analysis weighed : molarMass(methane) = 16.043 g/mol within 0.001 g/mol
analysis watered : theoretical(burning, H₂O, 10 g CH₄) = 22.46 g within 0.01 g
Combustion.Methane.MolarMass;                                   // 0.016043 (kg/mol)
Combustion.Burning.Reactants.Select(t => t.Coefficient);        // 1, 2
Combustion.Burning.Theoretical(water, (methane, 0.623));        // kg of water

Formulas

Written Reads as
H₂O, H2O element symbols with counts — a capital letter starts a symbol, so CO is carbon and oxygen, Co cobalt
Ca(OH)₂, Ca(OH)2 a group with a count
CuSO₄·5H₂O a hydrate
SO₄²⁻, Na⁺, SO4^2- a charge
e⁻ the electron: charge −1, no atoms
H₂O(l), (s), (g), (aq) a state
¹³CH₄, ²H₂O an isotope, weighed by its own mass
2H₂O, (1/2)O₂ a coefficient in a reaction
methane a substance’s name, wherever its formula may stand

A formula starts with a capital letter; a name starts in lower case. The atomic weights are the IUPAC CIAAW 2021 abridged standard atomic weights, declared with their sources in Chemistry.Elements.

Reactions

The build writes one row per element and one for charge, one column per species, and finds the coefficients as the nullspace of that matrix in exact fractions — never floating point.

  • Nothing written: the smallest positive integers (C₈H₁₈ + O₂ → CO₂ + H₂O is 2, 25, 16, 18).
  • Some written: they are kept, and the rest are solved around them.
  • per X: X’s coefficient is 1 and the rest may be fractions — H₂ + O₂ → H₂O per H₂O is 1, ½, 1, a formation reaction per mole of product.
  • ⇌ marks a reaction reversible; e⁻ on either side makes it a half-reaction.

The coefficients are the witness the proof kernel checks: one identity per element and one for charge.

Syntheses

A synthesis claims Σ λᵢ·stepᵢ = target, over species that include their state — so H₂O(l) and H₂O(g) are different, and a Hess cycle is honest about phase.

reaction co2_formation : C(s) + O₂(g) → CO₂(g)
reaction water_formation : H₂(g) + O₂(g) → H₂O(l) per H₂O
reaction methane_formation : C(s) + H₂(g) → CH₄(g) per CH₄

synthesis burning : CH₄(g) + 2O₂(g) → CO₂(g) + 2H₂O(l) by [co2_formation, 2·water_formation, −methane_formation]
synthesis solved : CH₄(g) + 2O₂(g) → CO₂(g) + 2H₂O(l) by [co2_formation, water_formation, methane_formation]
synthesis found : CH₄(g) + 2O₂(g) → CO₂(g) + 2H₂O(l)
  • Multipliers written (a bare step is 1, −x reads x backwards) are checked.
  • Steps named without multipliers are solved for.
  • No steps are searched for: every set of up to four reactions and established syntheses in scope, smallest first.
  • An established synthesis is usable as a step of another — a theorem used as a law.
  • Half-reactions combine with their electrons cancelled: MnO₄⁻ + 5Fe²⁺ + 8H⁺ → … is [reduction, 5·oxidation].

Analyses and amounts

Functor Answers
atoms(X) {Ca: 1, S: 1, O: 6, H: 4}
charge(X) a whole number
molarMass(X) a MolarMass, such as 16.043 g/mol
empirical(X) a formula (compositions compared, not spellings)
percent(X, E) the mass percent of element E
moles(m X), mass(n X) an Amount, a Mass
molarity(amount, V), dilution(c₁, V₁, V₂) a MolarConcentration
gasVolume(amount, T, P) a Volume, by the ideal gas law
extent(R, amounts…), limiting(R, amounts…) how far R runs; the reactant that runs out first
theoretical(R, P, amounts…), leftover(R, X, amounts…) the mass of product made; the mass of reactant left
percentYield(actual, theoretical) a number

An amount is a quantity and a species: 28 g N₂, 0.5 mol O₂, 100 mL 0.5 M HCl(aq). A reactant given no amount is in excess. Answers with a measure take within a tolerance in the same dimension. Everything is compared exactly, in SI.

Structures

A structure is a molecule as a graph, written in bond notation, SMILES or a MOL file:

structure ethanol ≔ CH₃−CH₂−OH
structure benzene ≔ CH[1]=CH−CH=CH−CH=CH[1]
structure alanine ≔ smiles "C[C@@H](C(=O)O)N"
structure caffeine ≔ mol "caffeine.mol"

A group is one heavy atom with its hydrogens (CH₃, OH, NH₂), bonds are −, =, ≡, a branch is ( … ), [n] opens and closes a ring, * is a polymer’s attachment point, and R, R1 are R-groups for transformations. A substance and a structure of one name are one species, and the build proves they are made of the same atoms (CH0301).

Over a structure: configuration(E), period, group, block, valenceElectrons, formalCharge(X, i), lonePairs, octet, bondOrder(X, i, j), resonance, stericNumber, shape, angle, hybridization, bondPolarity, polar, moBondOrder, moUnpaired, magnetism, piElectrons, aromatic, delocalization, huckelGap, saturated, built(X, g₁, …), sameStructure, smiles. Atoms are addressed by their position among the groups written.

Data

Every number a functor reads is a datum with its source:

datum formationEnthalpy(H₂O(l)) = −285.83 kJ/mol source "CODATA Key Values for Thermodynamics"
datum pKa(CH₃COOH) = 4.76 source "IUPAC Digitized pKa Dataset"
datum ionName(SO₄²⁻) = "sulfate" source "IUPAC Red Book 2005, Table IX"

A datum is keyed as an analysis asks for it, so formationEnthalpy(H₂O(l)) answers a reaction that wrote H₂O(l) and one that named water. A datum with no state answers a species in any state. The prelude carries elements, isotopes, atoms, thermodynamics, the inorganic ion catalogue, organic conformations, phases, nuclides and spectra.

Redox in solution

A redox equation is written as a chemist writes it, and the solution supplies the rest:

reaction permanganate : MnO₄⁻ + Fe²⁺ → Mn²⁺ + Fe³⁺ in acid
reaction chromite : CrO₂⁻ + ClO⁻ → CrO₄²⁻ + Cl⁻ in base

in acid lets the build add H⁺ and H₂O, in base OH⁻ and H₂O, and either may add e⁻ — which is what makes a half-reaction one. They are columns of the same exact nullspace every reaction is balanced by, so conservation of atoms and charge is still certified by the kernel; a species the equation did not need comes out zero and is dropped.

Thermodynamics and equilibrium

reactionEnthalpy(R) is a datum on R if there is one, else Σλ·ΔH over an established synthesis’s steps — Hess’s law as the functor — else Σν·ΔfH. Beside it: reactionEntropy, gibbs(R, T), spontaneity(R), crossover(R), equilibriumConstant(R, T), vantHoff(R, K₁, T₁, T₂), bondEstimate(R), atEquilibrium(X, [R₁, …], amounts…) and fraction(acid, i, pH).

reactionEnthalpy(R, T) and reactionEntropy(R, T) carry ΔH and ΔS to another temperature by Kirchhoff’s law from heatCapacity data, and gibbs and equilibriumConstant follow them there. In solution, ionicStrength(amounts…), activityCoefficient(ion, I) (Davies) and ionActivity(X, c, I) say what an ion really is at a concentration.

Kinetics

react Ozone {
  step decay : 2O₃ → 3O₂ rate 0.01 M⁻¹·s⁻¹
  start O₃ = 1 mM
  integrate rk45 tolerance 1e-10
  stop when t ≥ 100 s
}

A mechanism is a claim the build can check: declare intermediate N₂O₂ and steadyStateRate(R, X) holds every intermediate at d[X]/dt = 0 — a catalyst too, conserved by the stoichiometry’s own left nullspace — while reactionOrder(R, X, A) reports ∂ln(rate)/∂ln[A]. 2NO + O₂ → 2NO₂ through N₂O₂ comes out second order in NO, and E + S ⇌ ES → E + P comes out Michaelis–Menten, saturation and all.

A react block lowers to a Physis simulate: species become states (or fields under grid), each law is Σ νᵣ·rateᵣ by mass action, and the generated class, its Run, schemes, stops and events are Physis’s. ⇌ … rate kf back kr, arrhenius A Ea with temperature, adiabatic C with each step’s enthalpy, feed X rate F from c and diffusion X D are all laws the build writes. A stochastic block with a volume and a seed becomes Gillespie’s direct method over molecule counts instead, as a MLambda.Hilbert.Chemistry.Gillespie with Run and Ensemble.

The two kernels

organic Name { … } and inorganic Name { … } are networks under a kernel, and each kernel has its own functors.

Inorganic: oxidationState(X, E) by rule (F, group 1, group 2, H, O, the halogens, the rest solved by charge, so Fe₃O₄ is 8/3), oxidized, reduced, electronsTransferred, ionic(cation, anion), nameOf(X) and formulaOf("name") over the ion catalogue (Stock numbers, Greek prefixes, acids, hydrates), pH(amount), bufferPH, titrationPH, solubility, precipitates, cellPotential, cellGibbs, cellK, nernst, metalOxidation, dElectrons, spin, unpairedElectrons, cfse, magneticMoment, coordinationGeometry, packing, atomsPerCell, cellDensity, edgeFromRadius, coordinationByRatio, kapustinskii.

Organic: groups(X), nameOf/structureOf (IUPAC 2013 for acyclic and monocyclic hydrocarbons, alkenes, alkynes, alcohols, aldehydes, ketones and acids, with alkyl and halo substituents), isomers(CₙH₂ₙ₊₂), structuralIsomers, stereocentres, chirality(X, i) and alkeneGeometry(X, i, j) from SMILES marks, unsaturation, apply(T, [inputs]) and retrosynthesis(X) over transform declarations, reactionClass(R), torsionEnergy, ringStrain, equatorialFraction, repeatMass, degreeOfPolymerisation, carothers, dispersity, growth.

A transformation is graph rewriting with R-groups binding the rest of a molecule:

transform acetylation : R−OH + CH₃−C(=O)−O−C(=O)−CH₃ → R−O−C(=O)−CH₃ + CH₃−C(=O)−OH

Phases, nuclei and spectra

intermolecular(X), vaporPressure(X, T), boilingPoint(X, P), phaseRule(C, P), phaseAt(X, T, P), raoult, henry, vantHoffFactor, boilingElevation, freezingDepression, osmoticPressure, miscible read the phase data.

A nuclear equation is balanced by nucleons and protons, and states its own coefficients:

nuclear fission : ²³⁵U + n → ¹⁴¹Ba + ⁹²Kr + 3n

with nucleons, protons, qValue, massDefect, bindingEnergy, bindingPerNucleon, decayConstant, remaining, age and activity. Spectroscopy adds monoisotopicMass, nominalMass, isotopePattern, fragments, irBands, explainsIR, hSignals, cSignals, hIntegration, hMultiplicity, hShift, beerLambert, crystalFieldWavelength and determine(formula, hSignals, cSignals), which enumerates the structures a formula allows and keeps the one the spectra fit.

Diagnostics

code meaning
CH0001 an unknown element symbol (with a suggestion: CL → Cl)
CH0002 a malformed formula, or a coefficient or multiplier that is not a positive number
CH0003 a name bound twice
CH0004 a name that is no substance or reaction in scope
CH0005 a functor given the wrong arguments, or empirical of an ion
CH0006 a value or tolerance in the wrong dimension
CH0007 an isotope with no isotope declaration
CH0009 a false analysis, with the difference
CH0102 a reaction no coefficients balance
CH0103 a reaction that balances more than one way
CH0104 a species on the wrong side, or taking no part
CH0105 written coefficients that do not conserve
CH0106 a synthesis its steps do not reach, with what is left over
CH0107 a synthesis no set of up to four reactions composes
CH0108 a synthesis whose steps are dependent
CH0109 a synthesis reached only if states are ignored
CH0110 syntheses that use each other in a cycle
CH0111 an amount of a species that is not a reactant (or product)
CH0112 a reaction amount given no amount
CH0113 a .hc file whose class is named like another generated class
CH0301 a structure and its substance made of different atoms
CH0302 a malformed structure, SMILES or MOL file
CH0303 an atom index outside the structure
CH0304 no diatomic or no π system where one is needed
CH0401 a datum the functor needs is not in scope
CH0402 no equilibrium found, or a species in none of the reactions
CH0501 a step with no rate, or a stochastic step with a back
CH0502 a react missing its temperature, volume, grid or stop
CH0601 an oxidation state no rule fixes
CH0602 a compound the ion catalogue and the naming rules do not reach
CH0603 no coordination complex where one is needed
CH0701 a name or a structure outside the naming scope
CH0702 no stereo mark, or substituents that rank alike
CH0703 a transformation that does not apply, or no route
CH0801 phase data missing (reported as CH0401 against the datum)
CH0901 a nuclear equation that conserves neither nucleons nor protons
CH1001 none or several structures fit the spectra
CH0403 a heat capacity missing where Kirchhoff needs one
CH0404 an activity asked of something with no charge
CH0503 a steady state that does not settle, or an intermediate in no step