x lines of Python: Physical units

Difficulty rating: Intermediate

Have you ever wished you could carry units around with your quantities — and have the computer figure out the best units and multipliers to use?

pint is a nice, compact library for doing just this, handling all your dimensional analysis needs. It can also detect units from strings. We can define our own units, it knows about multipliers (kilo, mega, etc), and it even works with numpy and pandas.

To use it in its typical mode, we import the library then instantiate a UnitRegistry object. The registry contains lots of physical units:

import pint
units = pint.UnitRegistry()
thickness = 68 * units.m

Now thickness is a Quantity object with the value <Quantity(68, 'meter')>, but in Jupyter we see a nice 68 meter (as far as I know, you're stuck with US spelling).

Let's make another quantity and multiply the two:

area = 60 * units.km**2
volume = thickness * area

This results in volume having the value <Quantity(4080, 'kilometer ** 2 * meter')>, which pint can convert to any units you like, as long as they are compatible:

>>> volume.to('pint')
8622575788969.967 pint

More conveniently still, you can ask for 'compact' units. For example, volume.to_compact('pint') returns 8.622575788969966 terapint. (I guess that's why we don't use pints for field volumes!)

There are lots and lots of other things you can do with pint; some of them — dealing with specialist units, NumPy arrays, and Pandas dataframes — are demonstrated in the Notebook accompanying this post. You can use one of these links to run this right now in your browser if you like:

Binder   Run the accompanying notebook in MyBinder

Open In Colab   Run the notebook in Google Colaboratory (note the install cell at the beginning)

That's it for pint. I hope you enjoy using it in your scientific computing projects. If you have your own tips for handling units in Python, let us know in the comments!

There are some other options for handling units in Python:

  • quantities, which handles uncertainties without also needing the uncertainties package.
  • astropy.units, part of the large astropy project, is popular among physicists.

Jounce, Crackle and Pop


I saw this T-shirt recently, and didn't get it. (The joke or the T-shirt.)

It turns out that the third derivative of displacement \(x\) with respect to time \(t\) — that is, the derivative of acceleration \(\mathbf{a}\) — is called 'jerk' (or sometimes, boringly, jolt, surge, or lurch) and is measured in units of m/s³. 

So far, so hilarious, but is it useful? It turns out that it is. Since the force \(\mathbf{F}\) on a mass \(m\) is given by \(\mathbf{F} = m\mathbf{a}\), you can think of jerk as being equivalent to a change in force. The lurch you feel at the onset of a car's acceleration — that's jerk. The designers of transport systems and rollercoasters manage it daily.

$$ \mathrm{jerk,}\ \mathbf{j} = \frac{\mathrm{d}^3 x}{\mathrm{d}t^3}$$

Here's a visualization of velocity (green line) of a Tesla Model S driving in a parking lot. The coloured stripes show the acceleration (upper plot) and the jerk (lower plot). Notice that the peaks in jerk correspond to changes in acceleration.


The snap you feel at the start of the lurch? That's jounce  — the fourth derivative of displacement and the derivative of jerk. Eager et al (2016) wrote up a nice analysis of these quantities for the examples of a trampolinist and roller coaster passenger. Jounce is sometimes called snap... and the next two derivatives are called crackle and pop. 

What about momentum?

If the momentum \(\mathrm{p}\) of a mass \(m\) moving at a velocity \(v\) is \(m\mathbf{v}\) and \(\mathbf{F} = m\mathbf{a}\), what is mass times jerk? According to the physicist Philip Gibbs, who investigated the matter in 1996, it's called yank:

Momentum equals mass times velocity.
Force equals mass times acceleration.
Yank equals mass times jerk.
Tug equals mass times snap.
Snatch equals mass times crackle.
Shake equals mass times pop.

There are jokes in there, help yourself.

What about integrating?

Clearly the integral of jerk is acceleration, and that of acceleration is velocity, the integral of which is displacement. But what is the integral of displacement with respect to time? It's called absement, and it's a pretty peculiar quantity to think about. In the same way that an object with linearly increasing displacement has constant velocity and zero acceleration, an object with linearly increasing absement has constant displacement and zero velocity. (Constant absement at zero displacement gives rise to the name 'absement': an absence of displacement.)

Integrating displacement over time might be useful: the area under the displacement curve for a throttle lever could conceivably be proportional to fuel consumption for example. So absement seems to be a potentially useful quantity, measured in metre-seconds.

Integrate absement and you get absity (a play on 'velocity'). Keep going and you get abseleration, abserk, and absounce. Are these useful quantities? I don't think so. A quick look at them all — for the same Tesla S dataset I used before — shows that the loss of detail from multiple cumulative summations makes for rather uninformative transformations: 


You can reproduce the figures in this article with the Jupyter Notebook Jerk_jounce_etc.ipynb. Or you can launch a Binder right here in your browser and play with it there, without installing a thing!


David Eager et al (2016). Beyond velocity and acceleration: jerk, snap and higher derivatives. Eur. J. Phys. 37 065008. DOI: 10.1088/0143-0807/37/6/065008

Amarashiki (2012). Derivatives of position. The Spectrum of Riemannium blog, retrieved on 4 Mar 2018.

The dataset is from Jerry Jongerius's blog post, The Tesla (Elon Musk) and
New York Times (John Broder) Feud
. I have no interest in the 'feud', I just wanted a dataset.

The T-shirt is from Chummy Tees; the image is their copyright and used here under Fair Use terms.

The vintage Snap, Crackle and Pop logo is copyright of Kellogg's and used here under Fair Use terms.

Poisson's controversial stretch-squeeze ratio

Before reading this, you might want to check out the previous post about Siméon Denis Poisson's life and career. Then come back here...

Physicists and mathematicians knew about Poisson's ratio well before Poisson got involved with it. Thomas Young described it in his 1807 Lectures on Natural Philosophy and the Mechanical Arts:

We may easily observe that if we compress a piece of elastic gum in any direction, it extends itself in other directions: if we extend it in length, its breadth and thickness are diminished.

Young didn't venture into a rigorous formal definition, and it was referred to simply as the 'stretch-squeeze ratio'.

A new elastic constant?

Twenty years later, at a time when France's scientific muscle was fading along with the reign of Napoleon, Poisson published a paper attempting to restore his slightly bruised (by his standards) reputation in the mechanics of physical materials. In it, he stated that for a solid composed of molecules tightly held together by central forces on a crystalline lattice, the stretch squeeze ratio should equal 1/2 (which is equivalent to what we now call a Poisson's ratio of 1/4). In other words, Poisson regarded the stretch-squeeze ratio as a physical constant: the same value for all solids, claiming, 'This result agrees perfectly' with an experiment that one of his colleagues, Charles Cagniard de la Tour, recently performed on brass. 

