Computational chemistry, without the lab
Every lesson runs entirely in this tab. You start with a molecule written as text and turn it into numbers, train a model on 1,128 real measured solubilities and go looking for the compounds it gets wrong, then work out where the atoms actually sit, set them moving, and find out where the electrons are and where one molecule binds to another.
What is inside
No RDKit, no black box
The SMILES parser, ring perception, aromaticity
and every descriptor are written out in chem.js so you can read
them. They agree with reference software on 1,128 of 1,128 molecular weights
and 1,127 of 1,128 polar surface areas, and the handful that disagree are
named in the lessons.
Built for a class without a wet lab
Lessons 1 and 2 stand alone and take about a period each. Lessons 3 through 6 work best in order, because reading a model's errors only lands once you have watched your own model score well. Lesson 8 is worth two weeks.
Molecules as text
Chemistry software does not store pictures. It stores strings. SMILES writes a structure as one line of text, and any program can read that line back into atoms and bonds. Everything else in this lab starts here.
Type a molecule
The drawing updates as you type.
Structure
Aromatic rings carry the circle that textbooks use.
Or draw it
Pick a tool, then work on the canvas. Whatever you draw is turned back into SMILES and written into the box above, so the structure, the formula and every number up there follow your drawing as you make it.
The rules, all of them
SMILES has a small grammar. These eight rules cover almost everything you will meet in a school dataset.
C N O SOne letter per atom. Hydrogens fill the spare valences
on their own, so C means methane.CCCAtoms written in a row are bonded in a row. Propane.CC(C)CBrackets hang a branch off the atom before them.
2-methylpropane.C=C C#NAn equals sign is a double bond, a hash is a triple
bond. Ethene, then hydrogen cyanide.C1CCCCC1A matching pair of digits closes a ring.
Cyclohexane.c1ccccc1Lowercase marks an aromatic ring. Benzene.[NH4+] [O-]Square brackets spell out hydrogens and charge when
the defaults are wrong.[Na+].[Cl-]A full stop separates pieces that are not bonded.
Sodium chloride.What the parser saw
Every atom, with the hydrogens it worked out and the rings it belongs to.
Write these yourself
Any correct SMILES passes. The check compares the formula, ring count and aromatic ring count, so there is more than one right answer.
Numbers from a structure
A descriptor is a number you can compute from the structure alone, with no experiment. Count the oxygens, add up the atomic weights, measure how much of the surface is polar. These counts are the only thing the models in this lab ever see.
Molecule A
Molecule B
Side by side
Caffeine against tetradecane to start with. One dissolves in water, one does not, and the numbers say why before you know any thermodynamics.
Lipinski's rule of five
A rough filter from 1997 for whether a molecule could work as a pill you swallow. Breaking two or more rules is the warning sign.
Is this code right?
Fair question. The solubility file ships with descriptors computed by other software, so every molecule in it is a test case. Run on all 1 128:
Look at the data first
These are real measurements: 1 128 compounds whose water solubility somebody sat down and measured. Solubility is reported as log S, the base-10 logarithm of how many moles dissolve in a litre. Before fitting anything, find out what the numbers look like.
One descriptor against solubility
Pick a descriptor for the horizontal axis. Hover a point to see which compound it is.
How solubility is spread out
Counts of compounds per 0.5 log unit. The tail on the left is the trouble: those compounds barely dissolve at all.
Which descriptor tracks solubility best?
Correlation of each descriptor with log S across all 1 128 compounds. Click a row to put it on the scatter above.
Browse the compounds
Search by name or SMILES. Click a row to draw it.
One line through the data
The simplest model there is: pick one descriptor, draw the straight line that comes closest to every point, and read predictions off it. Least squares finds that line in one calculation. Gradient descent finds the same line by walking downhill, which is how every neural network is trained.
The fit
Walking downhill
Mean squared error after each step. The curve flattens when the line stops improving.
What the three numbers mean
R²The share of the variation the line explains. 1.0 is perfect,
0.0 is no better than always guessing the average, and a negative value means worse than
that.RMSERoot mean squared error, in log units. An RMSE of 1.0 means a
typical prediction is off by a factor of ten in concentration.MAEMean absolute error. Smaller than RMSE whenever a few compounds
are badly wrong, so comparing the two tells you whether the errors are even or
lumpy.Hold some data back
A model scored on the data it was fitted to will flatter you. Keep part of the dataset aside, fit on the rest, and score on the part the model never saw. That gap between the two scores is the whole reason machine learning has a method at all.
Choose the features
Every box you tick is one more column the model may use.
Predicted against measured
Test compounds only. The diagonal is a perfect prediction.
What the model leans on
Weight given to each feature, after putting them all on the same scale. Blue pushes solubility up, red pushes it down.
Try this
- Tick every feature and set λ to 0. The fit falls apart, and the warning above explains why: molecular weight, heavy atoms and carbon count are almost the same column three times over, so there is no single best answer.
- Raise λ to 1. Nearly all the accuracy comes back. The penalty breaks the tie by preferring small weights.
- Push λ to 1000. Both scores sink together, because now the penalty matters more than the data.
- Change the seed a few times with a 20% test share. Watch how much the test score moves on its own. That spread is why one split is never enough evidence.
Read the errors
An average score hides everything interesting. The compounds a model gets badly wrong are usually wrong for a chemical reason, and finding that reason is the actual science. Predictions here are out-of-fold, so no compound was in the data used to predict it.
Errors against prediction
Residual is measured minus predicted. Above zero the model called a compound less soluble than it really is.
The worst twenty
Click a row to draw the structure.
Structure
Your notebook
Three questions to answer from what you see. Your text stays in this browser, so copy it out when you are done.
A yes or no answer
Tox21 asked whether each of 7 980 compounds sets off a particular biological alarm. The answer is yes or no, not a number, and the yeses are rare. That changes which scores are worth reading, and accuracy stops being one of them.
Where the threshold falls
The model gives each compound a probability. You decide how high is high enough to call it active, and that decision has a cost either way.
ROC curve
Every threshold at once. The diagonal is random guessing, and the area underneath is the one score that does not depend on where you put the line.
Try this
- Train on NR-PPAR-gamma, where under 3% of compounds are active. Compare the model's accuracy with the accuracy of answering "inactive" every single time.
- Drag the threshold down to 0.2. Recall climbs, precision collapses. Decide which you would want if this were a screen for drinking water.
- Train the same features on SR-MMP, where 16% are active, and see how much easier the job becomes.
A molecule in three dimensions
A SMILES string says what is bonded to what. It says nothing about where the atoms are, and almost every physical property depends on that. Here we work out the shape: give every bond, angle and twist an energy, then move the atoms downhill until nothing pulls on them any more.
Build one
Drag the structure to turn it. Scroll to come closer.
Structure
The minimised geometry.
Where the energy sits
Five terms. Bonds and angles are springs, the torsion term decides how the two ends of a bond line up, the inversion term keeps flat atoms flat, and van der Waals stops two atoms that are not bonded from occupying the same space.
Walking downhill
Energy against step number, on a log scale because the first few steps cover more ground than the next few hundred. Each restart begins from a different random arrangement, because walking downhill finds the nearest bottom and not the deepest one.
Is it right?
The only test that counts. These bond lengths and angles have been measured, mostly by microwave spectroscopy, to three or four decimal places. Press the button and the lab builds each molecule from scratch and compares.
Are the forces right?
Moving downhill needs the slope of the energy with respect to every coordinate. Those derivatives are worked out on paper and written into the code, which is fast and easy to get wrong. The check is to nudge one atom by a ten-thousandth of an angstrom, measure how much the energy changed, and compare. Every term is tested separately, because an error in one can hide inside the total.
Writing this lab turned up two errors here that the geometries alone did not reveal. The torsion derivative gave the two middle atoms the wrong share of the change, which a test at a minimum cannot see, because a minimum is a flat point of the torsion term and the wrong number gets multiplied by zero. The twist term for a pair of flat atoms had its sign the wrong way round, which pushed benzene towards a bent ring instead of holding it flat, and showed up as a ring puckered by 0.78 angstroms.
Atoms in motion
The structure from the last lesson is a lie of omission: it is the one arrangement where the forces cancel, and a real molecule is never in it. At room temperature every bond is vibrating. Give each atom a velocity, push it with the force it feels, and watch what a molecule actually does.
Run it
Moving
Drag to turn it.
Energy
Potential energy falls as kinetic energy rises and back again, a thousand times a picosecond, while the sum of the two stays put. With a thermostat running the sum does move, because a thermostat is adding and removing energy on purpose.
Temperature
Temperature is not a property an atom has. It is what you get from the average kinetic energy once you divide by the number of ways the molecule can move, so for a handful of atoms it swings about wildly and only its average means anything.
How long a step can you take?
Longer steps mean less arithmetic for the same amount of simulated time, and a step that is too long throws energy away. This runs the same half-picosecond at four timesteps and reports how far the total energy wandered. The pattern in the last column is the thing to look at.
A bond length is a distribution
Pick a bond, run for a while, and record its length at every step. The spread has a predicted size: a spring of stiffness k at temperature T stretches by about the square root of kT over k. Nothing about that prediction was put into the dynamics, so agreement is a real check.
Where the electrons go
Nothing so far has mentioned an electron. Bond springs and van der Waals spheres are a picture of a molecule with the electrons averaged away, and they cannot tell you why benzene is stable or why a dye is coloured. This lesson puts the electrons back, with the simplest calculation that still gets chemistry right.
Pick a molecule
The matrix
One row and one column per atom that has a p orbital sticking out of the plane. The diagonal is how tightly that atom holds an electron, the off-diagonal entries are how much an electron gains by spreading between two neighbours, and both are in units of a quantity called beta. Finding the eigenvalues of this is the whole method.
The orbitals
Each rung is one molecular orbital, with the electrons that live in it drawn as arrows. Click a rung to see where that orbital sits on the molecule.
The molecule
Circle size is how much of the orbital sits on that atom. Filled and open circles are the two signs of the wave function, and a place where the sign changes between neighbours is a node.
Does the gap predict the colour?
A molecule absorbs light when a photon has exactly the energy needed to lift an electron from the highest filled orbital to the lowest empty one. That energy is the gap, in units of beta. The theory has no idea how big beta is, so the only way to find out is to measure where real molecules absorb and fit it.
Solving for the electrons
Every number on this site so far came from a parameter that somebody fitted to an experiment: a bond wants to be 1.52 angstroms because Rappé and co-workers measured that, and beta is 2.4 electron volts because we fitted it to absorption spectra two lessons ago. This lesson has no fitted parameters at all. It writes down the energy of a molecule as a function of where its electrons are, and solves for them. The only inputs are the nuclear charges and the positions.
Run a calculation
The solver handles hydrogen and helium. A basis set for carbon needs p functions, and the integrals over those are a long recursion that would not fit in a browser lesson; the two-electron integrals over s functions are closed forms (Szabo and Ostlund, Modern Quantum Chemistry, Appendix A).
The self-consistent cycle
An electron moves in the field of all the other electrons, and that field is made of where the electrons are, which is what we are solving for. So the calculation guesses, solves, rebuilds the field from the answer, and solves again. Each row below is one pass, and the energy on it is the energy of the orbitals that pass produced. The guess it starts from is a density of zero, which is to say electrons that have not yet noticed each other.
Where the electrons ended up
The electron density along the line joining the two nuclei, in electrons per cubic bohr. A bond is the pile-up between the nuclei; pull the atoms apart with the slider above and watch it split in two.
The orbitals
One row per molecular orbital, with its energy in hartree and the electrons in it. The gap between the highest filled and the lowest empty orbital is the same quantity the Huckel lesson fitted beta to, except that here it comes out in real energy units with nothing fitted.
Where Hartree-Fock breaks
Pulling H2 apart should end with two hydrogen atoms, and two hydrogen atoms have an energy of exactly −1 hartree. Run the curve and read the right hand end.
Checking the grid
Hartree-Fock needs no numerical integration: its exchange energy is a sum over integrals that have closed forms. A density functional has none, because it is a nonlinear function of the density, so it is integrated on a grid of points the way every density functional program does it. A grid can be wrong, and there are two ways to find out. Integrating the density has to give back the number of electrons that went in. And the exchange energy of a hydrogen atom's exact density has a closed form, so the grid can be checked against a number that owes nothing to any grid.
Fitting one molecule to another
A drug works by sticking to something. Given two molecules, where does the smaller one sit on the larger one, and how tightly does it hold? This is the calculation that screens libraries of millions of compounds, and it is two parts: a score that says how good a given arrangement is, and a search that goes looking for the best one.
Two molecules
The best arrangement found
Drag to turn it.
Did the search converge?
Every random start, sorted by the score it reached. A flat shelf on the left means many starts found the same answer and you can believe it. A staircase means the search is still wandering and needs more starts.
What the score is made of
Shape is the van der Waals term: two surfaces in contact, neither overlapping. Charge is the attraction between the partial positives and negatives. Which one wins decides the answer, and the slider above changes the balance.
How big should the charges be?
A partial charge cannot be measured. A dipole moment can, and it is fixed by the charges and where the atoms sit, which makes it the one honest check on whether a set of charges is the right size. Run this, then set the slider above to the number it gives and dock the water dimer again.
Against the measurements, and what is missing
Five pairs of molecules whose structures and binding energies have been measured in the gas phase. The geometries come out close. The energies do not, and the pattern in which ones fail is the useful part.
Everything here is in a vacuum. A drug does not bind in a vacuum: it binds in water, and before it can touch its target both surfaces have to shed the water already stuck to them. That cost is often larger than the attraction that replaces it, which is why a score like this one ranks compounds more reliably than it predicts how tightly any single one will bind.
Your own question
Pick something nobody told you to ask. Set it up, run it, and write down what happened, including the part that did not work. The write-up below fills in your real numbers as you go, so what you add is the thinking.
Set up the experiment
Ideas worth a week
- Do the descriptors that predict solubility also predict toxicity, or are they different sets?
- Split the solubility data into compounds with and without an aromatic ring. Does one group need a different model?
- How few features can you keep before the score drops by more than 0.05?
- Find twenty compounds the model fails on, then pick a descriptor that separates them from the rest. Add it to this lab's code.
- Train on compounds under 200 g/mol and test on the ones above. Does a model trained on small molecules transfer to big ones?
- The toxicity file has twelve assays. Which pairs agree most, and does that match what the assays measure?
Your write-up
The numbers come from your last run. Fill in the rest and copy it out.