Poisson's whole-hearted subscription to the corpuscular school certainly prejudiced his work. But the notion of discovering of a new physical constant, like Newton did for gravity, or Einstein would eventually do for light, must have been a powerful driving force. A would-be singular elastic constant could unify calculations for materials soft or stiff — in contrast to elastic moduli which vary over several orders of magnitude. 

Poisson's (silly) ratio

Later, between 1850 and 1870, the physics community acquired more evidence that the stretch-squeeze ratio was different for different materials, as other materials were deformed with more reliable measurements. Worse still, de la Tour's experiments on the elasticity of brass, upon which Poisson had hung his hat, turned out to be flawed. The stretch-squeeze ratio became known as Poisson's ratio not as a tribute to Poisson, but as a way of labeling a flawed theory. Indeed, the falsehood became so apparent that it drove the scientific community towards treating elastic materials as continuous media, as opposed to an ensemble of particles.

Today we define Poisson's ratio in terms of strain (deformation), or Lamé's parameters, or the speed \(V\) of P- and S-waves:


Interestingly, if Poisson turned out to be correct, and Poisson's ratio was in fact a constant, that would mean that the number of elastic constants it would take to describe an isotropic material would be one instead of two. It wasn't until Augustin Louis Cauchy used the notion of a stress tensor to describe the state of stress at a point within a material, with its three normal stresses and three shear stresses, did the need for two elastic constants become apparent. Tensors gave the mathematical framework to define Hooke's law in three dimensions. Found in the opening chapter in any modern textbook on seismology or mechanical engineering, continuum mechanics represents a unique advancement in science set out to undo Poisson's famously false deductions backed by insufficient data.


Greaves, N (2013). Poisson's ratio over two centuries: challenging hypothesis. Notes & Records of the Royal Society 67, 37-58. DOI: 10.1098/rsnr.2012.0021

Editorial (2011). Poisson's ratio at 200, Nature Materials10 (11) Available online.


Great geophysicists #11: Thomas Young

Painting of Young by Sir Thomas LawrenceThomas Young was a British scientist, one of the great polymaths of the early 19th century, and one of the greatest scientists. One author has called him 'the last man who knew everything'¹. He was born in Somerset, England, on 13 June 1773, and died in London on 10 May 1829, at the age of only 55. 

Like his contemporary Joseph Fourier, Young was an early Egyptologist. With Jean-François Champollion he is credited with deciphering the Rosetta Stone, a famous lump of granodiorite. This is not very surprising considering that at the age of 14, Young knew Greek, Latin, French, Italian, Hebrew, Chaldean, Syriac, Samaritan, Arabic, Persian, Turkish and Amharic. And English, presumably. 

But we don't include Young in our list because of hieroglyphics. Nor  because he proved, by demonstrating diffraction and interference, that light is a wave — and a transverse wave at that. Nor because he wasn't a demented sociopath like Newton. No, he's here because of his modulus

Elasticity is the most fundamental principle of material science. First explored by Hooke, but largely ignored by the mathematically inclined French theorists of the day, Young took the next important steps in this more practical domain. Using an empirical approach, he discovered that when a body is put under pressure, the amount of deformation it experiences is proportional to a constant for that particular material — what we now call Young's modulus, or E:

This well-known quantity is one of the stars of the new geophysical pursuit of predicting brittleness from seismic data, and a renewed interested in geomechanics in general. We know that Young's modulus on its own is not enough information, because the mechanics of failure (as opposed to deformation) are highly nonlinear, but Young's disciplined approach to scientific understanding is the best model for figuring it out. 

Sources and bibliography


¹ Thomas Young wrote a lot of entries in the 1818 edition of Encyclopædia Britannica, including pieces on bridges, colour, double refraction, Egypt, friction, hieroglyphics, hydraulics, languages, ships, sound, tides, and waves. Considering that lots of Wikipedia is from the out-of-copyright Encyclopædia Britannica 11th ed. (1911), I wonder if some of Wikipedia was written by the great polymath? I hope so.

What is spectral gamma-ray?

The spectral gamma-ray log is a measure of the natural radiation in rocks. The amplitude of the signal from the gamma-ray tool, which is just a sensor with no active source, is proportional to the energy of the gamma-ray photons it encounters. Being able to differentiate between photons of different energies turns out to be very handy Compared to the ordinary gamma-ray log, which ignores the energies and only counts the photons, it's like seeing in colour instead of black and white.

Why do we care about gamma radiation?

First, what are gamma rays? Highly energetic photons: electromagnetic radiation with very short wavelengths. 

Being able to see different energies, or 'colours', means we can differentiate between the radioactive decay of different elements. Elements decay by radiating energy, and the 'colour' of that energy is characteristic of that element (actually, of each isotope). So, we can tell by looking at the energy of a photon if we are seeing a potassium atom (40K) or a uranium atom (238U) decay. These are very different isotopes, with very different habits. We can do geology!

In fact, all sorts of radioisotopes occur naturally in the earth. By far the most abundant are potassium 40K, thorium 232Th and uranium 238U. Of these, potassium is the most abundant in sedimentary rocks, but thorium and uranium are present in small quantities, and have particular sedimentological implications.

What exactly are we measuring?

Potassium 40K decays to argon about 10% of the time, with γ-emission at 1.46 MeV (the other 90% of the time it decays to calcium). However, all of the decay in the 232Th and 238U decay series occurs by α- and β-particle decay, which don't always result in photon emission. The tool in fact measures γ-radiation from the decay of thallium 208Tl in the 232Th series (right), and from bismuth 214Bi in the 238U series. The spectral gamma-ray tool must be calibrated to known samples to give concentrations of 232Th and 238U from its readings. Proper calibration is vital, and is temperature-sensitive (of note in Canada!).

The concentrations of the three elements are estimated from the spectral measure­ments. The concentration of potassium is usually measured in percent (%) or per mil (‰), or sometimes in kilograms per tonne, which is equivalent to per mil. The other two elements are measured in parts per million (ppm).

Here is the gamma-ray spectrum from a single sample from 509 m below the sea-floor at ODP Site 1201. The final spectrum (heavy black line) is shown after removing the background spectrum (gray region) and applying a three-point mean boxcar filter. The thin black line shows the raw spectrum. Vertical lines mark the interval boundaries defined by Peter Blum (an ODP scientist at Texas A&M). Prominent energy peaks relating to certain elements are identified at the top of the figure. The inset shows the spectrum for energies >1500 keV at an expanded scale. 

We wouldn't normally look at these spectra. Instead, the tool provides logs for K, Th, and U. Next time, I'll look at the logs.

Spectrum illustration by Wikipedia user Inductiveload, licensed GFDL; decay chain by Wikipedia user BatesIsBack, licensed CC-BY-SA.

Filters that distort vision

Almost two weeks ago, I had LASIK vision correction surgery. Although the recovery took longer than average, I am seeing better than I ever did before with glasses or contacts. Better than 20/20. Here's why.

Low order and high order refractive errors

Most people (like me) who have (had) poor vision fall short of pristine correction because lenses only correct low order refractive errors. Still, any correction gives a dramatic improvement to the naked eye; further refinements may be negligible or imperceptible. Higher order aberrations, caused by small scale structural irregularities of the cornea, can still affect one's refractive power by up to 20%, and they can only be corrected using customized surgical methods.

It occurs to me that researchers in optometry, astronomy, and seismology face a common challenge: how to accurately measure and subsequently correct for structural deformations in refractive media, and the abberrations in wavefronts caused by such higher-order irregularities. 

The filter is the physical model

Before surgery, a wavefront imaging camera was used to make detailed topographic maps of my corneas, and estimate point spread functions for each eye. The point spread function is a 2D convolution operator that fuzzies the otherwise clear. It shows how a ray is scattered and smeared across the retina. Above all, it is a filter that represents the physical eye.

Point spread function (similar to mine prior to LASIK) representing refractive errors of the cornea (top two rows), and corrected vision (bottom row). Point spread functions are filters that distort both the visual and seismic realms. The seismic example is a segment of inline 25, Blake Ridge 3D seismic survey, available from the Open Seismic Repository (OSR).Observations in optics and seismology alike are only models of the physical system, models that are constrained by the filters. We don't care about the filters per se, but they do get in the way of the underlying system. Luckily, the behaviour of any observation can be expressed as a combination of filters. In this way, knowing the nature of reality literally means quantifying the filters that cause distortion. Change the filter, change the view. Describe the filter, describe the system. 

The seismic experiment yields a filtered earth; a smeared reality. Seismic data processing is the analysis and subsequent removal of the filters that distort geological vision. 

This image was made using the custom filter manipulation tool in FIJI. The seismic data is available from OpendTect's Open Seismic Repository.

Great geophysicists #7: Leonhard Euler

Leonhard Euler (pronounced 'oiler') was born on 15 April 1707 in Basel, Switzerland, but spent most of his life in Berlin and St Petersburg, where he died on 18 September 1783. Has was blind from the age of 50, but took this handicap stoically—when he lost sight in his right eye at 28 he said, "Now I will have less distraction".

It's hard to list Euler's contributions to the toolbox we call seismic geophysics—he worked on so many problems in maths and physics. For example, much of the notation we use today was invented or at least popularized by him: (x), e, i, π. He reconciled Newton's and Liebnitz's versions of calculus, making huge advances in solving difficult real-world equations. But he made some particularly relevant advances that resonate still:

  • Leonardo and Galileo both worked on mechanical stress distribution in beams, but didn't have the luxuries of calculus or Hooke's law. Daniel Bernoulli and Euler developed an isotropic elastic beam theory, and eventually convinced people you could actually build things using their insights. 
  • Euler's equations of fluid dynamics pre-date the more complicated (i.e. realistic) Navier–Stokes equations. Nonetheless, this work continued into vibrating strings, getting Euler (and Bernoulli) close to a general solution of the wave equation. They missed the mark, however, leaving it to Jean-Baptiste le Rond d'Alembert
  • optics (also wave behaviour). Though many of Euler's ideas about dispersion and lenses turned out to be incorrect (e.g. Pedersen 2008, DOI 10.1162/posc.2008.16.4.392), Euler did at least progress the idea that light is a wave, helping scientists move away from Newton's corpuscular theory.

The moment of Euler's death was described by the Marquis de Condorcet in a eulogy:

He had full possession of his faculties and apparently all of his strength... after having enjoyed some calculations on his blackboard concerning the laws of ascending motion for aerostatic machines... [he] spoke of Herschel's planet and the mathematics concerning its orbit and a little while later he had his grandson come and play with him and took a few cups of tea, when all of a sudden the pipe that he was smoking slipped from his hand and he ceased to calculate and live.

"He ceased to calculate," I love that.

Great geophysicists #6: Robert Hooke

Robert Hooke was born near Freshwater on the Isle of Wight, UK, on 28 July 1635, and died on 13 March 1703 in London. At 18, he was awarded a chorister scholarship at Oxford, where he studied physics under Robert Boyle, 8 years his senior. 

Hooke's famous law tells us how things deform and, along with Newton, Hooke is thus a parent of the wave equation. The derivation starts by equating the force due to acceleration (of a vibrating particle, say), and the force due to elastic deformation:

where m is mass, x is displacement, the two dots denote the second derivative with respect to time (a.k.a. acceleration), and k is the spring constant. This powerful insight, which allows us to compute a particle's motion at a given time, was first made by d'Alembert in about 1742. It is the founding principle of seismic rock physics.

Hooke the geologist

Like most scientists of the 17th century, Hooke was no specialist. One of his best known works was Micrographia, first published in 1665. The microscope was invented in the late 1500s, but Hooke was one of the first people to meticulously document and beautifully draw his observations. His book was a smash hit by all accounts, inspiring wonder in everyone who read it (Samuel Pepys, for example). Among other things, Hooke described samples of petrified wood, forams, ammonites, and crystals of quartz in a flint nodule (left). Hooke also wrote about the chalk formations in the cliffs near his home town.

Hooke went on to help Wren rebuild London after the great fire of 1666, and achieved great respect for this work too. So esteemed is he that Newton was apparently rather jealous of him, and one historian has referred to him as 'England's Leonardo'. He never married, and lived in his Oxford college all his adult life, and is buried in Bishopsgate, London. As one of the fathers of geophysics, we salute him.

The painting of Hooke, by Rita Greer, is licensed under a Free Art License. It's a interpretation based on descriptions of him ("his chin sharp, and forehead large"); amazingly, there are no known contemporary images of him. Hear more about this.

You can read more about the relationship between Hooke's law and seismic waves in Bill Goodway's and Evan's chapters in 52 Things You Should Know About Geophysics. Download their chapters for free!

Great geophysicists #4: Fermat

This Friday is Pierre de Fermat's 411th birthday. The great mathematician was born on 17 August 1601 in Beaumont-de-Lomagne, France, and died on 12 January 1665 in Castres, at the age of 63. While not a geophysicist sensu stricto, Fermat made a vast number of important discoveries that we use every day, including the principle of least time, and the foundations of probability theory. 

Fermat built on Heron of Alexandria's idea that light takes the shortest path, proposing instead that light takes the path of least time. These ideas might seem equivalent, but think about anisotropic and inhomogenous media. Fermat continued by deriving Snell's law. Let's see how that works.

We start by computing the time taken along a path:

Then we differentiate with respect to space. This effectively gives us the slope of the graph of time vs distance.

We want to minimize the time taken, which happens at the minimum on the time vs distance graph. At the minimum, the derivative is zero. The result is instantly recognizable as Snell's law:

Maupertuis's generalization

The principle is a core component of the principle of least action in classical mechanics, first proposed by Pierre Louis Maupertuis (1698–1759), another Frenchman. Indeed, it was Fermat's handling of Snell's law that Maupertuis objected to: he didn't like Fermat giving preference to least time over least distance.

Maupertuis's generalization of Fermat's principle was an important step. By the application of the calculus of variations, one can derive the equations of motion for any system. These are the equations at the heart of Newton's laws and Hooke's law, which underlie all of the physics of the seismic experiment. So, you know, quite useful.

Probably very clever

It's so hard to appreciate fundamental discoveries in hindsight. Together with Blaise Pascal, he solved basic problems in practical gambling that seem quite straightforward today. For example, Antoine Gombaud, the Chevalier de Méré, asked Pascal: why is it a good idea to bet on getting a 1 in four dice rolls, but not on a double-1 in twenty-four? But at the time, when no-one had thought about analysing problems in terms of permutations and combinations before, the solutions were revolutionary. And profitable.

For setting Snell's law on a firm theoretical footing, and introducing probability into the world, we say Pierre de Fermat (pictured here) is indeed a father of geophysics.

Smaller than they look

Suppose that you are standing on a pier at the edge of the Pacific Ocean. You have just created a new isotope of oxygen, 11O. Somehow, despite the fact that 12O is comically unstable and has a half-life of 580 yoctoseconds, 11O is stable. In your hand, you have a small glass of superlight water made with 11O, so that every molecule in the glass contains the new isotope.

You pour the water into the world's ocean and go home. In your will, you leave instructions to be handed down through generations of your family: wait several millennia for the world's ocean to mix completely. Then go to that pier, or any pier, and take a glass of water from the sea. Then count the 11O atoms in the glass.

What are the odds of getting one back?

Read More