Invariant
Preface
0 A New Dialect
1 Toys
2 The Image
3 A Column Is a List
Interlude A Column With No Name
4 Two Rays Tell All
5 Four Numbers
6 What No Lens Can Change
7 Thick Lenses Are Many Thin Ones
8 Two Old Friends
Interlude The Endless Column
9 The Slope Machine
10 Laws
11 The Bell
12 The Watcher
13 Glaser in Disguise
14 The Turn
15 Area Is Forever
16 The Price of a Small Spot
17 One Function to Rule the Ray
18 The True Ray
19 What the Straight Line Forgot
20 Colour
21 The Probe
22 The Fine Print
23 Two Directions
24 Poles
25 Three Corners
26 The Kick of a Kick
27 Four Corners
28 The Corrected Probe
29 The Wishlist
Interlude A Language of One’s Own
Coda
The Laws and the Commandments
The Kit
1 Maintainer

Invariant🔗

The automaton: svayam.

The Little Opticist

Electron optics, one question at a time

A lotus in line: the paths of twenty-four electron rays as the focus is swept.

Atharva Shukla

(define (opticist you) (opticist (read you)))

On the cover: a lotus, drawn by a program. Twenty-four rays leave one point of the axis, and the plane of focus is swept from the object to the image. Each curve is the path of one ray across the sample. It curls because a magnetic lens turns what it focuses (Chapter 14).

Preface🔗

For a student who has finished How to Design Programs and has never designed a lens.

What this book is🔗

An electron microscope is a column of lenses. An opticist is a person who can look at such a column and say where the electrons will land, how small the spot will be, and what stops it from being smaller.

You are not that person yet. But you can already do something most beginning opticists cannot: you can write down a data definition, let it shape a function, and test the function against examples you worked out by hand. This book claims that those three habits are most of optics.

So the book contains no physics that is not also a program. A ray is a pair of numbers. A column is a list. Tracing a ray is a fold. A lens that is not thin is a list you build with map. The laws of motion are a function that consumes a function. And the theorem at the centre of the book, Glaser’s bell-shaped lens, turns out to be a problem you solve in Chapter 8 wearing a costume you remove in Chapter 12.

The language🔗

The programs are written in DrRacket, in a language made for this book: #lang little-opticist. Inside it is sicm, a Racket edition of scmutils, the library of Sussman and Wisdom’s Structure and Interpretation of Classical Mechanics; around that are check-expect and a few other things a student of HtDP expects to find. It is close to the language you finished HtDP in, and Chapter 0 walks through the differences.

It was chosen for one thing the student languages cannot do. Here, a quoted symbol is a number you have not chosen yet:

> (+ 'a 'a)
(* 2 a)

So where another book would test a claim with three numbers, this one can often test it with a symbol, which is every number at once. Several things you will merely check in the early chapters, you will prove a few frames later, by handing the same function a symbol.

How to read it🔗

The chapters are dialogues, set as the Little books are: a rule, a question on the left, an answer on the right. Nobody is named. One voice asks. The other is yours.

Cover the right-hand column, answer the question aloud, then uncover it. If your answer differs, reread the frames above it, not the frame below it.

The book goes slowly on purpose. Most frames ask for one small step. If a frame seems too easy, answer it anyway; the next one leans on it.

Program text looks like this. Type it into the definitions window.

; drift : Number Ray -> Ray
(define (drift d r) ...)

An interaction looks like this. Type the line after the > at the prompt in the interactions window and compare.

> (* 2 (up 1 1/2))
(up 2 1)

Every block of both kinds has been run. The code/ folder holds one file per chapter, extracted from these pages by a script; each file follows the one before it, so opening a chapter’s file and pressing Run gives you everything the book has built up to that point, and runs that chapter’s tests. And every interaction printed here was put to Racket by that same script, in the way the interactions window does it, and compared with what the page says.

Two recipes🔗

You know the design recipe: six steps that take you from a problem to a function you can trust. This book teaches a second recipe beside it, for a piece of optics, and the two are the same recipe.

To design a function

To design a piece of optics

1

Data. Say what the information is made of, and what it means.

State. Say what must be written down about an electron to know where it goes next.

2

Signature, purpose, header. What goes in, what comes out, and one line on what it computes.

Planes and purpose. Which plane goes in, which comes out, and one line on what the element must do to every ray.

3

Examples, worked by hand before the code.

Special rays, traced by hand: on the axis, level, from the axis.

4

Template. The shape of the data is the shape of the function.

Invariant. The symmetry of the field is the shape of the answer. Say what cannot change before you compute.

5

Definition. Fill in the template.

Law. Fill in the physics.

6

Tests. The examples, run. Then a symbol, which is every example at once.

Checks. The special rays, the invariant, a theorem, a second way.

Every program in the book is designed by the left-hand column, with every step on the page: data definition, signature, purpose, examples, template, definition, tests. Every lens is designed by the right-hand column. Watch the two columns keep step. By the end you will not be able to do one without the other.

The left-hand recipe is re-read for each kind of data, as in HtDP: atomic data, enumerations, itemizations, structures, lists, natural numbers, functions as values, generative recursion, accumulators. Each has its own template, and each turns up here because the optics needs it.

“It works” is not something this book allows anyone to say. A function is done when its examples pass, a symbol passes, and a theorem agrees. That last check is possible because of something unusual. The facts about Glaser’s lens that this book leans on (the image at exactly 1/4, the magnification of exactly −1/4, the aberration coefficient 102/5 + 867π/32) are theorems checked by a proof assistant, in the electron-optics corpus. When your program prints 0.25, you are not agreeing with another program. You are agreeing with a proof.

What you need🔗

  • DrRacket, which you have, and two packages that do not come with it: rktsicm, which is the language sicm, and little-opticist, the folder of that name beside this book, which is the book’s own language. The setup page that comes with the book says how each is installed. On the machine this book was made on, that has been done.

  • A folder for your files, and one file in it for each chapter. Begin the file with #lang little-opticist, write the chapter’s definitions and examples in it, and press Run.

  • No calculus. The book builds the two ideas it needs, slope and sum, as functions you can run.

  • No physics. The book states four laws of nature in plain words and asks you to trust them until you have read SICM, where they are derived. Everything else it derives in front of you.

A debt🔗

The creed of this book is borrowed from Structure and Interpretation of Classical Mechanics: that writing physics as programs forces you to say exactly what you mean. The form is borrowed from Friedman and Felleisen’s The Little Schemer; the method, from How to Design Programs. The last chapter tells you which sections of SICM to open when you are done.

The road🔗

Chapter

You build

You learn to see

0. A New Dialect

nothing much

fractions, symbols, tuples

1. Toys

drift, kick

a ray is two numbers

2. The Image

toy, image-distance

where rays meet again

3. A Column Is a List

through, trace-ray

tracing is a fold

4. Two Rays Tell All

G, H

nothing is ever squared

5. Four Numbers

stack->transfer

a column, compiled

6. What No Lens Can Change

then, determinant

the first invariant

7. Thick Lenses Are Many Thin Ones

slice-lens

a lens with length

8. Two Old Friends

wave

sine and cosine are rays

9. The Slope Machine

D

the lens equation

10. Laws

euler-step, rk4-step

a law is a function

11. The Bell

bell, find-zero

Glaser’s lens, by brute force

12. The Watcher

gaze, apparent

the same lens, undisguised

13. Glaser in Disguise

glaser-h, glaser-image

a theorem, proved by D

14. The Turn

integrate, glaser-turn

why the picture rotates

15. Area Is Forever

area

what lenses cannot shrink

16. The Price of a Small Spot

transmit, acceptance

what an aperture costs

17. One Function to Rule the Ray

hamiltonian->law

laws, derived

18. The True Ray

true-H, landing

the image is not a point

19. What the Straight Line Forgot

cs-by-rays, cs-by-integral

spherical aberration

20. Colour

off-colour, cc-by-integral

chromatic aberration

21. The Probe

probe, best-angle

how small the spot can be

22. The Fine Print

nothing

what Scherzer assumed

23. Two Directions

ray2, turn

a ray out of its plane

24. Poles

pole, push

lenses that are not round

25. Three Corners

flip

two wrongs that cancel

26. The Kick of a Kick

thick, corrector

an error of the forbidden sign

27. Four Corners

iso, stretched

the other road, and a theorem

28. The Corrected Probe

corrected, row-budget

what a corrector buys, and for whom

29. The Wishlist

nothing

what to build next

Three interludes stand between chapters: after Chapter 3, after Chapter 8, and after the end. They are one story, and it is about this book.

A chapter is an evening, and most are short ones. Do not start the next until every frame of this one feels obvious.

Make tea first.

0 A New Dialect🔗

The language of this book is nearly the one you know. This chapter is about the “nearly”.

Open DrRacket. In the Language menu, choose “The Racket Language”. From now on the first line of a file says which language the file is written in.

Make a new file. Save it as ch00.rkt, in a folder of its own. Type this one line and press Run.

#lang little-opticist

A pause of a second or two. Then the interactions window says the language is little-opticist, and shows its prompt.

In the student languages you chose a language from a menu. Here a language is a library, and a file names the one it wants. This one was made for this book. Inside it is sicm, the language that Sussman and Wisdom’s book on mechanics is written in, with a few kindnesses added for a student of HtDP. Its whole text is at the back of the book, and it is short.

Now the prompt is waiting for an expression. Give it (+ 1 2).

> (+ 1 2)
3

Some things have not changed. Try fractions.

> (+ 1/2 1/3)
5/6
> (/ 3 4)
3/4
> (* 2/3 3/2)
1

Exact fractions, as before. Where DrRacket draws one with a bar, one number above the other, I shall write it on one line.

And a definition, typed at the prompt.

> (define (triple x) (* 3 x))
> (triple 1/6)
1/2

The same as in the student languages.

Now the first difference. Multiply 3 by one tenth, twice: once as 1/10 and once as 0.1.

> (* 3 1/10)
3/10
> (* 3 0.1)
0.30000000000000004

The second one is wrong! In the student languages 0.1 was exact.

In the student languages, 0.1 was secretly the fraction 1/10. Here a decimal point means: this number has been rounded to fit in the machine, and I know it. Such numbers are called inexact. What do you think happens when an exact number meets an inexact one?

> (+ 1/2 0.25)
0.75
> (exact->inexact 1/3)
0.3333333333333333

The answer is inexact. Rounding is catching.

Keep the two kinds apart in your mind: a slash means exactly, a point means about. Chapter 7 will tell you when to want which. You may leave out the zero before a point, and this book often does: .25 is 0.25. Next: squares and roots.

> (square 5)
25
> (sqrt 16)
4
> (sqrt 289/16)
17/4
> (sqrt 2)
1.4142135623730951

SICM says square where HtDP said sqr. And the root of a perfect square stays exact, even for a fraction.

That last fact will matter in Chapter 13. Now the difference this language was chosen for. What is 'a?

A quoted symbol. In HtDP it was a kind of data, like a little string. You could compare two of them and that was all.

Add two of them.

That should be an error. You cannot add symbols.

> (+ 'a 'a)
(* 2 a)

It did not complain. It answered with… a formula?

In this language, a symbol handed to arithmetic is treated as a number you have not chosen yet. The answer is whatever can be said about the result without choosing. Try some more.

> (* 0 'a)
0
> (- (* 3 'a) 'a 'a 'a)
0
> (square (+ 'a 'b))
(+ (expt a 2) (* 2 a b) (expt b 2))
> (triple 'a)
(* 3 a)

Zero times anything is zero, and it knows that without knowing a. And it multiplied out the square. My own triple works on a symbol too, though I never planned for that.

Think about the second of those. What have you learned about three times a number, less the number three times over?

That it is zero. Not for the numbers I happened to try: for every number, because I never chose one.

A test with a number checks one case. A test with a symbol can check all of them. We shall use that again and again.

Next: structures. define-struct is still here, and we shall want it in Chapter 3. But for a handful of numbers that belong together, the language offers something new: the tuple.

> (up 3 4)
(up 3 4)
> (ref (up 3 4) 0)
3
> (ref (up 3 4) 1)
4

up makes one, and ref takes a field out by its position, counting from zero. Like a structure whose fields have numbers for names.

Why it is called up is a story for SICM. Tuples have a talent that structures lack. Add two. Multiply one by 3.

> (+ (up 1 2) (up 10 20))
(up 11 22)
> (* 3 (up 1 2))
(up 3 6)
> (* 'c (up 1 2))
(up c (* 2 c))

Arithmetic goes through them, field by field. And symbols work inside.

Now the design recipe. Go back to the definitions window, and under your first line design a function as you always have: signature, purpose, examples, definition.

; double : Number -> Number
; twice a number
(check-expect (double 4) 8)
(check-expect (double 1/3) 2/3)
(define (double x) (+ x x))

Add an example that tests every number at once.

(check-expect (double 'a) (* 2 'a))

Press Run.

All 3 tests passed!

check-expect works as it always did, and the examples may come before the definition. But the third test has no numbers in it. What does it mean for it to pass?

That the two sides are the same formula, once each has been tidied. One passing test, and double is right for every number there is.

For inexact numbers there is check-within, as before.

(check-within (* 3 .1) 3/10 1e-12)
(check-within (sqrt 2) 1.41421 1e-5)

One new word. Each chapter will be a file of its own, and each will want what the chapters before it defined. When you begin Chapter 1, make a new file, ch01.rkt, and give it a second line.

#lang little-opticist
(follows "ch00.rkt")

“This file follows that one.” So in ch01.rkt I may use double?

And in ch02.rkt, if it follows ch01.rkt, and so on down the book. The tests of the earlier files are not run again: Run tests the file you are looking at.

The rest is a matter of spelling. Here is everything that is spelled differently.

In the student languages

Here

choose the language in a menu

#lang little-opticist on the first line

0.1 is exact

0.1 is inexact; write 1/10 for exact

(sqr x)

still works; this book says (square x), as SICM does

(first l), (rest l), (empty? l)

still work; this book says (car l), (cdr l), (null? l)

(local [(define ...)] body)

still works; this book puts the defines first inside the function

a structure for numbers you will add and scale

a tuple, (up x s)

a file uses what another file defined

(follows "that-file.rkt") on the second line

A short table. car, cdr and null? are the words of The Little Schemer. I know those. And my other old friends?

Try them.

> (build-list 5 square)
(list 0 1 4 9 16)
> (map double (list 1 2 3))
(list 2 4 6)
> (foldl + 0 (list 1 2 3 4))
10
> (foldl cons '() (list 1 2 3))
(list 3 2 1)

All here, and a list is printed the way I would write it.

Last: you will make mistakes. Type (car '()).

Red letters. car: contract violation. It expected a pair and was given the empty list. And the prompt is back.

Nothing is broken. Read the first line of a complaint: it nearly always names the function that was unhappy, and the next lines say what it wanted and what it got.

Fractions and points. Symbols that are numbers. Tuples. One file following another. A table of spellings. It is less than I feared.

Then you are ready for one electron.

Exercises

0.1 Without the machine: which of these are exact? 3/4, .75, (/ 3 4), (/ 3. 4), (sqrt 9/4), (sqrt 3), (* 2 1/2). Then check.

0.2 Predict, then try: (- (square (+ 'a 'b)) (square (- 'a 'b))). What does it tell you about every pair of numbers?

0.3 Design midpoint, which consumes two tuples and produces the tuple halfway between them. Give it two numeric examples and one with symbols.

0.4 Use foldl to design total, which adds up a list of numbers. Then call it on a list of tuples. Why does it work?

1 Toys🔗

A ray is two numbers. A gap changes one of them. A lens changes the other.

An electron is flying down the middle of a microscope. If you could stop the film on one frame, what would you need to write down, so that you could say where the electron goes next?

Where it is. And which way it is going.

Good. Draw a line down the middle of the microscope and call it the axis. We measure distance along the axis with a number called z. We stop the film whenever the electron crosses a plane at some z. On that plane, how far is the electron from the axis?

Some number. Call it x. Positive above the axis, negative below, zero on it.

And which way is it going?

It is mostly going forward. So what matters is how fast it climbs: how much x grows for each unit it moves along z. A slope. Call it s.

Two numbers that belong together. What did Chapter 0 give you for that?

A tuple. But I would like the fields to have names, as a structure’s do. So I write the constructor and the selectors myself.

; A Ray is a tuple: (up Number Number)
; interpretation (up x s) is an electron crossing
; a plane: it is x above the axis, and it climbs
; s for each unit it flies along the axis.
; make-ray : Number Number -> Ray
(define (make-ray x s) (up x s))
; ray-x : Ray -> Number
(define (ray-x r) (ref r 0))
; ray-s : Ray -> Number
(define (ray-s r) (ref r 1))
(check-expect (ray-x (make-ray 3 1/2)) 3)
(check-expect (ray-s (make-ray 3 1/2)) 1/2)

define-struct used to write those three for you. Now you know what it was doing. Where is (make-ray 0 1/2)?

On the axis, climbing. One unit further along it will be 1/2 above the axis.

And (make-ray 3 0)?

Three above the axis, flying level. It stays three above, forever, if nothing touches it.

And (make-ray 1 -1/4)?

One above the axis and sinking. After one unit it is at 3/4. After four units it reaches the axis.

You just traced a ray in your head. Now design the function. In empty space nothing pushes on the electron. An electron flies a distance d through empty space. What happens to its slope?

Nothing. Nothing pushes, so it keeps climbing at the same rate.

And to its height?

It climbs s for each unit, and it flies d units. So the height grows by d times s.

Examples first.

The three rays I just traced in my head will do.

; drift : Number Ray -> Ray
; the ray after flying d through empty space
(check-expect (drift 1 (make-ray 0 1/2))
(make-ray 1/2 1/2))
(check-expect (drift 4 (make-ray 1 -1/4))
(make-ray 0 -1/4))
(check-expect (drift 100 (make-ray 3 0))
(make-ray 3 0))
(check-expect (drift 0 (make-ray 3 7))
(make-ray 3 7))
(define (drift d r)
(make-ray (+ (ray-x r) (* d (ray-s r)))
(ray-s r)))

How does a Ray look when the machine prints it?

> (drift 2 (make-ray 0 1/2))
(up 1 1/2)

As the tuple it is. Height 1, slope 1/2.

The Law of the Drift.

In empty space the slope stays. The height grows by the distance times the slope.

Now a lens. What is a lens for?

To bring rays together. So it must bend them toward the axis.

A ray arrives exactly on the axis. Which way should the lens bend it?

Neither way. There is no “toward the axis” when you are on it. So a ray through the middle goes straight on.

A ray arrives a little above the axis. Which way?

Downward: its slope should get smaller.

And one that arrives far above the axis?

It has further to come back, so its slope should get smaller by more.

The simplest rule with those properties: the lens lowers the slope by an amount proportional to the height. Twice as far out, twice the change. Call the constant of proportion the power of the lens, p. If p is 1/2 and the ray arrives at height 1, by how much is the slope lowered?

By 1/2 times 1: a half.

At height 2?

By 1. At height 0, by nothing, which is what we wanted on the axis. And below the axis the height is negative, so the slope is raised. Toward the axis again. One rule does all of it.

One more supposition. The lens is so thin that the electron is through it before its height has had time to change.

Then it is the opposite of a drift. A drift changes the height and keeps the slope. This changes the slope and keeps the height.

; kick : Number Ray -> Ray
; the ray after a thin lens of power p
(check-expect (kick 1/2 (make-ray 0 1))
(make-ray 0 1))
(check-expect (kick 1/2 (make-ray 1 0))
(make-ray 1 -1/2))
(check-expect (kick 1/2 (make-ray 2 0))
(make-ray 2 -1))
(check-expect (kick 1/2 (make-ray -2 0))
(make-ray -2 1))
(check-expect (kick 0 (make-ray 2 5))
(make-ray 2 5))
(define (kick p r)
(make-ray (ray-x r)
(- (ray-s r) (* p (ray-x r)))))

The Law of the Kick.

A thin lens keeps the height. It lowers the slope by the power times the height.

Look at your second example. A level ray at height 1 meets a lens of power 1/2 and leaves as (make-ray 1 -1/2). Where does it cross the axis afterwards?

It is at height 1 and sinks 1/2 per unit. So after 2 units.

> (drift 2 (kick 1/2 (make-ray 1 0)))
(up 0 -1/2)

Your third example: the level ray at height 2.

It leaves as (make-ray 2 -1): height 2, sinking 1 per unit. After 2 units.

It crosses at the same place as the first one!

Try a level ray at height 10.

> (drift 2 (kick 1/2 (make-ray 10 0)))
(up 0 -5)

Two units again. But I have tried three heights. There are a great many more.

Then do not choose a height.

A symbol!

> (kick 1/2 (make-ray 'x 0))
(up x (* -1/2 x))
> (drift 2 (kick 1/2 (make-ray 'x 0)))
(up 0 (* -1/2 x))

The height after 2 units is 0, and there is no x left in it. Every level ray, whatever its height, crosses the axis 2 units after this lens.

(check-expect
(ray-x (drift 2 (kick 1/2 (make-ray 'x 0))))
0)

That place is called the focus of the lens, and the distance to it is the focal length. This lens had power 1/2 and focal length 2. Guess the rule, and then do not choose a power either.

One over the power?

> (drift (/ 1 'p) (kick 'p (make-ray 'x 0)))
(up 0 (* -1 p x))

Height 0 again. A lens of power p brings every level ray to the axis at a distance 1/p.

(check-expect
(ray-x (drift (/ 1 'p) (kick 'p (make-ray 'x 0))))
0)

Opticians label lenses by focal length. Why did I make you use the power?

Because of my last kick example. (kick 0 r) is r: a lens of power zero is no lens at all. Its focal length would be one over zero.

A data definition that needs infinity to say “nothing” is a poor one. There is a second reason, in exercise 1.3.

The First Commandment.

Take your examples from numbers you can check exactly. Then try a symbol: it is every example at once.

Is an electron microscope really made of straight flights and sudden kicks?

I suppose not. Real lenses are not thin, and I have no idea what a magnetic field does.

No. But everything that follows is this chapter, done more carefully.

Exercises

1.1 A ray that is not level crosses the axis somewhere. Design crossing, which consumes a ray and produces the distance it must fly to reach the axis. A level ray never gets there: produce #f for it. (A function that produces a number or #f has the signature Ray -> MaybeNumber.)

(check-expect (crossing (make-ray 1 -1/4)) 4)
(check-expect (crossing (make-ray 3 0)) #f)

1.2 In your mind. A lens of power 2 meets the ray (make-ray 3 1). What ray leaves? Where does it cross the axis? Then check.

1.3 Two thin lenses are pressed together, with no gap between them. Show with one check-expect that uses symbols that (kick 'p2 (kick 'p1 r)) is (kick (+ 'p1 'p2) r) for the ray (make-ray 'x 's). Powers add. What would you have had to write if lenses were labelled by focal length?

1.4 Show with a symbol that two drifts, one after the other, are one drift. Of what length?

2 The Image🔗

Rays leave a point in every direction. A lens can bring them back to one.

In Chapter 1 the rays came in level. Now the experiment that this whole book grows from. A point on the axis sends out electrons in many directions. Three units away is a lens of power 1/2. Follow the electron that leaves with slope 1. First the gap.

> (drift 3 (make-ray 0 1))
(up 3 1)

It arrives at the lens at height 3, still climbing.

Now the lens.

> (kick 1/2 (make-ray 3 1))
(up 3 -1/2)

The lens lowers the slope by 3/2, and 1 less 3/2 is −1/2. It has been turned around. It now sinks 1/2 per unit.

How far beyond the lens does it reach the axis?

It is at height 3 and sinks 1/2 per unit. Six units.

Now the electron that left with slope 1/10.

> (kick 1/2 (drift 3 (make-ray 0 1/10)))
(up 3/10 -1/20)

Height 3/10, sinking 1/20 per unit. That takes… 3/10 divided by 1/20. Six units.

And slope −1/3?

> (kick 1/2 (drift 3 (make-ray 0 -1/3)))
(up -1 1/6)

Below the axis and climbing 1/6 per unit. Six units again!

They left the point in different directions, and they all come back together at one place.

Write that down as a function and as tests, so that it stays true.

; toy : Ray -> Ray
; a ray carried 3 to a lens of power 1/2,
; through it, and 6 beyond
(check-expect (ray-x (toy (make-ray 0 1))) 0)
(check-expect (ray-x (toy (make-ray 0 1/10))) 0)
(check-expect (ray-x (toy (make-ray 0 -1/3))) 0)
(define (toy r)
(drift 6 (kick 1/2 (drift 3 r))))

Three slopes. The First Commandment.

Do not choose a slope.

> (toy (make-ray 0 's))
(up 0 (* -1/2 s))

Height 0, for every slope there is.

(check-expect (ray-x (toy (make-ray 0 's))) 0)

The place where all the rays from one point meet again is called the image of that point. An image is not a picture. It is a place where the slope a ray started with no longer matters.

Rays leave a point 3 before a lens of power 1/2. Whatever their slope, they meet again 6 beyond it. A point one unit above the axis is imaged two units below it.

Rays leave a point 3 before a lens of power 1/2. Whatever their slope, they meet again 6 beyond it. A point one unit above the axis is imaged two units below it.

Now move the starting point off the axis, to height 1. Try two slopes, and then all of them.

> (toy (make-ray 1 0))
(up -2 -1/2)
> (toy (make-ray 1 1))
(up -2 -1)
> (toy (make-ray 1 's))
(up -2 (+ -1/2 (* -1/2 s)))

They all land at height −2. So the point at height 1 has an image too, at height −2. Twice as far from the axis, and on the other side.

And a point at any height?

> (toy (make-ray 'x 's))
(up (* -2 x) (+ (* -1/2 s) (* -1/2 x)))

Its image is at height −2 times x. No s in it.

The image is upside down and twice as large. We say the magnification is −2.

(check-expect (ray-x (toy (make-ray 'x 's)))
(* -2 'x))

Now look at the slopes instead of the heights. Go back to the point on the axis. A ray leaves with slope s. With what slope does it arrive at the image?

I have that already: (toy (make-ray 0 's)) was (up 0 (* -1/2 s)). Every slope is multiplied by −1/2.

Heights are multiplied by −2. Slopes are multiplied by −1/2. Notice anything?

One is one over the other. Is that a coincidence?

It is the most important fact in this book, and you will prove it in Chapter 6. A microscope wants the opposite of this toy: an image smaller than the object. What will that do to the slopes?

If the rule holds, they get larger. Shrink the spot by ten, and the rays arrive ten times steeper.

Remember that you said so. Now, why 6? I chose the 3 and the 1/2, and then 6 was forced on me. Leave all three unchosen. A point on the axis, a gap u, a lens of power p, a gap v.

> (ray-x (drift 'v (kick 'p (drift 'u (make-ray 0 's)))))
(+ (* -1 p s u v) (* s u) (* s v))

Three terms, and every one of them has an s. So the height is s times something: s times u + v − p·u·v.

When is that zero for every s?

When the something is zero: u + v equals p·u·v.

Divide both sides by u·v.

1/v + 1/u = p. One over the distance in front, plus one over the distance behind, is the power.

With u = 3 and p = 1/2: 1/3 plus 1/v is 1/2, so 1/v is 1/6. Six!

That is called the thin lens formula, and it is in every book on optics. You did not look it up. Turn it into a function.

From u + v = p·u·v I get v times (p·u − 1) equals u.

; image-distance : Number Number -> Number
; how far behind a thin lens of power p the image
; forms, of a point a distance u in front of it
(check-expect (image-distance 1/2 3) 6)
(check-expect (image-distance 1/2 6) 3)
(check-expect (image-distance 1 2) 2)
(define (image-distance p u)
(/ u (- (* p u) 1)))

Three examples. Is it right for every lens and every distance?

Put the gap it computes after the lens, and ask where the ray is.

(check-expect
(ray-x (drift (image-distance 'p 'u)
(kick 'p (drift 'u (make-ray 0 's)))))
0)

It passes. For every power, every distance, every slope.

You wrote a function and then, in one line, proved it correct. That did not happen in HtDP.

In HtDP I could only choose examples and hope I had chosen well.

Look at your second example: the object 6 in front, the image 3 behind. What is the magnification there?

> (drift 3 (kick 1/2 (drift 6 (make-ray 'x 's))))
(up (* -1/2 x) (+ (* -2 s) (* -1/2 x)))

Heights are multiplied by −1/2: the image is half the size. And a ray from the axis has its slope multiplied by −2. Smaller image, steeper rays, and again one is one over the other.

A microscope column is that, several times over.

Go and eat something. A samosa has the right shape: it comes to a point.

Exercises

2.1 What does (image-distance 1/2 2) do? What do the rays do? Trace (make-ray 0 's) through a gap of 2 and a lens of power 1/2 and look at the slope that comes out.

2.2 In your mind. A lens of power 1 has an object 3/2 in front of it. Where is the image, and what is the magnification? Then check with a symbolic ray.

2.3 Design magnification-of, which consumes the power of a thin lens and the distance u of an object and produces the magnification of its image. Find the formula by tracing (make-ray 'x 's) through gap, lens, and the gap that image-distance gives. Check it against −2 and −1/2.

2.4 An object is 3 in front of a lens. Which power puts the image 3/2 behind it? Design power-for, the inverse of image-distance in its first argument, and prove it correct with one symbolic check-expect.

3 A Column Is a List🔗

The electron meets the modules in order. So must the function.

Read this aloud, in the order the electron lives it:

(drift 6 (kick 1/2 (drift 3 r)))

“Drift 6, kick, drift 3.” No, that is backwards. The electron drifts 3 first. I have to read it inside out.

And if the microscope had twenty parts?

Twenty nested parentheses, read from the middle. I would rather have a list, written in the order of travel.

A list of what?

Of the parts. A part is either some empty space of a certain length, or a thin lens of a certain power. In HtDP I would write two structure definitions.

Write them. define-struct is here, as Chapter 0 said.

Two structures, one field each.

; A Module is one of:
; - (make-gap Number)
; - (make-thin Number)
; interpretation one part of a microscope:
; (make-gap d) is empty space of length d;
; (make-thin p) is a thin lens of power p.
(define-struct gap (d))
(define-struct thin (p))
(check-expect (gap? (make-gap 3)) #t)
(check-expect (gap? (make-thin 1/2)) #f)
(check-expect (gap-d (make-gap 3)) 3)
(check-expect (thin-p (make-thin 1/2)) 1/2)

And the whole column?

; A ModuleStack is one of:
; - '()
; - (cons Module ModuleStack)
; interpretation the modules an electron meets,
; in order, from the source to the target.
(define TOY
(list (make-gap 3) (make-thin 1/2) (make-gap 6)))
> TOY
(list (make-gap 3) (make-thin 1/2) (make-gap 6))

It prints as what it is. I can read the microscope off the screen, in the order of travel.

A Module is one of two things. What does a function that consumes a Module look like, before you know what it does?

A cond with two clauses, one for each kind, and the selector laid out in each.

(define (fun-for-module m)
(cond ((gap? m) (... (gap-d m) ...))
((thin? m) (... (thin-p m) ...))))

Now fill it in: what does one module do to a ray?

; through : Module Ray -> Ray
; the ray after one module
(check-expect (through (make-gap 3) (make-ray 0 1))
(make-ray 3 1))
(check-expect (through (make-thin 1/2) (make-ray 3 1))
(make-ray 3 -1/2))
(define (through m r)
(cond ((gap? m) (drift (gap-d m) r))
((thin? m) (kick (thin-p m) r))))

A ModuleStack is a list. Design the function that carries a ray through a whole stack. This system already uses the name trace for something else, so call it trace-ray. Examples first.

Chapter 2 gives them. A ray from the axis with slope 1 must land on the axis.

; trace-ray : ModuleStack Ray -> Ray
; the ray after every module of ms, in order
(check-expect (ray-x (trace-ray TOY (make-ray 0 1))) 0)

And the template for a list says: empty or cons; in the cons case, the first module and the natural recursion on the rest.

(define (trace-ray ms r)
(cond
((null? ms) r)
(else (through (car ms)
(trace-ray (cdr ms) r)))))

The test passes.

Does it. Make the example say everything you know: not only where the ray lands, but with what slope.

In Chapter 2 the slope came out as −1/2.

(check-expect (trace-ray TOY (make-ray 0 1))
(make-ray 0 -1/2))
FAILED: (trace-ray TOY (make-ray 0 1))
actual: (up 0 -2)
expected: (up 0 -1/2)

It fails. The ray lands on the axis, but with slope −2.

What did your function really compute? Unfold it by hand, for a stack of three.

(through gap3 (through lens (through gap6 r))). The innermost one happens first. So the ray went through the last gap first.

I sent the electron through the microscope backwards.

And it still made an image, which is why your weak test passed. A microscope run backwards is also a microscope; exercise 3.3 is about that. But it is not this one. Why did the template lead you astray?

The natural recursion handles the rest of the list before the first module gets its turn. But the electron meets the first module first. By the time it reaches the rest, it is a different ray.

So the ray is not just an argument that rides along. It is…

An accumulator. It is what the electron remembers of everything it has passed.

; trace-ray : ModuleStack Ray -> Ray
; the ray after every module of ms, in order
; accumulator r: the ray as it is after all
; the modules already passed
(check-expect (trace-ray '() (make-ray 2 3))
(make-ray 2 3))
(check-expect (trace-ray TOY (make-ray 0 1))
(make-ray 0 -1/2))
(check-expect (trace-ray TOY (make-ray 1 0))
(make-ray -2 -1/2))
(define (trace-ray ms r)
(cond
((null? ms) r)
(else (trace-ray (cdr ms)
(through (car ms) r)))))

You have seen that shape before.

It is foldl: combine the first item with what has been accumulated, and carry on down the list. foldl hands its function the item first and the accumulated result second. That is a module and then a ray: exactly what through consumes. I do not even need a lambda.

(check-expect
(foldl through (make-ray 0 1) TOY)
(trace-ray TOY (make-ray 0 1)))

The Second Commandment.

Let the shape of the data be the shape of the function. A column is a list, so tracing is a fold, and the ray is what the fold remembers.

Look at what you have made. TOY is a piece of data. trace-ray reads it from left to right and does what each item says. What do you call a piece of data that says what to do, and a function that does it?

A program and an interpreter. The column is a program in a language with two instructions, gap and thin. The ray is the state of the machine.

And your interpreter never asks whether the numbers in the program are chosen.

> (trace-ray TOY (make-ray 0 's))
(up 0 (* -1/2 s))
> (trace-ray (list (make-gap 'u) (make-thin 'p))
(make-ray 0 1))
(up u (+ 1 (* -1 p u)))

A column with unchosen parts. I did nothing to make that work.

Now design a second program in that language. A lens of power 1/2, six units from the source. Where is the image?

(image-distance 1/2 6) is 3. Three units beyond the lens. And Chapter 2 said its magnification is −1/2.

Put a second lens, of power 1, four units beyond that image. Where is the image of the image?

(image-distance 1 4) is 4/3. And the magnification of that step… the heights will tell me. Let me build it and look.

(define TWO
(list (make-gap 6) (make-thin 1/2)
(make-gap 7) (make-thin 1)
(make-gap 4/3)))
> (trace-ray TWO (make-ray 'x 's))
(up (* 1/6 x) (+ (* 6 s) (* 2 x)))

The height is x over 6, with no s in it. So it does form an image, the right way up, a sixth of the size. The gap of 7 is the 3 to the first image and the 4 beyond it.

A sixth is not much of a microscope. But it is yours, so test it.

(check-expect (ray-x (trace-ray TWO (make-ray 0 1))) 0)
(check-expect (ray-x (trace-ray TWO (make-ray 1 5))) 1/6)
(check-expect (ray-x (trace-ray TWO (make-ray 'x 's)))
(* 1/6 'x))

Does the order of the modules matter?

> (trace-ray (list (make-gap 3) (make-thin 1/2))
(make-ray 0 1))
(up 3 -1/2)
> (trace-ray (list (make-thin 1/2) (make-gap 3))
(make-ray 0 1))
(up 3 1)

Very much. In the second column the ray is on the axis when it meets the lens, so the lens does nothing.

Like instructions in any program. One more function, because we shall want to know how long our columns are.

Only gaps have length. The template for lists again, and this time the natural recursion is right, because lengths can be added in any order.

; stack-length : ModuleStack -> Number
; the distance from the first plane to the last
(check-expect (stack-length '()) 0)
(check-expect (stack-length TOY) 9)
(check-expect (stack-length TWO) 43/3)
(define (stack-length ms)
(cond
((null? ms) 0)
((gap? (car ms))
(+ (gap-d (car ms))
(stack-length (cdr ms))))
(else (stack-length (cdr ms)))))

Your colleagues’ data definition says: a Module is one of an Aperture or a Lens, and a column is a beam together with a ModuleStack. Where are their gaps?

They must give each lens a position along the axis, so that the gaps are whatever lies between. Ours is simpler to trace. Theirs is closer to how a column is built. And they have an aperture, which we do not.

We shall grow toward theirs. The aperture arrives in Chapter 16, and real lenses, which have no edges at all, in Chapter 11.

Exercises

3.1 Design path, which consumes a ModuleStack and a ray and produces the list of rays at every plane: before the first module, between each pair, and after the last. It is the list you would need in order to draw the ray.

(check-expect (path TOY (make-ray 0 1))
(list (make-ray 0 1) (make-ray 3 1)
(make-ray 3 -1/2) (make-ray 0 -1/2)))

3.2 A telescope is two lenses whose foci coincide. Build one from a lens of power 1/2, a gap of 3, and a lens of power 1. Trace (make-ray 'x 0) through it. What does it do to level rays? Does a telescope form an image of a point?

3.3 Films of electrons can be run backwards. Design flip, which reverses the direction of a ray by negating its slope. Then state, as a check-expect that uses reverse and a symbolic ray, the fact that sending a flipped ray back through the reversed column returns the flipped original. Test it on TOY and TWO. This is the first invariant in the book: a fact about every column, not about one.

3.4 In your mind. In TWO, the first image forms 3 units after the first lens. Suppose you slide a third lens, of any power, to exactly that plane. What happens to the final image? Then check, with the power as a symbol.

Interlude A Column With No Name🔗

trace-ray calls itself by name. Take the name away, and see what is left.

Here is the function of Chapter 3.

(define (trace-ray ms r)
(cond
((null? ms) r)
(else (trace-ray (cdr ms)
(through (car ms) r)))))

How many times does it say trace-ray?

Twice. Once to take the name, and once to use it.

For this evening I take define away from you. You keep lambda. Write the function.

(lambda (ms r)
(cond
((null? ms) r)
(else (??? (cdr ms)
(through (car ms) r)))))

The first clause is done. In the second I must call the function I am in the middle of writing, and it has no name. A lambda has no word for “me”.

What does the body need that it does not have?

The function itself.

How does any function come by a value it does not have?

As an argument. One more parameter, me. Whoever calls the function hands the function to it.

(lambda (me ms r)
(cond
((null? ms) r)
(else (me me (cdr ms)
(through (car ms) r)))))

me now wants three arguments, and the first of them is itself. So the call inside is (me me ...).

And who hands it to itself the first time?

One more lambda, which does that and nothing else.

(check-expect
((lambda (f) (f f TOY (make-ray 'x 's)))
(lambda (me ms r)
(cond
((null? ms) r)
(else (me me (cdr ms)
(through (car ms) r))))))
(trace-ray TOY (make-ray 'x 's)))

It passes, for every ray. TOY, make-ray and through have names, but none of them calls itself. The recursion in the first expression is made of lambda and of nothing else.

Which words of your inner lambda are about columns, and which are about having no name?

null?, cdr, through and car are about columns. me me is about having no name, and it sits in the middle of the optics.

Then make a wish. Write only the optics. Suppose someone hands you trace, a function that carries a ray through the rest of the column.

(lambda (trace)
(lambda (ms r)
(cond
((null? ms) r)
(else (trace (cdr ms)
(through (car ms) r))))))

This is trace-ray with its name turned into a parameter. Handed a function for the rest of the column, it produces a function for one module more.

Its signature.

[ModuleStack Ray -> Ray] -> [ModuleStack Ray -> Ray]. A tracer goes in and a tracer comes out.

And the wish?

A function that consumes my step and produces the tracer for the whole column. Call the step f. The test showed the trick: hand a function to itself. Call that function x. Then (x x) is the tracer, and it is also “the rest” that the step asks for. So x is (lambda (x) (f (x x))).

When is that (x x) computed?

Before f is called, because it is an argument. And computing it runs x, whose first act is to compute (x x). It never reaches f, and so never reaches the optics.

How do you make a computation wait until it is wanted?

Wrap it in a lambda.

Two words of the language will help. A lambda whose parameters are one bare name, (lambda args ...), accepts any number of arguments and calls the list of them args. And (apply g args) calls g on the items of a list. Now grant your wish. Its name is Y.

; Y : [[X ... -> Z] -> [X ... -> Z]] -> [X ... -> Z]
; the whole journey, from a function that takes one
; step when handed a function for the rest
(check-expect
((Y (lambda (trace)
(lambda (ms r)
(cond
((null? ms) r)
(else (trace (cdr ms)
(through (car ms) r)))))))
TOY (make-ray 'x 's))
(trace-ray TOY (make-ray 'x 's)))
(define Y
(lambda (f)
((lambda (x) (x x))
(lambda (x)
(f (lambda args (apply (x x) args)))))))
> ((Y (lambda (trace)
(lambda (ms r)
(cond
((null? ms) r)
(else (trace (cdr ms)
(through (car ms) r)))))))
TOY (make-ray 0 1))
(up 0 -1/2)

On the axis, slope −1/2: Chapter 2’s answer. I wrote define once, for Y, and Y does not call itself.

Take the wrapper off Y, and the step out of it. This is what is left.

((lambda (x) (x x)) (lambda (x) (x x)))

Do not run it. Say what it does.

It hands a function to itself. That function hands its argument to itself. Which is the expression I started with. And again. It has no null? clause: it is the column with no last module.

You ran it.

My tea is cold.

Y knows nothing about rays. Chapter 3 had a second function on a ModuleStack. Write its step.

stack-length. Handed len, a function that measures the rest, measure one module more.

(check-expect
((Y (lambda (len)
(lambda (ms)
(cond
((null? ms) 0)
((gap? (car ms))
(+ (gap-d (car ms)) (len (cdr ms))))
(else (len (cdr ms)))))))
TWO)
(stack-length TWO))

43/3, as before. I copied the body and turned the name into a parameter. I did not have to think.

Inside Y there is a parameter called x. What kind of data is it?

A function. Look at the call, (x x): it consumes something like itself.

; A Self is a function: [Self -> [X ... -> Z]]

A data definition that mentions itself. A ModuleStack does that too, but a ModuleStack may be '(). A Self has no clause that stops.

Then what stops Y?

The step. Its null? clause answers without calling trace. The data stops the function. Y only promised to keep going while it was asked.

You had no define. Where did the recursion come from?

From the data definition. A ModuleStack is '(), or a cons of a Module onto a ModuleStack. It mentions itself once, in its second clause. My step mentions trace once, in its second clause. That is the template of Chapter 3, and Y had nothing to add to it.

Then say what define contributed.

A word for “me”. Four lines of lambda can supply the word.

Recursion is not a feature of define. It is a consequence of a data definition that refers to itself. The template comes from the data. This construction is the ninth chapter of The Little Schemer, replayed on a function of yours.

Shall I write Y from now on?

No. define is the better notation, and you may have it back. But now you know what it was doing.

One thing stays with me. The column with no last module. A microscope has a last module.

A microscope has. After Chapter 8 you will meet a column that has none: the same cell, repeated without end. You will say what becomes of every ray in it, and you will not run it for ever.

The tea will be glad.

Exercises

3x.1 Design path of exercise 3.1 as a step for Y, with no define. Check it against your path on TOY.

3x.2 Use Y to write, with no define, the function that consumes a natural number n and a ray and produces the ray after n gaps of length 1. A natural number is 0 or one more than a natural number. Where does that data definition mention itself, and where does your step mention its parameter?

3x.3 In your mind. (Y (lambda (trace) (lambda (ms r) r))) is a function. What does it do to a ModuleStack and a ray? When you call it, how many times does the wrapped (x x) run? Then check the first answer.

4 Two Rays Tell All🔗

Trace two rays through a column, and you have traced them all.

Trace these three rays through TOY: (make-ray 1 0), (make-ray 0 1) and (make-ray 2 3).

> (trace-ray TOY (make-ray 1 0))
(up -2 -1/2)
> (trace-ray TOY (make-ray 0 1))
(up 0 -1/2)
> (trace-ray TOY (make-ray 2 3))
(up -4 -5/2)

Take twice the first answer and three times the second, and add them.

Rays are tuples, and Chapter 0 said tuples can be scaled and added.

> (+ (* 2 (up -2 -1/2)) (* 3 (up 0 -1/2)))
(up -4 -5/2)

That is the third answer! I could have got it without tracing.

Why twice and three times?

Because the third ray going in was (make-ray 2 3): twice the first plus three times the second.

> (+ (* 2 (make-ray 1 0)) (* 3 (make-ray 0 1)))
(up 2 3)

So: the ray going in is a mixture of two rays, and the ray coming out is the same mixture of what those two became.

Was that luck? State what you noticed as two tests, for a column other than TOY.

Tracing a sum gives the sum of the traces. Tracing a scaled ray gives the scaled trace.

(check-expect
(trace-ray TWO (+ (make-ray 1 2) (make-ray -3 1/7)))
(+ (trace-ray TWO (make-ray 1 2))
(trace-ray TWO (make-ray -3 1/7))))
(check-expect
(trace-ray TWO (* 5/3 (make-ray 1 2)))
(* 5/3 (trace-ray TWO (make-ray 1 2))))

They pass. But those are particular rays, and one particular column.

Then choose nothing.

Two unchosen rays, an unchosen scale, and a column whose parts are unchosen too.

(define ANY-COLUMN
(list (make-gap 'd1) (make-thin 'p)
(make-gap 'd2)))
(check-expect
(trace-ray ANY-COLUMN
(+ (make-ray 'x1 's1) (make-ray 'x2 's2)))
(+ (trace-ray ANY-COLUMN (make-ray 'x1 's1))
(trace-ray ANY-COLUMN (make-ray 'x2 's2))))
(check-expect
(trace-ray ANY-COLUMN (* 'c (make-ray 'x1 's1)))
(* 'c (trace-ray ANY-COLUMN (make-ray 'x1 's1))))

They pass. For every gap, lens, gap, and every pair of rays.

Why must they pass? Look inside drift and kick.

Each one multiplies the height and the slope by fixed numbers and adds. The height is never squared. The slope is never squared. Neither is ever compared with anything. If I double the ray going in, every product doubles, so the ray coming out doubles. And a column only does drifts and kicks, one after another.

The Law of Two Rays.

Through any column of gaps and thin lenses, the trace of a sum is the sum of the traces, and the trace of a scaled ray is the scaled trace.

The word for this is linear. Now: you said the ray (make-ray 2 3) was a mixture of two special rays. Is every ray such a mixture?

> (+ (* 'x (make-ray 1 0)) (* 's (make-ray 0 1)))
(up x s)

Yes. Any ray is x times the one and s times the other.

Opticists have names for those two. The ray that starts one unit off the axis, flying level, is the field ray, and we call it G. The ray that starts on the axis, climbing at slope one, is the axial ray, and we call it H.

(define G (make-ray 1 0)) ; the field ray
(define H (make-ray 0 1)) ; the axial ray

Say what the Law of Two Rays tells you about G and H.

If I know where G and H end up, I know where every ray ends up: x times where G went, plus s times where H went.

A whole column is summed up by what it does to two rays.

Check that, for TOY and an unchosen ray.

(check-expect
(trace-ray TOY (make-ray 'x 's))
(+ (* 'x (trace-ray TOY G))
(* 's (trace-ray TOY H))))

Now look at the symbolic trace itself, and read it slowly.

> (trace-ray TOY (make-ray 'x 's))
(up (* -2 x) (+ (* -1/2 s) (* -1/2 x)))
> (trace-ray TOY G)
(up -2 -1/2)
> (trace-ray TOY H)
(up 0 -1/2)

The height that comes out is −2 times x, and 0 times s. Those two numbers, −2 and 0, are the heights of G and H afterwards.

The slope that comes out is −1/2 times x and −1/2 times s. Those are the slopes of G and H afterwards.

How many numbers does it take to say everything TOY does?

Four. Two for G and two for H.

Tomorrow we shall put them in a table and learn to read it. One last look at why this works. Suppose someone built a lens that lowered the slope by the power times the square of the height.

> (define (bad-kick p r)
(make-ray (ray-x r)
(- (ray-s r) (* p (square (ray-x r))))))
> (bad-kick 1 (make-ray 1 0))
(up 1 -1)
> (bad-kick 1 (make-ray 2 0))
(up 2 -4)

I doubled the ray going in and the slope coming out went from −1 to −4. It did not double. The Law of Two Rays is broken.

Remember that lens. Its name is in Chapter 19.

Exercises

4.1 Trace G and H through TWO. Without tracing anything else, say where (make-ray 3 -1) ends up. Then check.

4.2 A column sends G to (up 2 1) and H to (up 3 2). Where does it send (make-ray 1 1)? (make-ray 1 -1)? Is there a ray that comes out exactly as it went in?

4.3 With bad-kick in place of kick, find by experiment how the height at the far end of the toy depends on the starting slope of a ray from the axis. Use slopes 1/10, 2/10 and 4/10. Does it form an image?

4.4 In your mind. Two rays leave the same point with different slopes. What can you say about the difference of the two rays, as a ray? Use that to explain, in one sentence, what an image is in terms of H.

5 Four Numbers🔗

A column, however long, boiled down to a table with two rows and two columns.

Yesterday you found that TOY is summed up by four numbers. Say again which.

Where G ends up: its height and its slope. And where H ends up: its height and its slope.

Give them names. The height of G afterwards is g, and its slope is dg. The height of H afterwards is h, and its slope is dh. Arrange them so that a column of the table belongs to one ray.

G

H

height

g

h

slope

dg

dh

For TOY, G became (up -2 -1/2) and H became (up 0 -1/2). So the top row is −2 and 0, and the bottom row is −1/2 and −1/2.

sicm has a kind of data for exactly such a table. You build one row by row.

> (matrix-by-rows (list -2 0) (list -1/2 -1/2))
(matrix-by-rows (list -2 0) (list -1/2 -1/2))

It is called a matrix. I have heard the word and been afraid of it.

It is a table of numbers. Give it the same treatment you gave rays: a data definition, a constructor, and selectors with names.

To take a number out there is matrix-ref, with a row and a column, both counted from zero.

; A Transfer is a matrix with two rows and two
; columns:
; (matrix-by-rows (list g h) (list dg dh))
; interpretation what a column does to every ray,
; recorded as what it does to two: G arrives at
; height g with slope dg, and H arrives at
; height h with slope dh.
(define (make-transfer g h dg dh)
(matrix-by-rows (list g h) (list dg dh)))
(define (transfer-g t) (matrix-ref t 0 0))
(define (transfer-h t) (matrix-ref t 0 1))
(define (transfer-dg t) (matrix-ref t 1 0))
(define (transfer-dh t) (matrix-ref t 1 1))
(check-expect (transfer-h (make-transfer 1 2 3 4)) 2)
(check-expect (transfer-dg (make-transfer 1 2 3 4)) 3)

Now the function that boils a column down.

Trace G, trace H, and put the four numbers in their places.

; stack->transfer : ModuleStack -> Transfer
; sums up a column by tracing G and H
(check-expect (stack->transfer TOY)
(make-transfer -2 0 -1/2 -1/2))
(check-expect (stack->transfer TWO)
(make-transfer 1/6 0 2 6))
(define (stack->transfer ms)
(let ((g (trace-ray ms G))
(h (trace-ray ms H)))
(make-transfer (ray-x g) (ray-x h)
(ray-s g) (ray-s h))))

What is the Transfer of a single gap of length 5? Of a single lens of power 1/3? Work them out before you ask the machine.

A gap of 5: G stays (up 1 0), and H becomes (up 5 1). So 1 and 5 on top, 0 and 1 below. A lens of 1/3: G becomes (up 1 -1/3), and H is on the axis, so it stays (up 0 1). So 1 and 0 on top, −1/3 and 1 below.

(check-expect (stack->transfer (list (make-gap 5)))
(make-transfer 1 5 0 1))
(check-expect (stack->transfer (list (make-thin 1/3)))
(make-transfer 1 0 -1/3 1))

A Transfer is supposed to say what the column does to every ray. How do you get that out of it?

By the Law of Two Rays. The ray (make-ray x s) is x copies of G and s copies of H. So it comes out as x copies of where G went, plus s copies of where H went.

Its height is g·x + h·s. Its slope is dg·x + dh·s.

; apply-transfer : Transfer Ray -> Ray
; the ray after the column that t sums up
(check-expect
(apply-transfer (stack->transfer TOY) (make-ray 2 3))
(trace-ray TOY (make-ray 2 3)))
(check-expect
(apply-transfer (stack->transfer TWO) (make-ray 'x 's))
(trace-ray TWO (make-ray 'x 's)))
(define (apply-transfer t r)
(make-ray (+ (* (transfer-g t) (ray-x r))
(* (transfer-h t) (ray-s r)))
(+ (* (transfer-dg t) (ray-x r))
(* (transfer-dh t) (ray-s r)))))

Read your definition aloud, one row at a time.

The new height: go along the top row of the table, multiply each number by the matching field of the ray, and add. The new slope: the same with the bottom row.

Now ask the machine to multiply the table by the ray, with plain *.

> (* (stack->transfer TOY) (make-ray 2 3))
(up -4 -5/2)
> (apply-transfer (stack->transfer TOY) (make-ray 2 3))
(up -4 -5/2)

The same. The language’s * already does what I just wrote.

“Each row, times the tuple, added up” is what mathematicians mean by multiplying a matrix and a tuple. They invented it for exactly this purpose: to apply a rule like the Law of Two Rays. So you may forget the frightening word. A matrix is a table that remembers where G and H went, and multiplying by it is using the Law.

(check-expect
(* (stack->transfer TWO) (make-ray 'x 's))
(apply-transfer (stack->transfer TWO)
(make-ray 'x 's)))

In Chapter 3 you called the column a program and trace-ray its interpreter. What is stack->transfer?

A compiler. It runs the program twice, on G and on H, and afterwards any ray costs four multiplications, however long the column was.

Now learn to read the compiled column. (stack->transfer TOY) has −2 and 0 on top. What does it mean that h is 0?

The height that comes out is g·x + h·s. If h is 0, the s drops out: the slope the ray started with does not matter. Every ray from the same point lands at the same height.

That is what an image is.

And what does g mean then?

A ray that starts at height x lands at height g·x. So g is the magnification: −2 for TOY, 1/6 for TWO.

The Law of the Image.

A column forms an image where h is zero. There, g is the magnification.

Make the law into two small functions.

; image? : Transfer -> Boolean
; does the column that t sums up form an image
; at its last plane?
(check-expect (image? (stack->transfer TOY)) #t)
(check-expect
(image? (stack->transfer (list (make-gap 5)))) #f)
(define (image? t)
(= (transfer-h t) 0))
; magnification : Transfer -> Number
; assume: (image? t)
(check-expect (magnification (stack->transfer TOY)) -2)
(check-expect (magnification (stack->transfer TWO)) 1/6)
(define (magnification t)
(transfer-g t))

Compile a column whose parts are not chosen: a gap u, a lens of power p, a gap v.

> (stack->transfer
(list (make-gap 'u) (make-thin 'p) (make-gap 'v)))
(matrix-by-rows
(list (+ 1 (* -1 p v)) (+ (* -1 p u v) u v))
(list (* -1 p) (+ 1 (* -1 p u))))

The h in the top right is u + v − p·u·v. I have seen that before: it is what multiplied s in Chapter 2.

And the Law of the Image says?

An image forms when that is zero. The thin lens formula again, and this time I did not have to notice that every term had an s in it. The table kept the s part separate for me.

That is what a good data definition does. And the bottom right?

dh: the slope with which H arrives. A ray from the axis with slope s arrives with slope dh·s. For TOY it is −1/2, and for TWO it is 6.

Each time it is one over the magnification, as in Chapter 2.

Tomorrow you prove it.

Exercises

5.1 Design focus-gap. A column does not quite form an image at its last plane: its h is not 0. focus-gap consumes its Transfer and produces the length of the extra gap that must follow so that an image forms. (Trace H by hand through the extra gap first.)

(check-expect
(focus-gap (stack->transfer
(list (make-gap 3) (make-thin 1/2))))
6)

When is there no such gap? Compare exercise 1.1.

5.2 In the symbolic Transfer of gap, lens, gap, the magnification is 1 − p·v. Use the thin lens formula to show, on paper, that at an image this equals −v/u. Then check with u = 3, v = 6.

5.3 In your mind. A Transfer has dg equal to 0. What does the column do to level rays? What did exercise 3.2 call such a column?

5.4 What Transfer does the empty column '() have? Predict, then ask. What does multiplying by it do to a ray?

6 What No Lens Can Change🔗

One number that every column agrees on, and what it forbids.

Twice now you have seen heights multiplied by some number and slopes by one over it. I promised you would prove it. Here is a quantity to compute, for TOY and for TWO: g times dh, minus h times dg.

For TOY the table is −2, 0 over −1/2, −1/2. So (−2)·(−1/2) − 0·(−1/2), which is 1.

For TWO it is 1/6, 0 over 2, 6. So (1/6)·6 − 0·2. Also 1.

Along one diagonal of the table, multiply; along the other, multiply; subtract. That quantity has a name, the determinant, and sicm knows it.

> (determinant (stack->transfer TOY))
1
> (determinant (stack->transfer TWO))
1

One, both times. With two different microscopes.

Coincidence?

I have learned not to say so. Let me try the smallest columns there are: one gap, one lens. And let me not choose their sizes.

> (stack->transfer (list (make-gap 'd)))
(matrix-by-rows (list 1 d) (list 0 1))
> (determinant (stack->transfer (list (make-gap 'd))))
1
> (stack->transfer (list (make-thin 'p)))
(matrix-by-rows (list 1 0) (list (* -1 p) 1))
> (determinant (stack->transfer (list (make-thin 'p))))
1

For the gap: 1·1 − d·0. For the lens: 1·1 − 0·(−p). Each kind of module has determinant 1 by itself, whatever its length or power.

So the single modules are settled. What is left to understand?

What happens to the determinant when one column follows another.

Then first: what is the Transfer of one column followed by another? Suppose t1 sums up the first and t2 the second. Where does G end up?

The first column sends G to the ray (make-ray g1 dg1): the left-hand column of the table t1. That ray then goes through the second column, and t2 knows what the second column does to any ray. The same for H, with the right-hand column of t1.

; then : Transfer Transfer -> Transfer
; the transfer of the column summed up by t1,
; followed by the column summed up by t2
(check-expect
(then (stack->transfer TOY) (stack->transfer TWO))
(stack->transfer (append TOY TWO)))
(define (then t1 t2)
(let ((g (apply-transfer
t2 (make-ray (transfer-g t1)
(transfer-dg t1))))
(h (apply-transfer
t2 (make-ray (transfer-h t1)
(transfer-dh t1)))))
(make-transfer (ray-x g) (ray-x h)
(ray-s g) (ray-s h))))

In Chapter 5 the system’s * turned out to be your apply-transfer. Try multiplying two Transfers.

> (then (stack->transfer TOY) (stack->transfer TWO))
(matrix-by-rows (list -1/3 0) (list -7 -3))
> (* (stack->transfer TOY) (stack->transfer TWO))
(matrix-by-rows (list -1/3 0) (list -13/12 -3))
> (* (stack->transfer TWO) (stack->transfer TOY))
(matrix-by-rows (list -1/3 0) (list -7 -3))

The first product is close, but its bottom-left number is wrong. It is then only when I write the second column on the left.

Why would anyone want that order?

Because of how it is used. (* t2 (* t1 ray)): the Transfer nearest the ray acts first. It is the nested parentheses of Chapter 3 all over again, read from the inside.

(check-expect
(* (stack->transfer TWO) (stack->transfer TOY))
(then (stack->transfer TOY) (stack->transfer TWO)))

So the order matters for Transfers, as it did for columns. Now the question you asked: what does then do to determinants? Try numbers first.

> (determinant (make-transfer 2 3 5 7))
-1
> (determinant (make-transfer 1/2 4 -1 9))
17/2
> (determinant (then (make-transfer 2 3 5 7)
(make-transfer 1/2 4 -1 9)))
-17/2

Minus one times seventeen halves is minus seventeen halves. The determinants multiplied.

For those two tables. The First Commandment.

Two tables of unchosen numbers: eight symbols.

(define T1 (make-transfer 'a 'b 'c 'd))
(define T2 (make-transfer 'e 'f 'g 'h))
(check-expect (determinant (then T1 T2))
(* (determinant T1) (determinant T2)))

It passes. For every pair of tables there is.

If you multiply that out with pencil and paper, eight terms appear, four of them cancel in pairs, and the four that are left are the product of the two determinants. Do it once in your life; it is exercise 6.1. The machine has just done it for you.

Now put the pieces together.

Every single module has determinant 1. Following one column by another multiplies the determinants. A column is one module after another. One times one times one…

Every column of gaps and thin lenses has determinant exactly 1. However many modules, whatever their sizes.

Try a column with five unchosen parts.

(check-expect
(determinant
(stack->transfer
(list (make-gap 'a) (make-thin 'p) (make-gap 'b)
(make-thin 'q) (make-gap 'c))))
1)
> (transfer-h
(stack->transfer
(list (make-gap 'a) (make-thin 'p) (make-gap 'b)
(make-thin 'q) (make-gap 'c))))
(+ (* a b c p q) (* -1 a b p) (* -1 a c p)
(* -1 a c q) (* -1 b c q) a b c)

The four numbers in that table are each a tangle like this one. And the determinant of the whole tangle is 1.

The Law of the Determinant.

For every column, g times dh minus h times dg is exactly 1.

Now prove your promise from Chapter 2.

At an image, h is 0. So the law says g·dh − 0 = 1. So dh is 1/g.

The slopes are multiplied by one over the magnification. Always. In every column that will ever be built out of gaps and thin lenses.

Say it as a designer would hear it.

If I build a column that makes the image of the source a hundred times smaller, the electrons arrive at angles a hundred times steeper. No arrangement of lenses can make a spot both smaller and gentler.

That is called the Lagrange–Helmholtz relation, and it is the first thing a column designer runs into. Notice how you found it. You did not solve a problem about one microscope. You found a quantity that no module can change, and so no microscope can.

In HtDP, when I wrote a function with an accumulator, I had to write down what stayed true about it at every step. An accumulator invariant.

The ray is the accumulator. The Transfer is what has been accumulated. And this is its invariant: a thing that stays true however long the fold runs.

The Third Commandment.

Name the invariant before you compute. What nothing can change tells you more than what something happens to do.

Which was more work in these last three chapters: the programs, or the thinking?

The programs were selectors and some multiplication. The thinking was noticing that nothing was squared.

This is a good place to stop for the evening.

Exercises

6.1 With pencil and paper, write out the four numbers of (then T1 T2) in terms of the eight symbols, and show that its determinant is the product of the two determinants. Then ask the machine for (then T1 T2) and compare with your four.

6.2 In your mind. A column has magnification −1/20. An electron leaves the source at a slope of 1/1000. At what slope does it arrive? If an aperture in front of the target only admits slopes up to 1/100, what is the steepest slope at the source that gets through?

6.3 The telescope of exercise 3.2 does not form an image, so h is not 0. What does the Law of the Determinant say about it instead? (Look at which of its four numbers is 0.)

6.4 Could a column ever have a Transfer with g = 2, h = 0, dg = 0, dh = 2: twice as big, and twice as steep? Could it have g = 2, h = 0, dg = 5, dh = 1/2?

7 Thick Lenses Are Many Thin Ones🔗

In which a lens is built with map, and numbers are allowed to forget.

A real electron lens is a magnetic field that fills a stretch of the column. The electron is bent a little at every step of the way through it. Is that a thin?

No. A thin bends the ray once, at one plane. And it is not a gap, where nothing bends at all. It is both at the same time.

Must you extend the data definition?

Perhaps not. I could cut the thick lens into slices. If a slice is short enough, the ray hardly moves while it is being bent, so the slice is nearly a thin lens with a little empty space around it.

Take a thick lens one unit long, and be crude: one slice. Where in the slice do you put the thin lens?

In the middle. Half a unit of gap, the kick, half a unit of gap.

And what is the power of the thin lens? Say the whole thick lens is “worth” a power of 1.

Then the one slice gets all of it.

> (trace-ray (list (make-gap 1/2) (make-thin 1)
(make-gap 1/2))
H)
(up 3/4 1/2)

Now two slices.

Each is half a unit long: a quarter of gap, a kick, a quarter of gap. And each gets half the power, because powers add: exercise 1.3.

> (trace-ray (list (make-gap 1/4) (make-thin 1/2)
(make-gap 1/4)
(make-gap 1/4) (make-thin 1/2)
(make-gap 1/4))
H)
(up 105/128 17/32)

You said “half the power, because it is half as long”. So what is it that stays the same from slice to slice?

The power per unit length. A slice of length dz has power dz times that.

Call that number the stiffness of the lens, and write it kk. You will see in Chapter 8 why it deserves two letters. In a real lens the field is stronger in some places than others, so let the stiffness be a function of z. For the lens you just sliced by hand:

; always-1 : Number -> Number
; the stiffness of a lens that is the same all along
(define (always-1 z) 1)

Now design the function that does the slicing.

It consumes the stiffness function, where the lens starts and stops, and how many slices. It produces a ModuleStack. The slices are numbered 0, 1, 2, …, so build-list makes them. Each slice asks for the stiffness at its own middle. And each slice is a list of three modules, so at the end I must join the little lists into one.

; slice-lens :
; [Number -> Number] Number Number N -> ModuleStack
; the thick lens between z0 and z1 whose stiffness
; at z is (kk z), cut into n slices
(check-expect
(slice-lens always-1 0 1 1)
(list (make-gap 1/2) (make-thin 1) (make-gap 1/2)))
(check-expect
(slice-lens always-1 0 1 2)
(list (make-gap 1/4) (make-thin 1/2) (make-gap 1/4)
(make-gap 1/4) (make-thin 1/2) (make-gap 1/4)))
(define (slice-lens kk z0 z1 n)
(define dz (/ (- z1 z0) n))
; N -> ModuleStack
; slice number i: its lens sits at its middle
(define (slice i)
(let ((mid (+ z0 (* (+ i 1/2) dz))))
(list (make-gap (/ dz 2))
(make-thin (* dz (kk mid)))
(make-gap (/ dz 2)))))
(apply append (build-list n slice)))

The two defines inside are what local used to be for.

You have written a function that writes programs in the language of Chapter 3. What will run them?

trace-ray. I do not need anything new.

> (slice-lens always-1 0 1 1)
(list (make-gap 1/2) (make-thin 1) (make-gap 1/2))
> (trace-ray (slice-lens always-1 0 1 2) H)
(up 105/128 17/32)

The same as my two slices by hand.

Keep doubling. Look only at the height.

> (ray-x (trace-ray (slice-lens always-1 0 1 4) H))
876897/1048576
> (ray-x (trace-ray (slice-lens always-1 0 1 8) H))
7567645162888065/9007199254740992

The fractions are getting ugly. Sixteen digits on top already.

Why?

Each slice multiplies and adds fractions exactly, and exact fractions have to remember everything. A thousand slices would give a numerator thousands of digits long.

Exact numbers are for facts you want to prove. For a long walk, let the numbers forget. How do you make a number forgetful?

Chapter 0: a decimal point. And rounding is catching, so one point at the start is enough. I will write the end of the lens as 1. instead of 1.

> (ray-x (trace-ray (slice-lens always-1 0 1. 2) H))
0.8203125
> (ray-x (trace-ray (slice-lens always-1 0 1. 4) H))
0.8362741470336914
> (ray-x (trace-ray (slice-lens always-1 0 1. 8) H))
0.8401773902031523
> (ray-x (trace-ray (slice-lens always-1 0 1. 16) H))
0.8411479343205968

The Fourth Commandment.

Exact numbers for theorems. Inexact numbers for journeys.

With one slice you had 3/4, which is .75. Look at the five numbers in a row. Are they going anywhere?

.75, .820, .836, .840, .841. They are settling down. Each step is smaller than the one before.

How much smaller? Take the differences.

From .75 to .820 is .070. Then .016. Then .0039. Then .0010. Each step is about a quarter of the one before it.

Suppose it goes on that way for ever. Where does it end?

If each step is a quarter of the last, then all the steps still to come add up to a third of the last one I took. A third of .0010 is .0003. So about .8414 or .8415.

It is closing in on .8414709848. Let me give you that number to keep.

(define TARGET .8414709848078965)

How far away is each of your tries?

> (- TARGET
(ray-x (trace-ray (slice-lens always-1 0 1. 8) H)))
0.0012935946047442082
> (- TARGET
(ray-x (trace-ray (slice-lens always-1 0 1. 16) H)))
0.0003230504872997475

.0013 and then .00032. The miss shrinks to a quarter when I double the slices. So the misses and the steps both quarter.

Then predict the miss with 32 slices, before you run it.

A quarter of .00032: about .00008.

> (- TARGET
(ray-x (trace-ray (slice-lens always-1 0 1. 32) H)))
8.074090433840553e-5

I predicted the fifth digit of an answer before computing it.

That is a more useful skill than it looks, and Chapter 10 will give it a name. One test, to pin down what you have:

(check-within
(ray-x (trace-ray (slice-lens always-1 0 1. 100) H))
TARGET
1e-5)

Where did you get TARGET from? Did you use a million slices?

I typed (sin 1).

The sine? Of what angle? There are no angles here. There is a lens.

Sleep on it.

Exercises

7.1 Send G through (slice-lens always-1 0 1 n) for n = 1, 2 and 4, exactly. Then inexactly for 8, 16 and 32. The heights close in on .5403023058681398. Do the misses quarter?

7.2 Design slice-lens.v0, which puts each thin lens at the start of its slice (a kick, then one whole gap) instead of in the middle. Send H through one unit of stiffness 1 with 8, 16 and 32 slices. By what factor does the miss shrink when you double the slices now? Which design would you rather pay for?

7.3 In your mind. A slice has length 1/10 and sits where the stiffness is 3. What is the power of its thin lens? What is its focal length? Is the slice “thin”, compared with its own focal length?

7.4 Trace H exactly through (slice-lens always-1 0 1 16), and count the digits of the numerator with (string-length (number->string ...)). Then 32 slices. Guess the rule.

8 Two Old Friends🔗

The ray inside the simplest thick lens turns out to be someone you know.

Yesterday H went one unit into a lens of stiffness 1, and its height came out as (sin 1). Before I explain, look further. Make the lens longer. Where is H after 1, 2, 3 and 4 units? Use a thousand slices.

; wave : Number -> Number
; the height of H after a length len of stiffness 1
(define (wave len)
(ray-x
(trace-ray
(slice-lens always-1 0 (exact->inexact len) 1000)
H)))
> (wave 1)
0.8414709...
> (wave 2)
0.9092968...
> (wave 3)
0.1411187...
> (wave 4)
-0.7568027...

It rises, turns over, and comes back down through the axis somewhere between 3 and 4.

Why does it turn over? Think about what the lens does to a ray that is high above the axis.

The higher the ray, the harder each slice kicks it downward. So as it climbs, its slope is eaten away faster and faster, until the slope is zero and it starts to fall. And once it is below the axis, the kicks push it back up.

It will go on like that for ever. It is a wave.

Where does it first come back to the axis?

> (wave 3.1)
0.0415793...
> (wave 3.2)
-0.0583754...
> (wave 3.14)
0.0015913...
> (wave 3.15)
-0.0084085...

The last two are small: 1.59 thousandths above the axis, then 8.41 thousandths below. So between 3.14 and 3.15.

That is π. What is a circle doing inside a lens?

Chapter 12 will answer that properly. Here is the short answer. You know a function that starts at 0, rises with slope 1, peaks at 1, and returns to 0 at π.

The sine. So (wave len) is (sin len)?

(check-within (wave 1) (sin 1) 1e-6)
(check-within (wave 2) (sin 2) 1e-6)
(check-within (wave pi) 0 1e-5)

They pass. And pi is a word this system knows.

H gives the sine. What does G give? Compile the lens, for a length of 2, and compare with what you suspect.

G starts at height 1, flying level. The function that starts at 1 and level is the cosine.

> (stack->transfer (slice-lens always-1 0 2. 1000))
(matrix-by-rows
(list -0.41614... 0.90929...)
(list -0.90929... -0.41614...))
> (cos 2)
-0.4161468365471424
> (sin 2)
0.9092974268256817

G gives the cosine. And the bottom row, the slopes, are minus the sine and the cosine.

(check-within
(stack->transfer (slice-lens always-1 0 2. 1000))
(make-transfer (cos 2) (sin 2) (- (sin 2)) (cos 2))
1e-5)

So sine and cosine are not about triangles. They are the two rays of the simplest thick lens.

The axial ray H in a lens of stiffness 1. Four slices per unit (straight pieces) already follow the sine closely. The ray returns to the axis at π: a lens this long images its own entrance onto its exit.

The axial ray H in a lens of stiffness 1. Four slices per unit (straight pieces) already follow the sine closely. The ray returns to the axis at π: a lens this long images its own entrance onto its exit.

They are about both, which is the surprise waiting in Chapter 12. Now use what you know from Chapter 5. A lens of stiffness 1 and length π: read its Transfer.

Its h is (sin pi), which is 0. So it forms an image: a point at its entrance is imaged at its exit. The magnification is g, which is (cos pi): −1. Same size, upside down.

And the Law of the Determinant, for a lens of any length len?

g·dh − h·dg is cos times cos, minus sin times minus sin. Cosine squared plus sine squared.

> (determinant
(make-transfer (cos 'len) (sin 'len)
(- (sin 'len)) (cos 'len)))
1

The machine knows that it is 1. I learned that as a fact about triangles. It is the Law of the Determinant!

Your sliced lens is only approximately right about where the ray goes. Is it approximately right about the determinant?

I expect it to be a little off, like the heights. With four crude slices, exactly:

(check-expect
(determinant
(stack->transfer (slice-lens always-1 0 1 4)))
1)

It is exactly 1. With check-expect!

Why?

Because a sliced lens is still a column of gaps and thin lenses, and the law holds for every such column. Slicing makes mistakes about heights and slopes. It cannot make a mistake about the determinant.

Remember that. When you choose how to approximate, you choose which truths survive the approximation.

Now, stronger lenses. Suppose the stiffness is 4 all along. Before you run anything: will H come back to the axis sooner than π, or later?

Sooner. Every kick is four times as hard.

How much sooner?

A quarter of the distance?

; always-4 : Number -> Number
(define (always-4 z) 4)
> (ray-x (trace-ray (slice-lens always-4 0 .7853 1000) H))
0.4999998...
> (ray-x (trace-ray (slice-lens always-4 0 1.5707 1000) H))
9.568...e-5

At a quarter of π it is at its highest, a half. It comes back at 1.5707, which is half of π. Four times the stiffness, half the distance.

So the distance goes as…

One over the square root of the stiffness.

That is why the stiffness has two letters. Write k for its square root. Then k is what sets the pace of the wave, and the stiffness is k times k. With stiffness 4, k is 2, and you saw H peak at a half. Guess the formula for H.

It must be a sine that goes twice as fast: (sin (* 2 z)). But that peaks at 1, and mine peaked at 1/2. So half of it: (/ (sin (* 2 z)) 2). In general, (/ (sin (* k z)) k).

(check-within
(ray-x (trace-ray (slice-lens always-4 0 .7 1000) H))
(/ (sin (* 2 .7)) 2)
1e-6)

Why must it be divided by k? Think about how H starts.

H leaves the axis with slope 1. A sine that goes k times as fast is k times as steep at the start. Dividing by k brings the starting slope back to 1.

And where does a uniform lens with pace k image its own entrance?

Where (sin (* k z)) returns to zero: at π over k. A stiffer lens focuses sooner.

You came to these two chapters with gaps and thin lenses. What do you leave with?

A way to build any lens whatever out of them, if someone tells me its stiffness along the axis. And the knowledge that I will never have to draw a triangle to understand a sine.

Exercises

8.1 In your mind. A lens of stiffness 1 has length π/2. A level ray enters at height 3. Where is it when it leaves, and with what slope? What would an opticist call the exit plane?

8.2 A lens of stiffness 1 and length π images its entrance onto its exit. Without running anything, what does a lens of length 2π do? Then confirm it: what is its Transfer, to five places?

8.3 Guess the formula for G in a lens of pace k, and for the two slopes. Write the whole Transfer with make-transfer, and check its determinant with k and the length as symbols. Then test it against 1000 slices of stiffness 4.

8.4 If you like pictures, DrRacket will draw them in the interactions window:

> (require (only-in plot plot function))
> (plot
(list (function sin 0 7)
(function
(lambda (len)
(ray-x
(trace-ray (slice-lens always-1 0 len 8) H)))
0 7 #:style 'long-dash)))

The second curve is H through only eight slices, whatever the length. Where does it leave the sine, and why there?

Interlude The Endless Column🔗

A gap and a lens, and then the same again, for ever. One cell says what becomes of the ray.

A cell is a gap followed by a thin lens. Build one, and compile it.

; forever-cell : Number Number -> ModuleStack
; a gap of length d, then a thin lens of power p
(check-expect (forever-cell 1 1/2)
(list (make-gap 1) (make-thin 1/2)))
(define (forever-cell d p)
(list (make-gap d) (make-thin p)))
(define GENTLE (stack->transfer (forever-cell 1 1/2)))
(check-expect GENTLE (make-transfer 1 1 -1/2 1/2))
(check-expect (determinant GENTLE) 1)

Now the same cell again, and again. Design cells: the Transfer of n of them. What kind of data is n?

A natural number: 0, or one more than a natural number. No cells leave G and H as they are: 1 and 0 on top, 0 and 1 below. And n cells are one cell, then the other n − 1.

; cells : N Transfer -> Transfer
; sums up n copies, end to end, of the column that
; t sums up
(check-expect (cells 0 GENTLE) (make-transfer 1 0 0 1))
(check-expect (cells 2 GENTLE) (then GENTLE GENTLE))
(define (cells n t)
(cond
((= n 0) (make-transfer 1 0 0 1))
(else (then t (cells (- n 1) t)))))

The column I want has no last cell. Make me the list of the rays in it: after no cells, after one, after two, and so on.

I cannot. A list is '() or a cons, and whatever I build stops.

What will you ever ask of that list?

Its item number n, for some n I name. A function of n answers that.

; A [Forever X] is a function: N -> X
; interpretation an endless list of X, given by the
; rule for its item number n, counted from 0.
; forever : Transfer Ray -> [Forever Ray]
; the ray r after n of the cells that t sums up
(check-expect ((forever GENTLE (make-ray 1 0)) 0)
(make-ray 1 0))
(check-expect ((forever GENTLE (make-ray 1 0)) 2)
(make-ray 1/2 -3/4))
(define ((forever t r) n)
(apply-transfer (cells n t) r))

Some languages build an endless list by promising each item and computing it when asked. Did you need that?

No. A function already waits to be asked.

A level ray at height 1 enters. Where is it after 1, 10, 100 and 1000 cells? A journey: inexact numbers.

> (map (forever GENTLE (make-ray 1. 0))
(list 1 10 100 1000))
(list
(up 1.0 -0.5)
(up 0.8925... -0.6123...)
(up -1.0062... 0.0126...)
(up 1.0491... -0.1263...))

After a thousand lenses it is about as far from the axis as when it started. It wanders, and it stays.

Now make the lens ten times as strong: power 5. Before you run it: what becomes of the ray?

A stronger lens holds the beam closer to the axis. It stays, and it stays smaller.

(define STRONG (stack->transfer (forever-cell 1 5)))
> (map (forever STRONG (make-ray 1. 0))
(list 1 10 100 1000))
(list
(up 1.0 -5.0)
(up -9349.0 33825.0)
(up -3.877...e+41 1.402...e+42)
(up -inf.0 +inf.0))

I was wrong. After ten cells it is nine thousand units out. After a thousand the machine has run out of numbers.

Which step of the recipe comes before running?

The examples, by hand. Gap: (up 1 0). Lens of power 5: (up 1 -5). Gap: (up -4 -5). Lens: (up -4 15). One more gap puts it at 11. Each lens throws it across the axis, further out than it came. Two cells by hand would have told me, and I asked for a thousand by machine.

One cell holds a ray and the other throws it out. Add the two corners of the table that lie on the diagonal from g to dh, and halve.

; half-corner-sum : Transfer -> Number
; half of g plus dh
(check-expect (half-corner-sum GENTLE) 3/4)
(check-expect (half-corner-sum STRONG) -3/2)
(define (half-corner-sum t)
(/ (+ (transfer-g t) (transfer-dh t)) 2))

Chapter 8. The uniform lens of stiffness 1 and length len: what is its half corner sum? And that of n such lenses, end to end?

Its g and its dh are both (cos len), so (cos len). And n of them are one lens of length n times len: (cos (* n len)). A cosine, so between −1 and 1 however many there are.

(acos c) is the length between 0 and π whose cosine is c. Which length of uniform lens has the 3/4 of GENTLE?

; forever-angle : Transfer -> Number
; the length of uniform lens of stiffness 1 with the
; half corner sum of t
; assume: that half corner sum is between -1 and 1
(check-within (forever-angle GENTLE) .7227 1e-4)
(define (forever-angle t)
(acos (half-corner-sum t)))

GENTLE is not that lens. The two tables share one number. Here is a theorem about every table whose determinant is 1: if two of them share that number once, their repetitions share it for ever. Test it.

(check-within (half-corner-sum (cells 3 GENTLE))
(cos (* 3 (forever-angle GENTLE)))
1e-12)
(check-within (half-corner-sum (cells 50 GENTLE))
(cos (* 50 (forever-angle GENTLE)))
1e-9)

They pass. The half corner sums of GENTLE, repeated, march along a cosine. And STRONG has −3/2, and nothing has a cosine of −3/2.

A cell whose half corner sum lies between −1 and 1 is stable. Now do not choose the gap or the power.

(check-expect
(half-corner-sum
(stack->transfer (forever-cell 'd 'p)))
(- 1 (* 1/2 'p 'd)))

One, less half of p times d. That lies between −1 and 1 when p times d lies between 0 and 4. For GENTLE the product is 1/2. For STRONG it is 5. I could have refused STRONG without running it.

“It stays” was a claim about a thousand cells. For ever is longer. Name the invariant: what does one cell leave unchanged?

The determinant. But that is a fact about the table, and I need a fact about the ray.

Here is a function of the ray. Test whether one cell changes it.

; forever-kept : Number Number -> [Ray -> Number]
; for the cell of gap d and power p: a number that
; a ray has, and that the cell does not change
(check-expect
((forever-kept 'd 'p)
(apply-transfer
(stack->transfer (forever-cell 'd 'p))
(make-ray 'x 's)))
((forever-kept 'd 'p) (make-ray 'x 's)))
(define ((forever-kept d p) r)
(+ (* p (square (ray-x r)))
(* p d (ray-x r) (ray-s r))
(* d (square (ray-s r)))))

It passes with four symbols. Every ray, every gap, every power: one cell leaves that number alone. So two cells do, and a thousand, and all of them.

For GENTLE, how does a number that never changes keep the ray near the axis?

It is a sum of two squares.

(check-expect ((forever-kept 1 1/2) (make-ray 1 0)) 1/2)
(check-expect
((forever-kept 1 1/2) (make-ray 'x 's))
(+ (* 7/16 (square 'x))
(square (+ 's (* 1/4 'x)))))

Neither square can be negative. So 7/16 of the height squared can never exceed the 1/2 that my ray came in with. Its height stays within the square root of 8/7, which is 1.069, for ever. The largest the machine showed me was 1.049.

And STRONG?

(check-expect
((forever-kept 1 5) (make-ray 'x 's))
(- (square (+ 's (* 5/2 'x)))
(* 5/4 (square 'x))))

A difference of squares. Both may grow as large as they like, so long as they grow together. The number is kept, and it holds nothing in.

You have settled a column with no end. How many cells did you run?

One, with symbols in it. I never built the endless column. I asked what one cell leaves unchanged.

You have made that move before.

With Y. I described one step, and something that stayed the same from step to step did the rest. There it was a function, handed to itself. Here it is a number, handed on unchanged.

Keep the move in mind. Near the end of this book it is made once more, and that time on the book.

On the book?

Finish your tea first.

Exercises

8x.1 A cell with a gap of 1 and a lens of power 1. Compute its half corner sum and its angle. After how many cells does every ray return to where it began? State your answer as a check-expect on cells, with exact numbers. Do the same for power 2 and for power 3.

8x.2 The edges. Run (forever (stack->transfer (forever-cell 1 4)) (make-ray 1 0)) at 1, 2, 3, 10, 100 and 1000. Does the ray stay? Does it explode? Then the other edge: a cell with no lens at all. What do the two edges have in common?

8x.3 One slice of the uniform lens is a cell: (slice-lens always-1 0 'w 1). Find its half corner sum with the symbol. For which widths w is the sliced lens stable? Then choose w = 1/4 and compute the cell’s angle. The true lens turns its wave by exactly 1/4 in that length. Which of Chapter 7’s errors have you just measured?

9 The Slope Machine🔗

A function that eats a path and returns its slope. With it, a lens is one sentence.

In Chapter 1 a ray was two numbers at one plane. Now think of the whole flight of one electron. For each z there is a height. What kind of thing is that?

A function from Number to Number. The path of the electron.

Here is the path of an electron that starts at height 1 and climbs steadily at slope 1/2, in empty space.

; line : Number -> Number
; the height at z of a ray that leaves height 1
; at z = 0 with slope 1/2 and meets nothing
(check-expect (line 0) 1)
(check-expect (line 4) 3)
(define (line z) (+ 1 (* 1/2 z)))

Suppose I hand you only the function line, and not its definition. Can you find its slope?

Rise over run. Take two values of z a little apart, see how much the height changed, and divide by how far apart they were.

Do it between z = 7 and z = 8.

(line 8) is 5 and (line 7) is 9/2. The rise is 1/2, the run is 1. A half.

Make it a function. It consumes a path and a run. What does it produce?

The slope may be different at every z. So it produces a slope for each z: another function.

; slope-near :
; [Number -> Number] Number -> [Number -> Number]
; the function that gives, at each z, the rise of
; f between z and z + run, over the run
(check-expect ((slope-near line 1) 7) 1/2)
(check-expect ((slope-near line 1/10) -100) 1/2)
(define (slope-near f run)
(lambda (z)
(/ (- (f (+ z run)) (f z))
run)))

A function that consumes a function and produces a function. Does that frighten you?

No. (slope-near line 1) is a function; ((slope-near line 1) 7) is a number. Two pairs of parentheses, one for each step.

For a straight line the run does not matter. Try a path that bends: square. What is its slope near 3?

> ((slope-near square 1) 3)
7
> ((slope-near square 1/10) 3)
61/10
> ((slope-near square 1/100) 3)
601/100
> ((slope-near square 1/1000) 3)
6001/1000

It depends on the run. 7, then 6.1, 6.01, 6.001.

Which of those is the slope of square at 3?

None of them. Each is the slope of a straight line drawn between two points on the curve. But as the two points close up, the answers close in on 6. I would say the slope at 3 is 6: what the answers approach as the run shrinks to nothing.

Can you see why 6? Do not choose the run.

> ((slope-near square 'run) 3)
(+ 6 run)

Six plus the run. So with a run of 1/1000 it is 6.001, and with no run at all it would be 6.

But I cannot put in a run of zero. That would divide by zero.

You cannot. But you have a formula now, and in the formula you can see what happens. Do not choose the place either.

> ((slope-near square 'run) 'z)
(+ run (* 2 z))

Twice z, plus the run. When the run shrinks to nothing, twice z is left. The slope of square at any z is 2·z.

Try the cube.

> ((slope-near cube 'run) 'z)
(+ (expt run 2) (* 3 run z) (* 3 (expt z 2)))

Three terms. Two of them have the run in them and will vanish with it. What is left is 3·z².

“Find the formula, then let the run vanish” is the first idea of the calculus. sicm has a function that does both steps. It is called D.

> ((D square) 'z)
(* 2 z)
> ((D cube) 'z)
(* 3 (expt z 2))
> ((D line) 'z)
1/2
> ((D square) 3)
6

No run anywhere. It gives the slope at the place, exactly.

D consumes a function and produces its slope function.

(check-expect ((D line) 7) 1/2)
(check-expect ((D square) 3) 6)
(check-expect ((D square) 'z) (* 2 'z))
(check-expect ((D cube) 'z) (* 3 (square 'z)))

Now a function you met yesterday. What is the slope of the sine?

With slope-near first.

> ((slope-near sin .001) 0)
0.9999998333333416
> ((slope-near sin .001) 1)
0.5398814803603269
> (cos 1)
0.5403023058681398

Near 0 the slope is nearly 1, which is right: H leaves the axis with slope 1. Near 1 it is close to (cos 1). Is the slope function of the sine the cosine?

Ask D.

> ((D sin) 'z)
(cos z)
> ((D cos) 'z)
(* -1 (sin z))

The slope of sin is cos. The slope of cos is minus sin.

But I knew that already! In Chapter 8, the bottom row of the table was the slopes: H had height sin and slope cos, and G had height cos and slope minus sin.

You measured it with a thousand slices. D knows it as a rule. How does D know?

I cannot guess. For square I could see the run cancel. For sin there is nothing to cancel.

D does not measure anything. It carries a small book of rules, such as “the slope of sin is cos”, “the slope of a sum is the sum of the slopes”, and a rule for a function inside a function. It reads the program you hand it and applies the rules, piece by piece. It is an interpreter for your function that computes slopes instead of values.

A function that reads my function as data. Like trace-ray reading a column.

Now we can say what a lens does in one sentence. Call the path x and its slope function s. That is: s is (D x). In a gap, what is (D s)?

In a gap the slope stays. A function that stays has slope 0. So (D s) is 0 everywhere.

In a thick lens of stiffness kk, look at one slice of length dz. By how much does the slope change across it?

The slice kicks with power dz·kk, so the slope is lowered by dz·kk times the height.

Rise over run, for the slope.

The rise of the slope is minus dz·kk·x. The run is dz. Divide: minus kk·x. And that does not depend on how thin the slice is, so it is what is left when dz vanishes.

(D s) is minus kk times x.

Put your two sentences together.

s is (D x). And (D s) is minus kk times x. So (D (D x)) is minus kk times x.

The slope of the slope of the path is minus the stiffness times the path.

The Law of the Round Lens, first half.

Inside a lens, the slope of the slope of a ray is minus the stiffness times its height.

Books write that as x″ = −k²·x and call it the paraxial ray equation. It says everything slice-lens says, with no slices. Test it on the ray you know.

With stiffness 1 the axial ray is the sine. So the slope of the slope of the sine must be minus the sine.

> ((D (D sin)) 'z)
(* -1 (sin z))
(check-expect ((D (D sin)) 'z) (- (sin 'z)))
(check-expect ((D (D cos)) 'z) (- (cos 'z)))

Both rays of the uniform lens obey the sentence. Exactly, at every z.

And the lens of pace k, whose axial ray you guessed yesterday from one measurement?

(/ (sin (* k z)) k), with stiffness k squared. Let me leave k unchosen.

; h-uniform : Number -> [Number -> Number]
; the axial ray of a uniform lens of pace k
(define (h-uniform k)
(lambda (z) (/ (sin (* k z)) k)))
(check-expect
(+ ((D (D (h-uniform 'k))) 'z)
(* (square 'k) ((h-uniform 'k) 'z)))
0)
(check-expect ((h-uniform 'k) 0) 0)
(check-expect ((D (h-uniform 'k)) 0) 1)

The slope of the slope, plus the stiffness times the height, is zero. It starts on the axis. It starts with slope 1. For every pace.

Yesterday that formula was a guess checked at one point with a thousand slices. Today it is proved.

That is the difference between simulating and knowing, and you will feel it most in Chapter 13.

Exercises

9.1 Use slope-near with a symbolic run to find the slope function of (lambda (z) (/ 1 z)). What is left when the run vanishes? Compare with D.

9.2 What is ((D (D line)) 'z)? Say why in terms of rays, without computing.

9.3 Design g-uniform, the field ray of a uniform lens of pace k, and prove with three symbolic check-expects that it obeys the lens equation, starts at height 1, and starts level.

9.4 In your mind. The slope function of a path is negative everywhere. What is the ray doing? The slope of the slope is negative everywhere. What can you say about the ray then?

10 Laws🔗

A law says how fast things change here. A stepper turns that into where things are over there.

Yesterday’s sentence, “the slope of the slope is minus the stiffness times the height”, tells you about a ray at one place. Suppose you know the ray at one place. What exactly must you know, to carry on from there?

Its height and its slope, as always. And where I am: the stiffness may be different at different z.

Three numbers. Make them a tuple.

; A State is a tuple: (up Number Number Number)
; interpretation (up z x s): at the place z along
; the axis, a ray is x above the axis and climbs
; with slope s.
(define (state-z y) (ref y 0))
(define (state-x y) (ref y 1))
(define (state-s y) (ref y 2))

It is a Ray that remembers where it is.

Now, for each of the three numbers, say how fast it grows as the electron moves along the axis. Per unit of z: how much does z grow?

By one. Obviously.

Obvious things have to be said to machines. How much does x grow?

By the slope: s. That is what slope means.

And s?

Yesterday’s sentence: by minus the stiffness times x.

Three numbers going in, three rates coming out. A function of that kind is called a law.

; A Law is a function: State -> State
; interpretation given the state at one place,
; how fast each of its numbers is growing there,
; per unit of distance along the axis.
; lens-law : [Number -> Number] -> Law
; the law of a lens whose stiffness at z is (kk z)
(check-expect ((lens-law always-4) (up 0 3 5))
(up 1 5 -12))
(define (lens-law kk)
(lambda (y)
(up 1
(state-s y)
(- (* (kk (state-z y)) (state-x y))))))

At height 3 with slope 5 in a lens of stiffness 4: the place grows at 1, the height at 5, and the slope at −12.

A law tells you the rates here. You want the state over there, a short step dz further on. What is the simplest thing to do?

Believe the rates for the whole step. Each number moves by dz times its rate.

The state is a tuple and the rates are a tuple.

And tuples can be scaled and added! Scale the rates by dz and add them to the state.

; euler-step : Law Number State -> State
; the state a step dz further on, trusting the
; rates at the start for the whole step
(check-expect
(euler-step (lens-law always-4) 1/10 (up 0 3 5))
(up 1/10 7/2 19/5))
(define (euler-step law dz y)
(+ y (* dz (law y))))

One line.

That step is named after Leonhard Euler. Take one step with nothing chosen: an unchosen state, an unchosen stiffness, an unchosen dz.

> (euler-step (lens-law (lambda (z) 'kk))
'dz
(up 'z 'x 's))
(up (+ dz z) (+ (* dz s) x) (+ (* -1 dz kk x) s))

The place moves on by dz. The height grows by dz times the slope…

That is a drift of length dz! And the slope is lowered by dz·kk times the height: a kick of power dz·kk. An Euler step is made of a gap and a thin lens.

A slice, nearly. What is the difference from the slices of Chapter 7?

My slices did half a gap, then the kick, then half a gap. Here the drift and the kick are both worked out from the ray as it was at the start of the step.

We shall see what that costs. To go a long way, take many steps. How many is a natural number, so you know the template.

And the state is an accumulator again.

; flow : [Law Number State -> State]
; Law State Number N -> State
; the state at the place z1, starting from the
; state y, in n steps of the given stepper
(define (flow step law y z1 n)
(define dz (/ (- z1 (state-z y)) n))
; N State -> State
; accumulator y: the state with `left` steps to go
(define (go left y)
(cond ((= left 0) y)
(else (go (- left 1) (step law dz y)))))
(go n y))
; euler : Law State Number N -> State
(check-expect
(euler (lens-law always-4) (up 0 3 5) 1/10 1)
(up 1/10 7/2 19/5))
(define (euler law y z1 n)
(flow euler-step law y z1 n))

Send H through one unit of stiffness 1 in 10 Euler steps. This is a journey.

So I start from an inexact place: 0. instead of 0.

> (euler (lens-law always-1) (up 0. 0 1) 1 10)
(up 0.9999999999999999 0.8825... 0.5707...)
> (sin 1)
0.8414709848078965

The height should be (sin 1), .8415. It is .8825. Off by .041.

And with 20 steps, and 40?

; miss : State -> Number
; how far the height of a state is from (sin 1)
(define (miss y) (- (state-x y) (sin 1)))
> (miss (euler (lens-law always-1) (up 0. 0 1) 1 10))
0.041037...
> (miss (euler (lens-law always-1) (up 0. 0 1) 1 20))
0.020813...
> (miss (euler (lens-law always-1) (up 0. 0 1) 1 40))
0.010467...

.041, .021, .010. Each time I double the steps, the miss only halves. My slices did better: they quartered.

Euler trusts the rates at the start of the step for the whole step, like a driver who looks at the road once a minute. Here is a stepper that looks four times: at the start, twice in the middle, and at the end, and then takes a weighted average. It is named after Carl Runge and Wilhelm Kutta. Copy it carefully; its derivation is a long evening that we shall skip.

; rk4-step : Law Number State -> State
; the state a step dz further on, from four looks
; at the rates: start, middle, middle, end
(define (rk4-step law dz y)
(let* ((half (/ dz 2))
(r1 (law y))
(r2 (law (+ y (* half r1))))
(r3 (law (+ y (* half r2))))
(r4 (law (+ y (* dz r3)))))
(+ y (* (/ dz 6)
(+ r1 (* 2 r2) (* 2 r3) r4)))))
; runge-kutta : Law State Number N -> State
(define (runge-kutta law y z1 n)
(flow rk4-step law y z1 n))

let* lets each line use the ones above it. The first look is at the start. The second goes half a step along the first rates and looks there. The third goes half a step along the second rates and looks again. The fourth goes a whole step along the third. Then the average counts the two middle looks double: one, two, two, one, out of six.

The same experiment:

> (miss (runge-kutta (lens-law always-1) (up 0. 0 1) 1 10))
-5.07...e-7
> (miss (runge-kutta (lens-law always-1) (up 0. 0 1) 1 20))
-2.99...e-8
> (miss (runge-kutta (lens-law always-1) (up 0. 0 1) 1 40))
-1.8...e-9

Ten steps, and already right to six places.

By what factor does the miss shrink when you double the steps?

5.07e-7 over 2.99e-8 is about 17. Then 2.99e-8 over 1.8e-9 is about 16. Sixteen: two to the fourth power. Euler halves, slices quarter, this one sixteenths.

Halving is two to the power 1. Quartering is two to the power 2. Sixteen is two to the power 4. Those powers, 1, 2 and 4, are called the order of a method. They are the cheapest test you will ever have. If you halve the step of a fourth-order method and the answer does not improve sixteen-fold, something is wrong with your program, your law, or your arithmetic.

The Fifth Commandment.

Know your order. Before you halve the step, say what the error must do. Then look.

Pin your new stepper down with two tests: one for each ray, in two different lenses.

(check-within
(runge-kutta (lens-law always-1) (up 0. 0 1) 1 40)
(up 1 (sin 1) (cos 1))
1e-8)
(check-within
(runge-kutta (lens-law always-4) (up 0. 1 0) .7 40)
(up .7 (cos 1.4) (* -2 (sin 1.4)))
1e-7)

Now an invariant. In a lens of stiffness 1, take the square of the height plus the square of the slope. Before you compute anything: what must it be for the axial ray, at every place?

The height is sin and the slope is cos. Sine squared plus cosine squared: it is 1, everywhere. The Law of the Determinant again, in other clothes.

Then test your steppers against it. A hundred steps over ten units.

; swing : State -> Number
; height squared plus slope squared
(check-expect (swing (up 0 3 4)) 25)
(define (swing y)
(+ (square (state-x y)) (square (state-s y))))
> (swing (runge-kutta (lens-law always-1)
(up 0. 0 1) 10 100))
0.9999986...
> (swing (euler (lens-law always-1) (up 0. 0 1) 10 100))
2.7048...

Euler has nearly tripled it! The ray is swinging wider and wider. No lens does that.

Each Euler step multiplies swing by a little more than one, and a hundred little mores are not little. A stepper is not only more or less accurate. It keeps some truths and breaks others. Which truth did your slices keep?

The determinant, exactly. So the slices are not obsolete?

They are not. For following a ray through a lens they are honest in a way that even Runge and Kutta are not. But a slice only understands lenses. A stepper will follow any law you can write as a function, and soon we shall want to carry other passengers along with the ray: how far the image has turned, how much blur has piled up.

(check-within
(swing (runge-kutta (lens-law always-1)
(up 0. 0 1) 10 100))
1
1e-5)

Your steppers are for understanding. For long journeys sicm has a professional one, and it asks a different question. You tell your stepper how many steps to take and hope the error is small. What would you rather tell it?

How small I want the error. Let it worry about the steps.

It is called state-advancer. It wants the law in a particular form: as a function of knobs, plain numbers, that produces the Law. For a uniform lens the knob is the stiffness.

; uniform-law : Number -> Law
; the law of a lens whose stiffness is kk all along
(check-expect ((uniform-law 4) (up 0 3 5))
(up 1 5 -12))
(define (uniform-law kk)
(lens-law (lambda (z) kk)))

Then you hand state-advancer the law-maker and the settings of its knobs. What comes back is a function of three things: the state to start from, how far to go, and the error you will tolerate.

> ((state-advancer uniform-law 1) (up 0 0 1) 1 1e-13)
(up 1.0 0.841470984807897 0.5403023058681403)
> (sin 1)
0.8414709848078965
> (cos 1)
0.5403023058681398

Fifteen digits of each. And I did not have to make the start inexact: it did that itself.

It chooses its own steps, checks its own error, and tries again when it is not satisfied. We shall use it for every long journey from here on.

(check-within
((state-advancer uniform-law 1) (up 0 0 1) 1 1e-13)
(up 1 (sin 1) (cos 1))
1e-12)
(check-within
(swing
((state-advancer uniform-law 1) (up 0 0 1) 10 1e-13))
1
1e-11)

One more look at what you handled in this chapter. How many of those things were numbers?

Hardly any. A law is a function. lens-law makes it out of a stiffness, which is a function. The steppers eat laws. state-advancer eats a function that makes laws and gives back a function.

In HtDP that was a chapter near the end. Here it is the whole subject.

Exercises

10.1 Design midpoint-step, a stepper that looks twice: it takes half an Euler step to the middle, asks the law for the rates there, and uses those for the whole step. Before you run it, say what its order should be if it sits between Euler and Runge–Kutta. Then measure, with flow and miss.

10.2 Take one rk4-step with nothing chosen, as you did for Euler, but in a gap: use the law (lens-law (lambda (z) 0)). What comes out? How accurate are all the steppers in a gap, and why?

10.3 The law of a cricket ball thrown straight up: the rate of its height is its speed, and the rate of its speed is −10, always. Write it as a Law, with the time in the slot where z was. Throw the ball up at speed 5 from height 0 and find its height and speed one unit of time later, with a single rk4-step. Then with a symbolic step 't. You have derived a formula from school.

10.4 In your mind. state-advancer is asked for an error of 1e-13 over a distance of 10 and then over a distance of 1000. In which case will it take more steps? In which case would you trust swing less?

11 The Bell🔗

A lens with no edges, traced by brute force, lands on a suspiciously tidy number.

It is time you knew what is inside an electron lens. A coil of wire, a few hundred turns, wrapped around the column. An iron jacket around the coil, with a narrow slot cut in it facing the axis. When current flows in the coil, a magnetic field leaks out of the slot into the hole down the middle, where the electrons fly.

And the field bends the electrons toward the axis, as a thin does?

Not directly, and that is the odd part. Here is the first law of nature I shall ask you to take on trust. A magnetic field pushes a moving electron sideways: across its motion and across the field, never along its motion.

If the push is never along the motion, the electron can be steered but never sped up or slowed down.

You have named an invariant before computing anything: the speed of an electron in a magnetic lens never changes. Keep it; Chapter 20 needs it. Now: on the axis the field points along the axis. An electron flying exactly along the axis…

…moves along the field, so there is no “across”, and no push. It goes straight. Like a ray through the middle of a thin.

An electron off the axis, where the field lines are spreading out of the slot, is pushed around the axis. It starts to circle. Once it is circling, it is moving across the main field, and that pushes it inward.

Two steps. The field makes it circle, and the circling in the field pulls it in. So the field gets used twice.

Which is why the stiffness is a square. Here is the second law I ask you to trust. The last chapter of this book says where to find its proof.

The Law of the Round Lens, second half.

Seen from a turntable that turns about the axis at the right rate, an electron in a round magnetic lens obeys the lens law with stiffness k times k, where k at each z is the field on the axis there, times the electron’s charge, over twice its momentum.

A stronger field makes k bigger and the lens stiffer. A faster electron has more momentum, so k is smaller, and it is harder to bend. That sounds right. But what is the turntable doing there?

The electron circles the axis while it is pulled in. If you watch from a turntable that keeps pace with the circling, all that is left to see is the motion toward and away from the axis. That is our x. Until Chapter 14 we shall ride the turntable and not look down.

So all I need, to trace a ray, is how the field on the axis varies with z.

In 1941 Walter Glaser proposed a formula for it. The field is strongest at the middle of the slot, and falls away on both sides like this: the peak field, divided by one plus the square of z/a. The length a is called the half-width.

At z = a that is the peak divided by two. So a is how far from the middle you must go for the field to fall to half.

We shall measure every length in half-widths, so that a is 1. Then k at z is some number divided by (+ 1 (square z)). Write the number as the square root of q, and call q the strength of the lens.

A function that consumes a strength and produces a function of z.

; bell : Number -> [Number -> Number]
; k along the axis of a Glaser lens of strength q,
; centred at 0, with z in half-widths
(check-expect ((bell 4) 0) 2)
(check-expect ((bell 4) 1) 1)
(check-expect ((bell 4) -3) 1/5)
(define (bell q)
(lambda (z) (/ (sqrt q) (+ 1 (square z)))))

You will write that shape, a define whose body is a lambda, a great many times. This dialect has a shorthand for it: put the two sets of arguments in the header, nested the way you would call the function. Write the stiffness that way.

I call it as ((bell-kk 3) 0), so the header is ((bell-kk q) z).

; bell-kk : Number -> [Number -> Number]
; the stiffness of the same lens: k times k
(check-expect ((bell-kk 3) 0) 3)
(check-expect ((bell-kk 3) 1) 3/4)
(check-expect ((bell-kk 3) -4) 3/289)
(define ((bell-kk q) z)
(/ q (square (+ 1 (square z)))))

It means exactly what the lambda form means. And I gave the stiffness its own function, so that it stays exact when q is 3. The square root of 3 is not a fraction.

The Fourth Commandment, anticipated. Why is it called a bell?

High in the middle, sloping away on both sides, never quite reaching zero.

Never reaching zero! ((bell-kk 3) -4) is 3/289. Small, but the lens is still there. Where does this lens end?

Nowhere. That is the first way in which it is more honest than a thin. Real fields have no edges. So where shall we put the object?

Anywhere, I suppose. The ray starts wherever I start it, and the law takes care of the rest. Far enough out that the lens is weak there.

Put it at −4, with strength 3, because a theorem lives there. You will want state-advancer. What is the knob?

The strength.

; glaser-law : Number -> Law
; the law of a Glaser lens of strength q
(check-expect ((glaser-law 3) (up 1 2 5))
(up 1 5 -3/2))
(define (glaser-law q)
(lens-law (bell-kk q)))
; glaser-ray : Number State Number -> State
; the state at the place z of the ray that starts
; as the state y, in a Glaser lens of strength q
(define (glaser-ray q y z)
(if (= z (state-z y))
y
((state-advancer glaser-law q)
y (- z (state-z y)) 1e-13)))

state-advancer wants to know how far to go, so I subtract where I am from where I want to be.

Let me see the axial ray, from −4, in the lens of strength 3.

; h-traced : Number -> Number
; the height at z of the axial ray from -4,
; in the Glaser lens of strength 3
(define (h-traced z)
(state-x (glaser-ray 3 (up -4 0 1) z)))
; g-traced : Number -> Number
; the same for the field ray
(define (g-traced z)
(state-x (glaser-ray 3 (up -4 1 0) z)))
> (map h-traced (list -4 -3 -2 -1 0 1))
(list
0
0.99705...
1.95237...
2.57247...
0.97014...
-2.57247...)

It leaves the axis at slope 1 and at first hardly notices the lens: after one unit it is at .997, where a straight line would be at 1. Then it bends over, and between 0 and 1 it plunges through the axis.

Above: the stiffness of the Glaser lens of strength 3. Below: the axial ray h and the field ray g from an object at −4. Where h returns to the axis, there is the image.

Above: the stiffness of the Glaser lens of strength 3. Below: the axial ray h and the field ray g from an object at −4. Where h returns to the axis, there is the image.

Where H crosses the axis, there is the image. Find the crossing.

I can try values.

> (h-traced .2)
0.1997736...
> (h-traced .3)
-0.1997840...

Positive at .2, negative at .3. This is HtDP’s root finder: halve the interval, and keep the half across which the sign changes.

(define TOL 1e-12)
; find-zero : [Number -> Number] Number Number
; -> Number
; a place between lo and hi where f crosses zero
; assume: (f lo) and (f hi) have opposite signs
; generative: look at the middle; the crossing is
; in the half whose ends still differ in sign
; termination: the interval halves at every step,
; so it is soon narrower than TOL
(check-within (find-zero sin 3 4) pi 1e-9)
(check-within
(find-zero (lambda (z) (- (square z) 2)) 1 2)
(sqrt 2)
1e-9)
(define (find-zero f lo hi)
; Number Number Number -> Number
; accumulator flo: the value of f at lo
(define (go lo flo hi)
(let ((mid (/ (+ lo hi) 2)))
(cond
((< (- hi lo) TOL) mid)
(else
(let ((fmid (f mid)))
(if (<= (* flo fmid) 0)
(go lo flo mid)
(go mid fmid hi)))))))
(go (exact->inexact lo) (f lo) (exact->inexact hi)))
> (find-zero h-traced 0 1)
0.2499999999995...

A quarter, to twelve places. And twelve places is all I asked of find-zero: that is TOL.

And the magnification is the height of G there.

> (g-traced 1/4)
-0.249999999999...
> (glaser-ray 3 (up -4 0 1) 1/4)
(up 0.25 ... -3.99999999999...)

The image is at .25. The magnification is −.25. The axial ray arrives with slope −4, and a height I shall call zero.

Check the Law of the Determinant.

g·dh − h·dg is (−1/4)·(−4) − 0·something. One. Good. But is the law even supposed to hold here? This is not a column of gaps and thin lenses.

Isn’t it?

I could slice it! slice-lens takes any stiffness function. Then it is a column, and the law holds exactly, however many slices I use. So it holds for the true lens, which the slices close in on.

(check-expect
(determinant
(stack->transfer (slice-lens (bell-kk 3) -4 1/4 8)))
1)

And that is why I had you keep the stiffness exact. Now look at your three numbers again. What do you notice about them?

They came out of a professional stepper grinding through a field with no edges. They ought to be ugly. But they are 1/4, −1/4 and −4, as far as I can see.

They are inexact numbers, but they smell like fractions.

When an inexact number smells like a fraction, a theorem is hiding nearby. Record what you found, to as many places as you trust, and tomorrow we go looking for it.

(check-within (find-zero h-traced 0 1) 1/4 1e-10)
(check-within (g-traced 1/4) -1/4 1e-10)
(check-within (glaser-ray 3 (up -4 0 1) 1/4)
(up 1/4 0 -4)
1e-10)

One question before you sleep. Strength 3: is that a lot? For electrons that have been accelerated through ten thousand volts, in a lens whose half-width is two millimetres, it means a peak field of about 0.59 tesla.

I do not know what a tesla feels like.

A fridge magnet is a hundredth of that at its surface. The magnet in a loudspeaker is about one. So this is a strong lens, as lenses go, but one that people build every day. You will compute that number yourself in Chapter 21.

Exercises

11.1 Weaken the lens to strength 3/2, with the object still at −4. Find the image and the magnification. You should get an image at .77786897543 and a magnification of −.30727264603; both numbers are certified by the proof corpus. Do these smell like fractions?

11.2 Trace H through the lens of strength 3 with slices instead: (slice-lens (bell-kk 3) -4. .25 n) for n = 100, 200 and 400. The ray should land at height 0. State the order of the method before you look (the Fifth Commandment), then measure it.

11.3 In your mind, then on the machine. If you raise the strength above 3, does the image move toward the lens or away from it? Use find-zero on a function of q to find the strength at which the image falls exactly at the centre of the lens, z = 0.

11.4 The level ray G enters from far away: start it at −40 instead of −4, in the lens of strength 3, and find where it first crosses the axis. Move the start to −400. Does the crossing move? What would you call that plane?

11.5 Look at what you traced. (#:samples 60 asks for sixty points on each curve; every point is a journey.)

> (require (only-in plot plot function x-axis))
> (plot
(list (function h-traced -4 1.5 #:samples 60)
(function g-traced -4 1.5 #:samples 60
#:style 'long-dash)
(x-axis))
#:y-min -3 #:y-max 3)

12 The Watcher🔗

Someone stands beside the lens and turns her head. That is all it takes.

Yesterday a great deal of arithmetic gave you 1/4, −1/4 and −4. Today we look for the reason. Come and stand beside the lens: one half-width away from the axis, level with the centre of the bell. You are looking straight at the centre. Now look at the point z = 1 on the axis instead. Through what angle did you turn your head?

I am 1 away from the axis, and the point is 1 along it. One across and one along: half of a right angle.

We shall measure angles the way the sine and cosine of this language do: a half turn is π. So a right angle is π/2, and half of one is π/4. Now the point at any z.

I am 1 from the axis and the point is z along it. The tangent of the angle is z over 1. So the angle is (atan z).

Call it the gaze.

; gaze : Number -> Number
; the angle through which a watcher, one
; half-width to the side of the lens centre,
; turns her head to look at z on the axis
(check-expect (gaze 0) 0)
(check-within (gaze 1) (/ pi 4) 1e-12)
(check-within (gaze -1) (/ pi -4) 1e-12)
(define (gaze z) (atan z))

The axis is infinitely long. How far must you turn your head to see all of it?

> (gaze 10)
1.4711276743037345
> (gaze 1000)
1.5697963271282298
> (/ pi 2)
1.5707963267948966

Looking further and further to the right, my gaze creeps toward a quarter turn but never gets there: I would be looking parallel to the axis. The same to the left. So the whole infinite axis fits into half a turn of my head.

What is the gaze of the object at −4? Of the image at 1/4?

> (gaze -4)
-1.3258176636680326
> (gaze 1/4)
0.24497866312686414
> (- (gaze 1/4) (gaze -4))
1.5707963267948968

That last number is π/2. From where I stand, the object and its image are exactly a quarter turn apart.

We shall want that difference often.

; swept : Number Number -> Number
; how far the gaze turns from zo to z
(check-within (swept -4 1/4) (/ pi 2) 1e-12)
(define (swept zo z) (- (gaze z) (gaze zo)))

Hold the quarter turn in your mind. Now the second half of the costume. Things far away look small. How far are you from the point z on the axis?

One across and z along: (sqrt (+ 1 (square z))).

So a ray at height h above the point z appears to you to have height h divided by that distance. Call it the apparent height.

; apparent : Number Number -> Number
; a height h above the point z on the axis,
; as it looks to the watcher
(check-expect (apparent 0 10) 10)
(check-expect (apparent 3/4 10) 8)
(define (apparent z h)
(/ h (sqrt (+ 1 (square z)))))

At z = 3/4 I am 5/4 away, so a height of 10 looks like 8.

Now watch the axial ray go by. For several z, tabulate two things: how far your gaze has swept since the object, and the apparent height of H there.

; watched : Number -> (list Number Number)
; for the axial ray from -4 in the lens of
; strength 3: the gaze swept and the apparent
; height when it passes z
(define (watched z)
(list (swept -4 z)
(apparent z (h-traced z))))
> (watched -3)
(list 0.0767718... 0.3152963...)
> (watched -2)
(list 0.2186689... 0.8731282...)
> (watched -1)
(list 0.5404195... 1.8190171...)
> (watched 0)
(list 1.3258176... 0.9701425...)

z

gaze swept

apparent height

−4

0

0

−3

.0768

.3153

−2

.2187

.8731

−1

.5404

1.8190

0

1.3258

.9701

1/4

1.5708

0

It starts at zero, rises, and comes back to zero when the gaze has swept π/2.

A function that starts at zero, rises, and returns to zero. You met one in Chapter 8.

The sine. But the sine returns to zero at π, and this returns at π/2.

And which lens in Chapter 8 had a ray that returned at π/2?

always-4. Stiffness 4, pace 2. Its axial ray was (/ (sin (* 2 z)) 2).

Can that be right? If the apparent height is some multiple of the sine of twice the gaze swept, then dividing one by the other should give the same number every time.

> (define (ratio z)
(/ (apparent z (h-traced z))
(sin (* 2 (swept -4 z)))))
> (map ratio (list -3 -2 -1 0))
(list
2.06155281...
2.06155281...
2.06155281...
2.06155281...)

The same number, four times, to nine figures.

Does 2.06155281 smell of anything?

Twice it is 4.1231. The square of that is… 17. It is half the square root of 17.

> (/ (sqrt 17) 2)
2.0615528128088303

And the square root of 17 is my distance from the object: one across, four along.

Say what you have found.

The Glaser lens of strength 3 has no edges and a stiffness that changes at every z. But if I describe each point by my gaze, and each height as it appears to me, then the axial ray is the axial ray of a uniform lens of stiffness 4, scaled by a constant. The plainest lens there is.

Glaser’s bell is always-4, in disguise.

The axial ray of the Glaser lens of strength 3, redrawn: the gaze swept across, the apparent height up. The points of the table lie on a pure sine wave that returns to zero after a quarter turn.

The axial ray of the Glaser lens of strength 3, redrawn: the gaze swept across, the apparent height up. The points of the table lie on a pure sine wave that returns to zero after a quarter turn.

Why 4?

The strength was 3. Is it the strength plus one?

Test your guess. In exercise 11.1 the strength was 3/2.

Then the disguised stiffness would be 5/2, the pace its square root, and the wave returns to zero when the gaze has swept π over that. Let me find the image by brute force and see how far the gaze sweeps to reach it.

> (define zi
(find-zero
(lambda (z)
(state-x (glaser-ray 3/2 (up -4 0 1) z)))
0 2))
> zi
0.7778689754...
> (swept -4 zi)
1.9869176531...
> (/ pi (sqrt 5/2))
1.9869176531...

The same! It is the strength plus one.

Glaser's Law.

Describe each point of the axis by the watcher’s gaze, and each height as it appears to her. Then every ray of the bell lens of strength q is a ray of the uniform lens of stiffness 1 + q.

And where does the 1 come from? What if the strength is 0?

Then there is no lens, and rays are straight lines. The law says a straight line, in disguise, is a wave of pace 1. Even empty space looks like a lens to the watcher?

Think of a straight line passing by you, parallel to the axis and a little above it. At first it is far to your left: how high does it appear?

Small, because it is far away. Then it comes near and looks large. Then it goes off to my right and looks small again. Its apparent height swells and shrinks once as my head turns through half a turn.

That is half a wave, in a gaze of π: pace 1. Exercise 13.2 will let you check it exactly. The magnetic field only quickens a swing that was already there.

So that is what a circle was doing inside a lens. The π was the watcher’s head turning.

You have found Glaser’s Law by looking. You have not proved it: four points on a curve, and one other strength. Tomorrow you turn it into functions, and then D will prove it for every strength there is.

Have something sweet. Tomorrow is the best day.

Exercises

12.1 Add z = −1/2 and z = 1/8 to the table, and check that ratio gives the same number there.

12.2 At what z does the apparent height of H peak? Find the gaze swept at the peak first, from what you know about the sine, and then turn it back into a z. Check with watched.

12.3 Do the same experiment for the field ray G: tabulate the gaze swept and the apparent height of g-traced. It starts at an apparent height of 1 over the square root of 17, not at zero. Which old friend is it, mostly? Is it only that one?

12.4 In your mind. For a lens of strength 8, what is the disguised stiffness, and the pace? Through what gaze does the watcher turn between the object and the first image? If the object is very far to the left, about where is that image?

13 Glaser in Disguise🔗

Three numbers with no steps at all, and a proof in three lines.

Yesterday you saw that the bell lens of strength q, watched by gaze and apparent height, is a uniform lens of stiffness 1 + q. What is the pace of that uniform lens?

The square root of its stiffness.

; pace : Number -> Number
; how fast the disguised ray of a Glaser lens of
; strength q swings: the k of its uniform lens
(check-expect (pace 3) 2)
(check-expect (pace 0) 1)
(define (pace q) (sqrt (+ 1 q)))

Now write the axial ray itself. Start from what the watcher sees. What is the axial ray of a uniform lens of pace w?

(/ (sin (* w z)) w): Chapter 8.

In the disguise, what plays the part of z?

The gaze swept since the object: (swept zo z).

That gives the apparent height. How do you get the real height back?

Apparent height was the real height divided by my distance to the point. So I multiply by (sqrt (+ 1 (square z))).

And yesterday’s table said there was one more factor.

The ratio came out as half the square root of 17. The half is the “over w” I already have, with w = 2. The square root of 17 was my distance to the object. So: multiply by my distance to the object as well.

; glaser-h : Number Number -> [Number -> Number]
; the axial ray of the Glaser lens of strength q
; from an object at zo
(check-within ((glaser-h 3 -4) -4) 0 1e-12)
(check-within ((glaser-h 3 -4) -1) (h-traced -1) 1e-10)
(check-within ((glaser-h 3 -4) 0) (h-traced 0) 1e-10)
(check-within ((glaser-h 3 -4) 2) (h-traced 2) 1e-10)
(define ((glaser-h q zo) z)
(* (sqrt (+ 1 (square zo)))
(sqrt (+ 1 (square z)))
(/ (sin (* (pace q) (swept zo z)))
(pace q))))

One line of arithmetic agrees with the professional stepper, to ten places.

At four places. And for one strength and one object. You know what to do about that.

Choose nothing. But what should I ask? I cannot compare with h-traced for an unchosen strength.

What makes a function the axial ray of a lens? Three facts, from Chapters 4 and 9.

It starts on the axis. It starts with slope 1. And it obeys the lens equation: the slope of its slope is minus the stiffness times its height.

All three are things I can ask D.

; glaser-h starts on the axis
(check-expect ((glaser-h 'q 'zo) 'zo) 0)
; glaser-h starts with slope 1
(check-expect ((D (glaser-h 'q 'zo)) 'zo) 1)
; glaser-h obeys the lens equation of the bell
(check-expect
(+ ((D (D (glaser-h 'q 'zo))) 'z)
(* ((bell-kk 'q) 'z) ((glaser-h 'q 'zo) 'z)))
0)

They pass.

They pass! With q unchosen, zo unchosen, z unchosen.

Say what that means.

For every strength, every place of the object, and every point along the axis, my one line is exactly the axial ray of Glaser’s lens. Not to ten places. Exactly. The machine took the slope of the slope of that tangle of sines and square roots and arctangents, added the stiffness times the tangle, and everything cancelled.

You have proved Glaser’s theorem. What was the hard part?

Guessing the line. Once I had the watcher, the proof was three check-expects.

It is nearly always so. Now use the theorem. In disguise, when does the axial ray return to the axis?

When the sine comes back to zero: the pace times the gaze swept is π. So the gaze of the image is the gaze of the object plus π over the pace.

And which point has a given gaze?

The gaze was the arctangent of z, so z is the tangent of the gaze.

Always?

No! If the sum reaches a quarter turn, I am looking parallel to the axis, and there is no such point. The lens is too weak to bring the ray back at all.

; A MaybeNumber is one of:
; - #f
; - Number
; glaser-image : Number Number -> MaybeNumber
; where the Glaser lens of strength q images an
; object at zo; #f if it is too weak to
(check-within (glaser-image 3 -4) 1/4 1e-12)
(check-within (glaser-image 3/2 -4) .77786897543 1e-10)
(check-expect (glaser-image 1/10 -4) #f)
(define (glaser-image q zo)
(let ((th (+ (gaze zo) (/ pi (pace q)))))
(if (< th (/ pi 2)) (tan th) #f)))

For strength 3 the pace is 2, so the gaze sweeps exactly a quarter turn between object and image. What does a quarter turn of the head do to the point you are looking at? Try a few.

> (tan (+ (gaze 2) (/ pi 2)))
-0.5000000000000002
> (tan (+ (gaze -4) (/ pi 2)))
0.24999999999999986
> (tan (+ (gaze -10) (/ pi 2)))
0.1000000000000000...

From 2 to −1/2. From −4 to 1/4. From −10 to 1/10. A quarter turn takes z to minus one over z.

So the object at −4 has its image at 1/4. Exactly. Not .2499999999995.

There is your fraction. And the magnification? Think about the field ray G, in disguise.

G in disguise is also a ray of the uniform lens. In Chapter 8 every ray of a uniform lens was a mixture of a sine and a cosine of the pace times the distance. At the image, the pace times the gaze swept is π.

What happens to a sine when you add π to what is inside it? To a cosine?

> (sin 1)
0.8414709848078965
> (sin (+ 1 pi))
-0.841470984807896...
> (cos 1)
0.5403023058681398
> (cos (+ 1 pi))
-0.540302305868139...

Both reverse their sign. Of course: π further along, a wave is doing the opposite of what it was doing. So any mixture of them reverses its sign.

At the image, the apparent height of every ray is exactly the reverse of what it was at the object.

And the real height?

G started at real height 1, which appeared as 1 over my distance to the object. At the image it appears as minus that. To get the real height back I multiply by my distance to the image.

; glaser-mag : Number Number -> Number
; the magnification of the Glaser lens of
; strength q for an object at zo
; assume: the lens is strong enough to image it
(check-within (glaser-mag 3 -4) -1/4 1e-12)
(check-within (glaser-mag 3/2 -4) -.30727264603 1e-10)
(define (glaser-mag q zo)
(- (/ (sqrt (+ 1 (square (glaser-image q zo))))
(sqrt (+ 1 (square zo))))))

Minus the ratio of my two distances. For us, the square root of 17/16 over the square root of 17: a quarter.

And the slope of the axial ray at the image?

I do not need to compute it. The Law of the Determinant: one over the magnification. Minus four.

Three numbers, no steps. Now make the first fraction undeniable. When the pace is 2, the sine of twice an angle can be written with nothing but the tangent of the angle, and the tangent of your gaze is z. Carry out that algebra for our lens and the sines and arctangents disappear. This is what is left.

; h-exact : Number -> Number
; the axial ray from -4 of the Glaser lens of
; strength 3, written without sine or gaze
(check-expect (h-exact -4) 0)
(check-expect (h-exact 1/4) 0)
(check-within (h-exact -1) ((glaser-h 3 -4) -1) 1e-12)
(check-within (h-exact 3) ((glaser-h 3 -4) 3) 1e-12)
(define (h-exact z)
(/ (* (+ z 4) (- 1 (* 4 z)))
(sqrt (* 17 (+ 1 (square z))))))

(check-expect (h-exact 1/4) 0). With check-expect, and no symbols: an exact zero, because the square root of 289/16 is exactly 17/4. The image is at one quarter and that is the end of the matter.

I did the algebra for you. Do you trust me?

I do not have to.

(check-expect ((D h-exact) -4) 1)
(check-expect
(+ ((D (D h-exact)) 'z)
(* ((bell-kk 3) 'z) (h-exact 'z)))
0)

It starts with slope exactly 1 and it obeys the lens equation at every z. It is the axial ray.

Your colleagues have this as a theorem, checked by a proof assistant, under the name glaserTrue_q3. You have now met it from three sides: by brute force, by turning your head, and by D.

The Sixth Commandment.

When a problem is hard, change how you describe it, until it is one you have already solved.

One more function, and this one is worth money. The operator of a microscope does not ask where the image falls. She has a specimen at a fixed place and turns a knob until the image falls on it. What does the knob change?

The current in the coil, so the field, so the strength q. She needs the inverse: given the object and where the image must be, which strength?

The gaze swept must be π over the pace. So the pace is π over the gaze swept, and the strength is the pace squared, minus one.

; strength-for : Number Number -> Number
; the strength at which a Glaser lens images an
; object at zo onto zi
(check-within (strength-for -4 1/4) 3 1e-12)
(check-within
(glaser-image (strength-for -40 1) -40) 1 1e-9)
(define (strength-for zo zi)
(- (square (/ pi (swept zo zi))) 1))

In exercise 11.3 you found a strength by find-zero, tracing a ray for every guess. What does it cost now?

Two arctangents and a division.

That is what a theorem is for. And this is the reason Glaser’s lens is the one every opticist learns first: a lens with no edges, like a real one, that can be solved by turning your head.

Exercises

13.1 Design glaser-g, the field ray. In disguise it is a mixture of a cosine and a sine of the pace times the gaze swept. The cosine has coefficient 1; the sine has coefficient minus zo over the pace. Undo the disguise as for glaser-h, but divide by the watcher’s distance to the object. Then prove with three symbolic check-expects that it starts at height 1, starts level, and obeys the lens equation.

13.2 Set the strength to 0. There is no lens, so the axial ray from zo is the straight line (- z zo). What does ((glaser-h 0 'zo) 'z) print? If the machine does not reduce it to a straight line, check it at five numeric places instead. Either way you have verified that a straight line is a sine wave, to a watcher who turns her head.

13.3 Design glaser-threshold, which consumes the place of an object and produces the strength below which a Glaser lens forms no image of it at all.

(check-within (glaser-threshold -4) .17630108 1e-8)

13.4 In your mind, then on the machine. A strong lens can swing the ray through the axis more than once before it leaves. Each crossing is an image. For an object at −4, at what strength does a second image first appear? Design crossings, which consumes a strength and an object place and counts the images.

(check-expect (crossings 3 -4) 1)
(check-expect (crossings 4 -4) 2)
(check-expect (crossings 1/10 -4) 0)

14 The Turn🔗

We look down from the turntable, and learn to add up a function.

Since Chapter 11 you have been riding a turntable. It is time to ask how far it has turned. Here is the rest of the law I asked you to trust.

The Law of the Round Lens, third half.

The turntable turns about the axis at the rate k: over a short stretch dz of the axis, it turns through the angle k times dz.

The rate is k, not the stiffness kk?

The focusing uses the field twice. The turning uses it once. Suppose for a moment that k were the same all along, say 2, and the flight were 3 units long. How far would the table turn?

Two per unit, for three units: 6.

In the bell lens k is different at every place. Now what?

Cut the flight into slices, as in Chapter 7. In each slice k is nearly steady, so the table turns by k at the middle of the slice, times the length of the slice. Add up all the slices.

Design it for any rate function, not only k.

; integrate :
; [Number -> Number] Number Number N -> Number
; what piles up between a and b at the rate f:
; the sum, over n slices, of f at the middle of
; the slice times the length of the slice
(check-expect (integrate (lambda (z) 2) 0 3 10) 6)
(check-expect (integrate (lambda (z) z) 0 4 10) 8)
(define (integrate f a b n)
(define dz (/ (- b a) n))
; N -> Number
; what piles up in slice number i
(define (piece i)
(* dz (f (+ a (* (+ i 1/2) dz)))))
(foldl + 0 (build-list n piece)))

Explain your second example.

The rate grows steadily from 0 to 4. On a graph that is a triangle, 4 wide and 4 high, and what piles up is its area: 8. Each slice is a thin strip of the graph, and its piece is the area of the strip.

So integrate measures the area under the graph of f.

Adding up a function, slice by slice, is the second idea of the calculus. Is your sum exact?

For a steady rate and a steadily growing rate it was. Let me try a rate that bends.

> (integrate square 0 3 10)
3591/400
> (integrate square 0 3 100)
359991/40000
> (integrate square 0 3. 1000)
8.9999977...

8.9775, then 8.999775, then 8.9999977. Closing in on 9. The misses are .0225, .000225 and .0000023: ten times the slices, a hundredth of the miss.

So doubling the slices would…

Quarter it. Order 2, like slice-lens, and for the same reason I suppose: both use the middle of the slice.

As with steppers, sicm has a professional that takes the error you want instead of a number of slices.

> (definite-integral square 0 3 1e-12)
9.0
> (definite-integral cos 0 1 1e-12)
0.841470984807896...
> (sin 1)
0.8414709848078965

Nine. And what piles up from 0 to 1 at the rate cos is (sin 1).

Why should it be the sine?

D of the sine is the cosine: the sine grows at the rate cosine. So if I pile up at the rate cosine, starting from nothing at 0, I get the sine.

D asks how fast something is growing. integrate adds up the growing. One undoes the other!

People call that the fundamental theorem of the calculus. To you it is a pair of tests.

(check-within (definite-integral cos 0 1 1e-12)
(sin 1) 1e-11)
(check-within (definite-integral (D square) 0 3 1e-12)
(square 3) 1e-11)

Now turn the table.

; turn-traced : Number -> Number
; how far the turntable of the Glaser lens of
; strength 3 has turned between -4 and z
(define (turn-traced z)
(definite-integral (bell 3) -4 z 1e-13))
> (turn-traced 1/4)
2.72069904635132...

Is that a lot?

The units are those of your gaze: a half turn is π.

2.72 out of 3.14: most of a half turn. In degrees, 2.72 times 180 over π: about 156.

Does 2.7206990463 smell of anything?

Not a fraction. But the last two chapters taught me to think about the watcher. k is the square root of q over (+ 1 (square z)). Is there a function whose slope is one over (+ 1 (square z))? If there were, piling up k would give the square root of q times that function.

Ask D about the gaze.

> ((D gaze) 'z)
(/ 1 (+ 1 (expt z 2)))

There it is. The slope of the gaze is the bell!

(check-expect ((D gaze) 'z)
(/ 1 (+ 1 (square 'z))))
(check-expect (* (sqrt 'q) ((D gaze) 'z))
((bell 'q) 'z))

So the rate at which the table turns is the square root of q times the rate at which the watcher turns her head. They turn in step. And then what piles up is the square root of q, times the gaze swept.

; glaser-turn : Number Number -> Number
; the angle the turntable turns between an object
; at zo and its image, in a Glaser lens of
; strength q
; assume: the lens is strong enough to image it
(check-within (glaser-turn 3 -4)
(* (sqrt 3) (/ pi 2))
1e-12)
(check-within (glaser-turn 3 -4) (turn-traced 1/4)
1e-10)
(define (glaser-turn q zo)
(* (sqrt q) (swept zo (glaser-image q zo))))

For our lens the gaze sweeps a quarter turn, so the table turns by the square root of 3 times π/2. Another number with no steps.

Now step off the table. An operator looks at the image on her screen. What does she see?

The magnification is −1/4, so on the turntable the picture is a quarter the size and upside down. And the turntable itself has turned 156 degrees. So she sees a small picture, turned by some odd angle that depends on the lens.

She turns the focus knob. What happens to the picture?

The knob changes q. The image plane moves, which is what she wanted. But glaser-turn depends on q too. The picture rotates as she focuses!

Every operator of an electron microscope has watched that happen. Now a design question. The turn is a nuisance. Can you build a round magnetic lens that focuses but does not turn?

Focusing needs k not to be zero, at least somewhere. And wherever k is not zero, the table is turning. Unless… can the turn have either sign?

Run the current through the coil the other way.

Then the field points the other way and k changes sign. The turning reverses. But the stiffness is k times k, which does not care about the sign. So the focusing is exactly as before.

Two lenses, one after the other, with opposite currents: both focus, and the second undoes the turn of the first.

That is how it is done. Which of our functions would have told you so, had you looked?

bell-kk has no square root in it and bell does. The sign has nowhere to live in bell-kk.

Last: why must a round lens turn the picture? I shall give you the shape of the answer, and SICM will give you the rest. The lens is round: turn the whole apparatus about its axis and nothing changes.

An invariant of the machine, not of the ray.

There is a theorem, due to Emmy Noether, that whenever a law is unchanged by some motion, such as turning about an axis, some quantity is conserved along every path. For a round magnetic lens that quantity is a kind of angular momentum. An electron that sets out from the axis starts with none of it, and can go on having none only by circling at exactly the rate k. The turn is not an accident of Glaser’s bell. It is the price of roundness.

So symmetries give invariants, and invariants give design rules. The Third Commandment keeps coming back.

It is most of physics.

Exercises

14.1 Compute the turn of the lens of strength 3/2 for an object at −4, both by definite-integral and by glaser-turn. The proof corpus certifies 2.43346720558.

14.2 Measure the order of integrate properly: for (integrate cos 0 1. n) with n = 10, 20, 40, print the miss from (sin 1). (The Fifth Commandment: say first, then look.)

14.3 Build a pair of bell lenses centred at −3 and +3, each of strength 1: the first as (lambda (z) ((bell 1) (+ z 3))), the second likewise with (- z 3). Make two versions of the pair, one adding the two ks and one subtracting them. For each, integrate k from −30 to 30. Explain both answers. Then explain why the two pairs do not focus exactly alike, though they nearly do: where along the axis do they differ?

14.4 In your mind. As the strength q grows without limit, the gaze swept between object and image shrinks. What does glaser-turn approach? Can the first image of a Glaser lens ever be turned by more than half a turn?

15 Area Is Forever🔗

A beam is a list of rays. Lenses can reshape it and cannot shrink it.

One electron is not a microscope. A source sends out millions, from slightly different places, in slightly different directions. What is a beam?

; A Beam is one of:
; - '()
; - (cons Ray Beam)
; interpretation the rays of many electrons,
; all at the same plane.
; trace-beam : ModuleStack Beam -> Beam
; every ray of b, carried through ms
(check-expect
(trace-beam TOY (list (make-ray 0 1) (make-ray 1 0)))
(list (make-ray 0 -1/2) (make-ray -2 -1/2)))
(define (trace-beam ms b)
(map (lambda (r) (trace-ray ms r)) b))

Now a way of seeing a beam. Take a sheet of paper. For each ray make a dot: its height x across, its slope s up. Call the sheet the chart. Where on the chart is the ray (make-ray 1 0)?

One to the right, on the middle line. And (make-ray 0 1) is one up from the centre. A ray on the axis flying level is the centre itself.

A source reaches one unit either side of the axis, and sends electrons at slopes up to one either way. What does its beam look like on the chart?

Every height from −1 to 1, and for each, every slope from −1 to 1. A filled square. I cannot list every ray, but I can list its corners.

(define SQUARE
(list (make-ray -1 -1) (make-ray 1 -1)
(make-ray 1 1) (make-ray -1 1)))

Send the corners through a gap of 3. Before you run it: which way does the top edge of the square move?

The top edge is the rays with slope 1. They climb, so after 3 units their heights have grown by 3. The top edge slides right. The bottom edge is the rays that sink: it slides left.

> (trace-beam (list (make-gap 3)) SQUARE)
(list (up -4 -1) (up -2 -1) (up 4 1) (up 2 1))

The square has become a leaning parallelogram.

And are the rays that were inside the square still inside the parallelogram?

By the Law of Two Rays, a ray halfway between two corners stays halfway between them. So edges go to edges and the inside stays inside. I only ever need the corners.

How much of the chart does the beam cover now? There is an old recipe for the area of a figure with straight sides, from its corners taken in order. It uses this, for one corner and the next:

; cross : Ray Ray -> Number
; x of the first times s of the second, minus
; x of the second times s of the first
(check-expect (cross (make-ray 1 0) (make-ray 0 1)) 1)
(check-expect (cross (make-ray 2 3) (make-ray 4 6)) 0)
(define (cross a b)
(- (* (ray-x a) (ray-s b))
(* (ray-x b) (ray-s a))))

Compute cross for each corner and the one after it, the last corner being followed by the first. Add them all up, and halve.

A list of corners, so the list template. In the last clause I need the first corner again, so I keep the whole beam within reach.

; area : Beam -> Number
; the area of the chart region whose corners,
; in anticlockwise order, are the rays of b
; assume: b has at least one ray
(check-expect (area SQUARE) 4)
(check-expect
(area (list (make-ray 0 0) (make-ray 4 0)
(make-ray 0 3)))
6)
(define (area b)
; Beam -> Number
; the crosses of each corner with the next,
; and of the last with the first of b
(define (go l)
(cond
((null? (cdr l))
(cross (car l) (car b)))
(else (+ (cross (car l) (cadr l))
(go (cdr l))))))
(/ (go b) 2))

The square is 2 by 2: area 4. The triangle is half of 4 by 3: area 6. The recipe works.

Before you run anything more. The square had area 4. After the gap it is a parallelogram four times as wide at its widest. What is its area?

It is wider but it leans, so I cannot tell by eye. The Third Commandment: name the invariant. Is it the area?

Look at cross again. You have computed that quantity before, under another name.

x of one times s of the other, minus the other way round. If the two rays are what became of G and H, that is g·dh − h·dg.

cross is the determinant!

And what are G and H, on the chart?

One step to the right and one step up: two sides of a little square of area 1. So the Law of the Determinant says: that unit square is carried to a parallelogram whose cross is exactly 1. Area 1.

Every little square is. So any region keeps its area.

(check-expect
(area (trace-beam (list (make-gap 3)) SQUARE)) 4)
(check-expect (area (trace-beam TOY SQUARE)) 4)
(check-expect (area (trace-beam TWO SQUARE)) 4)
(check-expect
(area (trace-beam (slice-lens (bell-kk 3) -4 1/4 8)
SQUARE))
4)

Four, four, four, four. Exactly. Through gaps, lenses, and eight slices of Glaser’s bell.

And for parts you have not chosen?

(check-expect
(area (trace-beam ANY-COLUMN SQUARE))
4)

For every gap, lens, gap.

The Law of Area.

No column of gaps and lenses changes the area a beam covers on the chart. It can only change the shape.

Opticists call that area the emittance of the beam, and the law is Liouville’s theorem. Look at the shape at the image plane of TWO, where the magnification is 1/6.

> (trace-beam TWO SQUARE)
(list (up -1/6 -8) (up 1/6 -4) (up 1/6 8) (up -1/6 4))

All the heights are within 1/6 of the axis: six times narrower. But the slopes now reach 8. A tall thin sliver, with the same area as the square.

One beam on the chart at three planes, all drawn to one scale: height across, slope up. The gap shears it, the column squeezes it into a sliver, and its area is 4 throughout.

One beam on the chart at three planes, all drawn to one scale: height across, slope up. The gap shears it, the column squeezes it into a sliver, and its area is 4 throughout.

So a column designer who wants a spot six times smaller…

…gets slopes at least six times steeper, because the area will not shrink. Chapter 6 said it for one ray. This says it for the whole beam.

A microscope needs a small spot and gentle slopes, because steep rays are the ones lenses treat worst, as you will see in Chapter 19. No lens can shrink the area. What can?

Nothing that is made of gaps and lenses. I would have to throw some of the electrons away.

That is tomorrow, and it has a price.

Exercises

15.1 Design width and spread, the largest distance from the axis and the largest steepness among the rays of a beam. For SQUARE, the product of the two is 1 at the source. Compute it at the image plane of TWO. It is not 1. The area is still 4. Sketch the chart at both planes and explain how both can be true.

15.2 Take the corners of SQUARE in clockwise order. What does area produce? What has that to do with the sign of a magnification?

15.3 A thin lens of power p acts on SQUARE. Before running anything, say which way each edge moves on the chart. Then check with (trace-beam (list (make-thin 'p)) SQUARE).

15.4 In your mind. A beam covers a region of the chart 1/1000 wide and 1/100 tall, where it leaves the source. A column brings it to a spot 1/100000 wide. How tall, at least, is its region of the chart there?

16 The Price of a Small Spot🔗

A plate with a hole in it. The only module that makes a beam smaller, and what it charges.

Yesterday you said: to make the beam cover less of the chart, throw electrons away. With what?

Something solid in the way, with a hole for the electrons I want to keep.

A plate of metal with a round hole. An aperture. It is a new kind of Module. What does it need to remember?

The radius of the hole. A third kind of structure.

; A Module.v2 is one of:
; - (make-gap Number)
; - (make-thin Number)
; - (make-stop Number)
; interpretation as before; (make-stop r) is a
; metal plate with a round hole of radius r.
(define-struct stop (r))

In HtDP, what did you do after adding a clause to a data definition?

I went to every function that consumes that kind of data and added a clause. Here that is through. A ray meets a plate with a hole of radius r: if it is within r of the axis it goes on unchanged.

And if it is not? There is no ray any more. What does through produce?

Say so in the data.

; A MaybeRay is one of:
; - #f
; - Ray
; interpretation #f is an electron that has
; hit metal.

Then a ray that has hit metal must stay that way through every later module. So the new through has to consume a MaybeRay as well.

; through.v2 : Module.v2 MaybeRay -> MaybeRay
; the ray after one module, if it survives
(check-expect
(through.v2 (make-stop 1) (make-ray 1/2 3))
(make-ray 1/2 3))
(check-expect
(through.v2 (make-stop 1) (make-ray -2 0))
#f)
(check-expect (through.v2 (make-gap 5) #f) #f)
(check-expect
(through.v2 (make-gap 5) (make-ray 0 1))
(make-ray 5 1))
(define (through.v2 m r)
(cond
((not r) #f)
((stop? m)
(if (<= (abs (ray-x r)) (stop-r m)) r #f))
(else (through m r))))

Three questions, in order. Is the electron already lost? Is this a plate? Otherwise it is one of the old modules, and the old function knows what to do.

And tracing?

The fold has the same shape as before. Only the function inside it has changed.

; trace-ray.v2 :
; [List-of Module.v2] MaybeRay -> MaybeRay
(check-expect (trace-ray.v2 TOY (make-ray 0 1))
(trace-ray TOY (make-ray 0 1)))
(define (trace-ray.v2 ms r)
(foldl through.v2 r ms))

For a whole beam, what do you want to know?

Which rays come out of the far end. Trace each one, and keep those that are not #f.

; transmit : [List-of Module.v2] Beam -> Beam
; the rays of b that come out of the far end
(define (transmit ms b)
(filter (lambda (r) r)
(map (lambda (r) (trace-ray.v2 ms r)) b)))

Try it. A point source on the axis sends out a fan of rays.

Evenly spread slopes, from −a to a. With n gaps between them there are n + 1 rays.

; fan : N Number -> Beam
; n + 1 rays from a point on the axis, their
; slopes evenly spread from -a to a
(check-expect (fan 2 1/10)
(list (make-ray 0 -1/10) (make-ray 0 0)
(make-ray 0 1/10)))
(define (fan n a)
(build-list
(+ n 1)
(lambda (i)
(make-ray 0 (* a (- (* 2 (/ i n)) 1))))))

Put a plate with a hole of radius 1 in the toy, just in front of the lens. Send a fan of nine rays at it, with slopes up to 4/10. Before you run it: how many get through?

The slopes are −4/10, −3/10, and so on up to 4/10. The plate is 3 units from the source, so a ray of slope s meets it at height 3·s. The steepest two arrive at 12/10 and −12/10: outside the hole. The next arrive at 9/10: inside. So seven.

(define STOPPED
(list (make-gap 3) (make-stop 1)
(make-thin 1/2) (make-gap 6)))
(check-expect (length (fan 8 4/10)) 9)
(check-expect (length (transmit STOPPED (fan 8 4/10)))
7)
> (transmit STOPPED (fan 8 4/10))
(list
(up 0 3/20)
(up 0 1/10)
(up 0 1/20)
(up 0 0)
(up 0 -1/20)
(up 0 -1/10)
(up 0 -3/20))

Seven arrive, all on the axis: the image is still an image. And the steepest slope arriving is 3/20, where without the plate it would have been 4/20.

Which slopes get through, at the source?

Those up to 1/3: the ray of slope s is at height 3·s at the plate, and the hole has radius 1.

You traced that ray in your head. Which ray was it?

A multiple of H! The height of H at the plate is 3. So a hole of radius 1 admits slopes up to one third. H is a ruler for apertures.

; acceptance : ModuleStack Number -> Number
; the steepest slope, from a point on the axis,
; that passes a hole of radius r placed after ms
(check-expect (acceptance (list (make-gap 3)) 1) 1/3)
(check-expect
(acceptance (list (make-gap 3) (make-thin 1/2)
(make-gap 3))
1/2)
1/3)
(define (acceptance ms r)
(/ r (abs (ray-x (trace-ray ms H)))))

My second example puts a smaller hole halfway to the image, where H has come down to height 3/2. It admits the same rays.

So an aperture chooses the angle of the beam. On the chart, what has it done to the region the beam covers?

It has cut off the top and the bottom: every dot with a slope too steep. The region is smaller.

It is the first module that changes the area.

And what does it charge?

Electrons. Seven out of nine here.

It is worse than that. Our chart shows one sideways direction, but a real beam spreads in two: it is a cone. Halve the radius of the hole, and the area of the hole falls to…

A quarter. So the current goes as the square of the angle. Halve the angle, keep a quarter of the electrons.

That is the bargain at the heart of every microscope: a gentler beam makes a sharper spot and a dimmer picture. No arrangement of lenses gets you out of it, because of the Law of Area. The only way to have more electrons in the same area of chart is to start with a better source: one that packs more current into each unit of area. That property of a source is called its brightness.

So lenses cannot improve brightness. They can only spend it.

Your colleagues’ data definitions say the same thing from the other side. Their Beam is a list of Beamlets, and a Beamlet remembers its place, its slope, its energy, and how much current it carries. What have we left out?

The current and the energy. Our rays all count the same, so I can only count them. If each ray carried its share of current I could add up what gets through instead. That is their Transmission_Current.

Exercise 16.4. The energy comes in Chapter 20.

Stop here for the evening. The second half of the book begins tomorrow, and it begins with a confession.

Exercises

16.1 Move the stop in STOPPED to just after the lens instead of just before it. Does transmit let through the same rays of (fan 8 4/10)? Then move it to the middle of the last gap, keeping its radius 1. Explain what you see using H.

16.2 Give stack-length a third clause, so that it accepts columns with stops. What did you have to change? What does that tell you about how the function was written?

16.3 A column forms an image with magnification m. A stop somewhere in it gives an acceptance of a at the source. With what steepest slope do rays arrive at the image? Design arrival-angle.

16.4 Design a Beamlet as a list beginning with 'beamlet that holds a ray and a current, with a constructor and two selectors. Design transmitted-current, which consumes a column and a list of beamlets and produces the total current that gets through. Give each of the nine rays of (fan 8 4/10) a current of 1/9 and check that 7/9 arrives.

17 One Function to Rule the Ray🔗

In which we stop writing laws by hand.

A confession. Everything since Chapter 1 has rested on one assumption: a lens lowers the slope in proportion to the height. Is a real magnetic lens exactly like that?

I cannot know. You gave me the Law of the Round Lens on trust.

I gave you the beginning of it. The true law of an electron in a round magnetic lens has a square root in it, and the field away from the axis, and if I wrote out its rates for you, you would copy them wrongly, as I would. Mechanics has a better way. It was found in the 1830s by William Rowan Hamilton, who was studying, as it happens, rays of light.

A better way to write a law?

A way not to write it at all. You write one function, which produces one number. The law is derived from it.

First, a small change to the state. Until now it was (up z x s). From here on the third number is p: the electron’s sideways momentum, as a fraction of its whole momentum. For a ray that slopes gently, p and s are very nearly the same number.

; state-p : State -> Number
; the third number of a state, read as momentum
(define (state-p y) (ref y 2))

The one function consumes a state and produces a number. It is called a Hamiltonian. Here is the first one I want you to meet: half of the sum of p squared and the stiffness times x squared.

; A Hamiltonian is a function: State -> Number
; interpretation one number for each place z,
; height x and sideways momentum p, from which
; a law of motion is derived.
; lens-H : [Number -> Number] -> Hamiltonian
; half of: p squared, plus stiffness times x squared
(check-expect ((lens-H always-4) (up 0 3 5)) 61/2)
(define ((lens-H kk) y)
(* 1/2 (+ (square (state-p y))
(* (kk (state-z y))
(square (state-x y))))))

At height 3 with momentum 5 in a lens of stiffness 4: half of 25 plus 36. But what does 61/2 mean?

By itself, little. What matters is how it changes when the state changes. Hold z and x still, at 0 and 3, and vary only p. That is a function of one number. What is its slope at p = 5?

“Hold two still and vary one” is a lambda of one argument. And “the slope of” is D.

> ((D (lambda (p) ((lens-H always-4) (up 0 3 p)))) 5)
5

Five.

Now hold z and p still and vary x.

> ((D (lambda (x) ((lens-H always-4) (up 0 x 5)))) 3)
12

Twelve.

Recall ((lens-law always-4) (up 0 3 5)).

(up 1 5 -12). The rate of the height was 5 and the rate of the slope was −12.

Five and twelve! The slope of the Hamiltonian along p is the rate of x. And the slope along x is the rate of p, with the sign turned over.

That is Hamilton’s recipe. “The slope of a function of a tuple when only one slot varies” is wanted so often that sicm has a word for it: partial. ((partial 2) H) is the slope function of H along slot 2.

> (((partial 2) (lens-H always-4)) (up 0 3 5))
5
> (((partial 1) (lens-H always-4)) (up 0 3 5))
12

The same two numbers, without my lambdas. Three sets of parentheses: (partial 2) is a function that eats a Hamiltonian and gives a function that eats a state.

Then write the recipe as a function.

It consumes a Hamiltonian and produces a Law. The rate of z is 1. The rate of x is the slope along slot 2. The rate of p is minus the slope along slot 1.

; hamiltonian->law : Hamiltonian -> Law
; the law in which the rate of x is the slope of H
; along p, and the rate of p is minus the slope
; of H along x
(check-expect
((hamiltonian->law (lens-H always-4)) (up 0 3 5))
((lens-law always-4) (up 0 3 5)))
(define ((hamiltonian->law H) y)
(up 1
(((partial 2) H) y)
(- (((partial 1) H) y))))

One state, one lens. You know what to do. For the state, choose nothing. For the stiffness you need something new: not an unchosen number but an unchosen function.

There is such a thing?

> ((literal-function 'kk) 'z)
(kk z)

A function that, asked for its value at z, answers “my value at z”. The function I have not chosen yet.

> ((hamiltonian->law (lens-H (literal-function 'kk)))
(up 'z 'x 'p))
(up 1 p (* -1 x (kk z)))

The rate of x is p. The rate of p is minus x times the stiffness at z.

That is the lens law. All of it. For every lens and every state. The machine derived it, from a function that does nothing but square two numbers and add.

(check-expect
((hamiltonian->law (lens-H (literal-function 'kk)))
(up 'z 'x 'p))
((lens-law (literal-function 'kk))
(up 'z 'x 'p)))

I can see how. Along p, the Hamiltonian is half of p squared plus something standing still, and the slope of half a square is the thing itself. Along x, it is half the stiffness times a square, whose slope is the stiffness times x.

So the whole of Chapter 10’s law was folded up inside one function.

The recipe is standard equipment, of course. In sicm it is called Hamiltonian->state-derivative.

(check-expect
((Hamiltonian->state-derivative
(lens-H (literal-function 'kk)))
(up 'z 'x 'p))
((hamiltonian->law (lens-H (literal-function 'kk)))
(up 'z 'x 'p)))

Why does Hamilton’s recipe work? Why that function, and why slopes?

That is the deepest thing in mechanics, and it is the third law I ask you to take on trust. It occupies the first three chapters of SICM. But I can show you one reason to believe the recipe is not arbitrary. Suppose the Hamiltonian does not mention z at all: a uniform lens. Follow a ray. What happens to the value of the Hamiltonian along it?

Let me think with rates. As the ray moves, x changes and p changes, and each change moves the Hamiltonian. The change through x is the slope along x, times the rate of x. The change through p is the slope along p, times the rate of p.

Now use the recipe on those two rates.

The rate of x is the slope along p. The rate of p is minus the slope along x. So the first change is “slope along x times slope along p”, and the second is “slope along p times minus slope along x”.

The same product, with opposite signs. They cancel!

Check your argument, with a uniform lens of unchosen stiffness.

(define UNIFORM-H (lens-H (lambda (z) 'kk)))
(define UNIFORM-LAW (hamiltonian->law UNIFORM-H))
(define ANY-STATE (up 'z 'x 'p))
; the rate at which the value of the Hamiltonian
; changes along a ray is zero
(check-expect
(+ (* (((partial 1) UNIFORM-H) ANY-STATE)
(state-x (UNIFORM-LAW ANY-STATE)))
(* (((partial 2) UNIFORM-H) ANY-STATE)
(state-p (UNIFORM-LAW ANY-STATE))))
0)

Zero. The value of the Hamiltonian never changes along a ray.

An invariant, and nobody had to guess it.

What is it, for the lens of stiffness 1 and the axial ray?

Half of p squared plus x squared. That is half of swing, from Chapter 10! I found that one by luck. This recipe hands it to me.

(check-expect ((lens-H always-1) (up 0 0 1)) 1/2)
(check-within
((lens-H always-1)
((state-advancer uniform-law 1) (up 0 0 1) 10 1e-13))
1/2
1e-11)

The Seventh Commandment.

Write one function for the system, and derive its law. Never copy out by hand what a machine can derive.

That is the SICM way. One function says what the system is. Everything else is machinery that does not need to know. Tomorrow you hand that machinery the truth.

Exercises

17.1 Chapter 10’s cricket ball has the Hamiltonian “half of p squared, plus 10 times x”, with the time in the slot where z was. Feed it to hamiltonian->law with a symbolic state, and check that you get the law you wrote by hand in exercise 10.3. Is the value of this Hamiltonian conserved along the flight? What do people call it?

17.2 What is the Hamiltonian of a gap? Derive its law symbolically.

17.3 Your cancellation argument assumed that the Hamiltonian does not mention z. Repeat the symbolic check with (lens-H (literal-function 'kk)), adding a third term for the change through z: the slope of H along slot 0, times the rate of z. What is left? When is the value of the Hamiltonian not conserved?

17.4 In your mind. A Hamiltonian is changed by adding the same number, say 7, to its value at every state. What happens to the law derived from it?

18 The True Ray🔗

The Hamiltonian with nothing left out, and a ray that misses.

Here is the Hamiltonian of an electron in a round magnetic lens, with nothing left out. The lens is described by a function f of the place z and of s, the square of the electron’s distance from the axis. It is the field, in the units of k, averaged over the disc that reaches from the axis out to the electron. On the axis the disc is a point, and f is our old k.

; true-H : [Number Number -> Number] -> Hamiltonian
; the Hamiltonian of a round magnetic lens whose
; field, averaged over the disc of squared radius
; s about the axis at place z, is (f z s)
(define ((true-H f) y)
(let ((z (state-z y))
(x (state-x y))
(p (state-p y)))
(- (sqrt (- 1
(square p)
(square (* x (f z (square x)))))))))

Minus the square root of: one, minus p squared, minus the square of x times that averaged field. That looks nothing like lens-H.

Doesn’t it? Take the simplest field there is: the same everywhere, k. And leave everything unchosen.

> ((true-H (lambda (z s) 'k)) (up 'z 'x 'p))
(* -1 (sqrt (+ 1 (* -1 (expt k 2) (expt x 2))
(* -1 (expt p 2)))))

Minus the root of one, less k²x², less p².

For a ray near the axis and gently sloped, how big are k²x² and p²?

Small. Squares of small numbers.

So you need the square root of a number a little less than one. Try (sqrt (- 1 .0002)).

> (sqrt (- 1 .0002))
0.9998999949995

Very nearly .9999. The square root of one-minus-a-little is one, minus half the little.

Use that.

The little is p² + k²x². So the root is about 1 minus half of that, and the Hamiltonian, with its minus sign, is about: −1, plus half of p² plus k²x².

That is lens-H, with a −1 in front.

And what does the −1 do to the law?

Nothing: exercise 17.4. The law is made of slopes, and shifting a function by a constant does not change its slopes. So for rays close to the axis and gently sloped, the true law is the lens law.

Close to the axis: par-axial. Everything in Chapters 1 to 16 is called paraxial optics, and now you know what it is. It is the first term of the truth. Derive the true law for that steady field and look at it.

> ((hamiltonian->law (true-H (lambda (z s) 'k)))
(up 'z 'x 'p))
(up 1
(/ p (sqrt (+ 1 (* -1 (expt k 2) (expt x 2))
(* -1 (expt p 2)))))
(/ (* -1 (expt k 2) x)
(sqrt (+ 1 (* -1 (expt k 2) (expt x 2))
(* -1 (expt p 2))))))

The rate of x is p, divided by that same root. The rate of p is minus k²x, divided by the root.

It is the lens law, over a number that is very nearly 1. I can see the paraxial law sitting inside the true one.

And when is the root not nearly 1?

When p or x is not small. Steep rays, or rays far from the axis. For them the true rates are a little bigger than the lens law says.

Now a true field. For Glaser’s bell there is a formula for f off the axis. Type it carefully.

; bell-off : Number -> [Number Number -> Number]
; the field of the Glaser lens of strength q,
; averaged over the disc of squared radius s
; about the axis at z; on the axis it is (bell q)
(check-expect ((bell-off 4) 0 0) 2)
(check-within ((bell-off 3) 1/2 0) ((bell 3) 1/2)
1e-12)
(check-within ((bell-off 3) -4 0) ((bell 3) -4)
1e-12)
(define ((bell-off q) z s)
(let* ((c (- 1 (square z) s))
(rho (sqrt (+ (square c) (* 4 (square z)))))
(a (sqrt (/ (+ rho c) 2)))
(b (/ z a)))
(/ (* 2 (sqrt q) (+ 1 a))
(+ (square (+ 1 a)) (square (+ z b))))))

Where does that come from?

From a fact about magnetic fields in empty space. Inside the bore of the lens there is no wire and no iron. That one condition ties the field at every point of the bore to the field on the axis: know it on the axis and you know it everywhere inside. Your colleagues’ corpus proves that the field belonging to this formula is the only one whose value on the axis is Glaser’s bell. Does the average grow or shrink as the disc widens?

> ((bell-off 3) 0 0)
1.7320508075688772
> ((bell-off 3) 0 1/4)
1.856406460551018...

Over a disc half a half-width in radius, at the centre of the lens, it is seven per cent more than on the axis. So the field must be stronger away from the axis, and a ray out there is kicked harder than “in proportion”.

Two reasons, then, for a real lens to depart from the lens law: the square root, and the field itself. Test what you said about the first term.

(define TRUE-H (true-H (bell-off 3)))
(check-within (+ 1 (TRUE-H (up 0 .001 .002)))
((lens-H (bell-kk 3)) (up 0 .001 .002))
1e-10)
(check-within (+ 1 (TRUE-H (up 1/2 .002 -.001)))
((lens-H (bell-kk 3)) (up 1/2 .002 -.001))
1e-10)

They agree to ten places for a ray a thousandth of a half-width from the axis.

Now derive the true law of Glaser’s lens.

(define TRUE-LAW (hamiltonian->law TRUE-H))
> (TRUE-LAW (up -1. .01 .02))
(up 1 0.020004751674093883 -0.0075014067781427...)
> ((glaser-law 3) (up -1. .01 .02))
(up 1 0.02 -0.0075)

The paraxial law says .02 and −.0075. The true law says a hair more of each.

Each time you ask TRUE-LAW for its rates, it differentiates the whole Hamiltonian afresh, square roots and all. A stepper asks thousands of times. We can do the differentiating once, with nothing chosen. What comes back when a law is given an unchosen state?

A formula. As in Chapter 17, when the lens law came out as (up 1 p (* -1 x (kk z))). But this one will be enormous.

The kit will tell you how enormous.

> (formula-size TRUE-LAW)
3461

Nearly three and a half thousand symbols and numbers. I am glad I did not write it by hand.

A formula is a list. And a list that happens to be an expression can be turned into a procedure: that is what eval is for, and it is the subject of the last chapter of The Little Schemer. The kit wraps the two steps up as compile-law.

; the true law, as arithmetic and nothing else
(define FAST-LAW (compile-law TRUE-LAW))
(check-within (FAST-LAW (up -1. .01 .02))
(TRUE-LAW (up -1. .01 .02))
1e-15)

The same answers. So TRUE-LAW derives, and FAST-LAW only computes what was derived.

And computes it about ten times sooner. For one ray you will not notice: a tenth of a second against a hundredth. For the ten thousand rays of a real simulator you will.

In Chapter 5 you compiled a column into a table. Here the machine compiles a Hamiltonian into arithmetic. Now fire three electrons from the object at −4, aimed at the image plane at 1/4.

With state-advancer?

Not this time. state-advancer insists on tidying a law’s formula before it uses it, and three and a half thousand symbols of nested square roots defeat its tidying: it labours for some seconds and then stops with a complaint. The kit’s compile-law does no tidying. So for this one law you drive yourself: your own Runge–Kutta, which will follow any law, with 400 steps.

; landing : Number -> Number
; the height, at the plane z = 1/4, of the true
; ray that leaves the axis at -4 with sideways
; momentum a
(define (landing a)
(state-x
(runge-kutta FAST-LAW (up -4. 0 a) .25 400)))
> (landing .001)
-2.63...e-8
> (landing .01)
-2.641...e-5
> (landing .04)
-0.001720...

What did paraxial optics promise?

Zero, each time. (h-exact 1/4) is exactly 0, so every ray from the object should land on the axis. The gentle ray very nearly does: it misses by 26 thousand-millionths. The steep one misses by nearly two thousandths.

The image is not a point.

No real image is. Tomorrow you will measure how much it is not. How many lines of physics did you type today?

true-H is eight lines, and bell-off is another eight. hamiltonian->law works for any Hamiltonian whatever. The stepper is from Chapter 10. I did not write a single rate by hand.

(check-within (landing .001) 0 1e-7)
(check-within (landing .04) -.00172 1e-5)

Exercises

18.1 Empty space is a lens with no field: (true-H (lambda (z s) 0)). Derive its law symbolically. What are the rates of x and of p? Then send the ray (up 0. 0 3/5) a distance 4 with runge-kutta and check that it arrives at height 3. (A triangle with sides 3, 4 and 5 is hiding here. Which side is p?)

18.2 The value of TRUE-H is not conserved along a ray through Glaser’s lens. Compute it at the start and at the end of the ray that leaves with momentum .04. Which part of your cancellation argument from Chapter 17 fails?

18.3 Near the axis, the field (f z s) is close to (k z) minus one eighth of s times the slope of the slope of k at z. Test this for the bell of strength 3 at z = 1/2 with s = 1/100 and then 1/400, using D twice on (bell 3). By what factor should the discrepancy shrink (the Fifth Commandment)?

18.4 How good is 400 steps? Compute (landing .01) with 200, 400 and 800 steps by editing a copy of landing that takes the number of steps. What should the differences do?

19 What the Straight Line Forgot🔗

One number, measured two ways, that no round lens can make zero.

Yesterday three true rays missed the image point. Fire two of them again, and one in between, and look at the misses side by side.

> (landing .01)
-2.641...e-5
> (landing .02)
-0.0002120...
> (landing .04)
-0.001720...

What does the Law of Two Rays say about doubling a ray?

Everything about it doubles. The landing height should double, though twice zero is zero.

And what do these do?

> (/ (landing .02) (landing .01))
8.028...
> (/ (landing .04) (landing .02))
8.114...

Eight times, not twice. Eight is two times two times two. When the momentum doubles, the miss grows as its cube.

So here is something that breaks the Law of Two Rays. Where have you seen a lens do that?

bad-kick, in Chapter 4: the lens that lowered the slope by the square of the height. This is a real lens doing something of the same kind.

Opticists have a word for whatever does that.

The Eighth Commandment.

An aberration is a departure from the Law of Two Rays. To find one, look for what does not double when the ray doubles.

And this particular one?

Spherical aberration. The name is inherited from glass lenses with spherical faces, and has nothing to do with our field. It is measured by a number, the coefficient of spherical aberration, written Cs, defined so that the miss at the image is the magnification, times Cs, times the cube of the momentum the ray set out with.

Then I can measure it with one ray: divide the miss by the magnification, which is −1/4, and by the cube.

; cs-by-ray : Number -> Number
; the spherical aberration coefficient of the
; Glaser lens of strength 3 with its object at
; -4, as one true ray of momentum a measures it
(define (cs-by-ray a)
(/ (landing a) (* -1/4 (cube a))))
> (cs-by-ray .04)
107.53...
> (cs-by-ray .02)
106.01...
> (cs-by-ray .01)
105.64...

About 105. But the three rays do not agree. Which one is right?

None of them. The cube is only the first thing the straight line forgot; beyond it there is a fifth power, and a seventh. The coefficient is what your measurements approach as the ray becomes gentle. Are they approaching something?

107.53, 106.01, 105.64. The steps are 1.52, then .37. Each halving of the momentum brings a step about a quarter of the last. I have been here before, in Chapter 7: if it goes on that way, the steps still to come add up to a third of the last one. A third of .37 is .12. So about 105.52.

You did that sum by eye. Do it by algebra. If the error quarters each time you halve, then the worse measurement is off by four times as much as the better one.

Call the true value T and the better one’s error e. The better measurement is T + e. The worse is T + 4e.

Four times the better is 4T + 4e. Subtract the worse: 3T is left, and the errors are gone. Divide by three.

; cs-by-rays : Number -> Number
; the same coefficient from two true rays, of
; momentum a and 2a, combined so that the part
; of the miss that goes as the fifth power cancels
(define (cs-by-rays a)
(/ (- (* 4 (cs-by-ray a)) (cs-by-ray (* 2 a)))
3))
> (cs-by-rays .01)
105.51...

That is a measurement, made by firing electrons at a wall and seeing where they hit. In Chapter 13 you learned what is better than a measurement. Is there a way to get Cs with no true rays at all?

Glaser’s lens had a disguise. Does the aberration?

In 1936 Otto Scherzer found that it does, for every round magnetic lens. The coefficient is a sum piled up along the paraxial axial ray, the plain H of Chapter 11. At each place you need only h, its slope dh, the field k, and the slope of the field. This is what piles up, per unit length. Half of the sum of three terms:

  • twice the fourth power of k·h;

  • the square of h, times the square of: h times the slope of k, plus dh times k;

  • the square of k·h·dh.

Something that piles up along the ray, at a rate that depends on the state. In Chapter 10 you promised passengers. I add a fourth number to the state and a fourth rate to the law. And the slope of k is (D k).

; cs-law : [Number -> Number] -> Law
; for states (up z h dh c): the paraxial axial
; ray of the lens whose field on the axis is k,
; and Scherzer's sum c piling up along it
(define ((cs-law k) y)
(let* ((z (ref y 0))
(h (ref y 1))
(dh (ref y 2))
(kz (k z))
(dkz ((D k) z)))
(up 1
dh
(- (* (square kz) h))
(* 1/2
(+ (* 2 (expt (* kz h) 4))
(* (square h)
(square (+ (* h dkz) (* dh kz))))
(square (* kz h dh)))))))

For the professional stepper you need a knob.

The strength again.

; glaser-cs-law : Number -> Law
(define (glaser-cs-law q)
(cs-law (bell q)))
; cs-by-integral : Number Number Number -> Number
; the spherical aberration coefficient of the
; Glaser lens of strength q, for an object at zo
; and its image at zi
(define (cs-by-integral q zo zi)
(ref ((state-advancer glaser-cs-law q)
(up zo 0 1 0) (- zi zo) 1e-13)
3))
> (cs-by-integral 3 -4 1/4)
105.517525958...

It agrees with the true rays. And it never left the axis: it only followed H.

Does 105.517525958 smell of anything?

Not to me.

Nor to anyone. But your colleagues carried out Scherzer’s sum for this lens with pencil, paper and a proof assistant. Their theorem says the coefficient is exactly 102/5 plus 867/32 times π.

(define CS-EXACT (+ 102/5 (* 867/32 pi)))
(check-within (cs-by-integral 3 -4 1/4)
CS-EXACT
1e-10)
(check-within (cs-by-rays .01) CS-EXACT 2e-3)
> CS-EXACT
105.51752595819846

My sum agrees to twelve figures. My two rays agree to five.

So I have the same number three ways. From true rays, which know nothing of Scherzer. From Scherzer’s sum, which knows nothing of true rays. And from a proof, which did no arithmetic at all.

The Ninth Commandment.

Compute every number that matters in two ways that share as little as possible.

Your colleagues’ wishlist has a function called Aberration_Coefficients, with an argument Method that is one of Scherzer_Integral or Ray_Tracer. Why would anyone want both?

For this. The sum is fast and precise but it is a formula someone derived, and I typed it. The rays are slower and rougher, but they come straight from the Hamiltonian. If they agree, I believe both.

They also certify the lens of strength 3/2: its coefficient lies between 103.47103754630 and 103.47103754634.

> (cs-by-integral 3/2 -4 (glaser-image 3/2 -4))
103.471037546...
(check-within
(cs-by-integral 3/2 -4 (glaser-image 3/2 -4))
103.47103754632
3e-11)

Inside their interval.

Now look hard at the three terms that pile up. What kind of thing is each?

A fourth power. A square times a square. A square. None of them can be negative, whatever the lens, whatever the ray.

So the sum can only grow. Cs is positive. Always?

For every lens that is round, steady in time, with no charge or current where the beam flies, and through which the electrons never turn back. That is Scherzer’s theorem, and it is the central fact of electron optics.

Scherzer's Law.

The spherical aberration of a round lens is a sum of squares. It cannot be zero and it cannot be negative.

Why is that so terrible? Every number has to be something.

A maker of glass lenses has the same trouble with one lens. She cures it by adding a second lens whose aberration has the opposite sign. What can you add?

Another round magnetic lens. Whose Cs is also positive. Nothing I am allowed to build has the other sign.

For sixty years that was the wall every electron microscope stood against. What does the sign mean for the rays? The magnification is negative, the momentum was positive, Cs is positive.

So the miss is negative: the steep ray arrives below the axis. It came from above, so it has already crossed. Steep rays cross the axis before the image plane, and the steeper, the sooner. The lens is too strong for them.

As yesterday’s two reasons said: the square root, and the stronger field away from the axis.

Rays near the image plane, drawn from the cube law with the slopes greatly exaggerated. Gentle rays cross the axis at the image; steeper ones cross earlier. Nowhere do they all meet.

Rays near the image plane, drawn from the cube law with the slopes greatly exaggerated. Gentle rays cross the axis at the image; steeper ones cross earlier. Nowhere do they all meet.

And which part of a column contributes most to the sum? Look at the powers of h.

Every term has h to the fourth power in all, counting dh as one. So what matters is where the beam is wide inside a strong field. A lens the beam passes through as a thin pencil adds almost nothing.

In a microscope that is the last lens, the objective, where the beam is widest just before it is brought to its final point. Designers spend their effort there. One last conversion. Cs as we defined it multiplies the cube of the momentum at the object. An operator thinks about the slope with which rays arrive at the specimen.

By the Law of the Determinant, a ray that leaves with momentum a arrives with slope a over the magnification. So a is the magnification times the arriving slope b. The miss is M times Cs times the cube of M times b: M to the fourth, times Cs, times b cubed.

; cs-at-image : Number Number -> Number
; a spherical aberration coefficient, referred to
; the slopes at the image instead of the object
(check-expect (cs-at-image 256 -1/4) 1)
(define (cs-at-image cs m) (* (expt m 4) cs))
> (cs-at-image CS-EXACT -1/4)
0.4121778...

A fearsome 105 half-widths at the object is .41 half-widths at the image.

And if the half-width is two millimetres, and rays arrive at slopes up to one hundredth?

.41 times 2 millimetres is .82 millimetres. Times the cube of a hundredth, which is a millionth: .82 millionths of a millimetre. Under a nanometre.

A few atoms wide. That is the scale at which this number matters, and why people fought it for sixty years.

How did they win?

Read Scherzer’s Law again, with its conditions. Round. Steady. Empty. No turning back. A theorem is only as strong as its hypotheses.

The Tenth Commandment.

To beat Scherzer, break one of his assumptions, on purpose and by name.

The correctors in the best microscopes today break round: they use fields with four, six and eight poles around the axis. Others use mirrors, which break no turning back. Your colleagues’ corpus contains proofs that each escape really is one. That is another book.

Exercises

19.1 Check your claim about cs-by-rays: compute it for a = .02 and .01 and see how fast it closes in on CS-EXACT. What power of a does the remaining error seem to go as? What else limits you? (Exercise 18.4.)

19.2 Design scherzer-terms, which consumes k, the slope of k, h and dh at one place and produces a list of the three terms. Then call it with four symbols. Can the machine tell you that each term is never negative? Can you?

19.3 In your mind, then on the machine. Keep the image at 1/4 but move the object away, to −8 and then −40, choosing the strength each time with strength-for. The coefficient at the object grows enormously. What happens to cs-at-image? Which of the two numbers should a designer watch?

19.4 Scherzer’s sum works for any lens, not only Glaser’s. Use cs-law with your own rk4-step on a uniform lens of pace 1 and length π (a field with edges: k is 1 and its slope is 0). You know h and dh there exactly, so you can also add the sum up by definite-integral. Do the two agree?

20 Colour🔗

Not all electrons are the same. The lens can tell, and cannot help.

Until now every electron in the beam had the same momentum. Does a real source manage that?

I doubt it. Nothing real is perfectly alike.

A source is a hot tip of metal, or a cold one in a fierce electric field. Either way, the electrons leave with slightly different energies: a spread of something like half a volt, on top of the thousands of volts that accelerate them. Recall the Law of the Round Lens. Where does the momentum appear?

k is the field, times the charge, over twice the momentum. So an electron with a little more momentum sees a little less k. The lens is weaker for it.

Opticists borrow a word from light, where rays of different energy have different colours. An electron with more momentum than the rest is a different colour. Suppose its momentum is (+ 1 d) times the proper one. By what is its k divided?

By (+ 1 d).

And the strength q?

The strength goes as k squared. So it is divided by the square of (+ 1 d).

; detuned : Number Number -> Number
; the strength a Glaser lens of strength q has
; for an electron whose momentum is (1 + d)
; times the momentum the lens was set for
(check-expect (detuned 3 0) 3)
(check-expect (detuned 3 1) 3/4)
(define (detuned q d) (/ q (square (+ 1 d))))

Our lens of strength 3 images −4 onto 1/4 for the proper colour. Where does a ray of another colour meet the plane at 1/4?

I do not need to trace anything. Each colour has its own Glaser lens, and Chapter 13 gave me the axial ray of every Glaser lens.

; off-colour : Number -> Number
; the height at the plane z = 1/4 of the axial
; ray from -4, for an electron whose momentum is
; (1 + d) times the proper one
(check-within (off-colour 0) 0 1e-12)
(define (off-colour d)
((glaser-h (detuned 3 d) -4) 1/4))
> (off-colour .001)
0.0050050...
> (off-colour .002)
0.0100062...
> (off-colour -.001)
-0.0050087...

One part in a thousand too much momentum, and H is still five thousandths above the axis at the plane where it should have landed.

Above the axis. It has not crossed yet. Why?

The lens is weaker for it, so its image is further along. Faster electrons focus later.

And how does the miss grow with d?

Double the d, double the miss, very nearly. And the opposite d gives the opposite miss, very nearly. So for small d the miss is some constant times d.

That constant, suitably dressed, is the coefficient of chromatic aberration, Cc. A true ray leaves the object with momentum a, of a colour that is off by d. Its miss at the image is: minus the magnification, times Cc, times d, times a.

off-colour is the miss of H, whose a is 1. So Cc is off-colour, divided by d, and by minus the magnification, which is a quarter.

Divided by d… as d becomes small. Rise over run, with the run made to vanish. That is a slope! Cc is the slope of off-colour at zero, over a quarter. And I have the machine for slopes.

; CC-BY-RAYS : Number
; the chromatic aberration coefficient of the
; Glaser lens of strength 3 with its object at
; -4: how fast the landing height of H changes
; with its colour, over minus the magnification
(define CC-BY-RAYS (/ ((D off-colour) 0) 1/4))
> CC-BY-RAYS
20.0276531666...

You used D on something that is not a path.

D does not care what its function means. Here the function consumes a colour and produces a height. Its slope is “height per unit of colour”. That is exactly what an aberration coefficient is.

And D went through detuned, into glaser-h, through a square root, a sine and two arctangents.

It read my program. As in Chapter 9.

The Ninth Commandment asks for a second way. Scherzer has one for colour too, and it is simpler than the last: along the paraxial axial ray, pile up twice the square of k·h.

The same passenger trick, with a simpler passenger.

; cc-law : [Number -> Number] -> Law
; for states (up z h dh c): the paraxial axial
; ray of the lens whose field on the axis is k,
; and the chromatic sum c piling up along it
(define ((cc-law k) y)
(let* ((z (ref y 0))
(h (ref y 1))
(dh (ref y 2))
(kz (k z)))
(up 1
dh
(- (* (square kz) h))
(* 2 (square (* kz h))))))
; glaser-cc-law : Number -> Law
(define (glaser-cc-law q)
(cc-law (bell q)))
; cc-by-integral : Number Number Number -> Number
; the chromatic aberration coefficient of the
; Glaser lens of strength q, for an object at zo
; and its image at zi
(define (cc-by-integral q zo zi)
(ref ((state-advancer glaser-cc-law q)
(up zo 0 1 0) (- zi zo) 1e-13)
3))
> (cc-by-integral 3 -4 1/4)
20.0276531666...

And the theorem: 51/8 times π.

(define CC-EXACT (* 51/8 pi))
(check-within (cc-by-integral 3 -4 1/4)
CC-EXACT
1e-10)
(check-within CC-BY-RAYS CC-EXACT 1e-10)
> CC-EXACT
20.02765316663493

Three ways again, and this time all three agree to twelve figures.

Why is CC-BY-RAYS so much better than cs-by-rays was?

cs-by-rays fired true rays with a stepper and then guessed the limit from two of them. Here the rays are exact formulas, and D takes the limit exactly. No steps, and no guessing.

Look at what piles up.

Twice a square. So Cc is positive too, for every lens. Scherzer’s Law again: faster electrons always focus later, and no round lens can be built in which they focus sooner, to cancel it.

Now a subtle question. The chromatic miss is proportional to a. Double the ray and the miss doubles. Does it break the Law of Two Rays?

It doubles when the ray doubles, so… no. For any one colour, the lens is a perfectly good Glaser lens, and the Law of Two Rays holds in it exactly.

Then why call it an aberration?

Because the beam is a mixture. Each colour has its own image plane. The specimen can only be at one of them. Every other colour arrives a little early or a little late, and paints a little disc instead of a point.

So there are two different ways for an image to fail. The lens can be wrong for some rays of one colour, or right for each colour at a different place. Which blur grows faster as you open the aperture?

The spherical miss goes as the cube of the angle. The chromatic one goes as the angle itself. With a wide cone, the cube wins and the blur is spherical. With a narrow cone, the chromatic blur is what is left.

How large is d in practice? You are told the spread of energy: say 0.6 volts in 10 000. For slow electrons, energy goes as the square of momentum. If the momentum is off by a fraction d, by what fraction is its square off?

> (square (+ 1 'd))
(+ 1 (expt d 2) (* 2 d))

By 2·d, and a d squared which is far too small to matter. So the fraction by which momentum is off is half the fraction by which energy is off. Half of 0.6 over 10 000: three parts in a hundred thousand.

At ten thousand volts an electron is travelling at a fifth of the speed of light, and “half” is off by about one part in a hundred. Chapter 21 has the correction. Last question, and it needs something from Chapter 11. Could a cleverer magnetic lens narrow the energy spread, so that the colours come back together?

A magnetic field pushes across the motion, never along it. It cannot change any electron’s speed. So whatever spread of energy leaves the source arrives at the specimen.

An invariant, named in Chapter 11 before it was needed. Within Scherzer’s rules, the only cures for colour are a better source, a higher voltage, or a filter that throws away the electrons of the wrong energy, with the usual price.

Electrons. It is always electrons.

Your colleagues’ Beamlet has two fields for this, e and de: the energy of the electrons in it, and how wide a band of energies it stands for. Now you know why they bothered.

Exercises

20.1 Design cc-at-image, like cs-at-image. A ray leaves with momentum a and arrives with slope b; rewrite “minus M times Cc times d times a” in terms of b. Which power of the magnification appears? Evaluate it for our lens.

20.2 Scherzer’s chromatic sum has a twin: pile up twice the square of dh instead of twice the square of k·h. Design cc-law.v2 and its knob version, and show that it gives the same coefficient for the bell lens of strength 3, and for strength 3/2. (The proof corpus certifies 20.2665600622 for the latter.) Two different things pile up to the same total. Are the two rates equal at each place along the way?

20.3 What is the slope of the slope of off-colour at 0? Ask D twice. What does a non-zero answer say about the claim that the miss is “some constant times d”?

20.4 In your mind. A microscope is run at 10 000 volts and then at 1000 volts, with the same source, and the lens current is lowered so that the strength q is the same. By what factor does d change? What happens to the chromatic blur at a given arrival slope?

21 The Probe🔗

In which lengths get their metres back, and four blurs fight over one spot.

A scanning electron microscope forms an image of its source on the specimen. That image is called the probe, and the smaller it is, the finer the detail the microscope can show. You now know three things that keep it from being a point. Name them.

The source itself has some size, and the probe is its image, so it has the size of the source times the magnification. Spherical aberration smears it by an amount that goes as the cube of the arrival slope. Chromatic aberration smears it by an amount that goes as the slope times the spread of colour.

So close the aperture and let the slopes be tiny. What stops you?

Current: Chapter 16. But if I were patient, nothing. The probe would shrink to the image of the source.

Something does stop you, and it is the fourth and last law I shall ask you to take on trust. An electron is also a wave. Its wavelength is a constant of nature, named after Max Planck, divided by its momentum. And a wave that converges in a cone of half-angle b cannot be brought to a spot much smaller than 0.61 wavelengths divided by b.

Divided by b? Then a narrower cone makes a bigger spot. That is the opposite of everything else.

It is called diffraction. So there will be a best angle, neither too open nor too closed, and finding it is the first task of every column designer. First we need metres. So far every length was in half-widths and every momentum was 1. Here are four constants of nature.

(define E-CHARGE 1.602176634e-19) ; coulombs
(define E-MASS 9.1093837015e-31) ; kilograms
(define LIGHT 299792458.) ; metres a second
(define PLANCK 6.62607015e-34) ; joule seconds

An electron accelerated through v volts has gained an energy of its charge times v. For a slow electron the momentum is the square root of twice the mass times that energy. For a fast one, relativity adds a term. The word momentum already means something in mechanics, so pick another name.

; volts->momentum : Number -> Number
; the momentum, in kilogram metres a second, of
; an electron accelerated through v volts
(check-within (volts->momentum 10000)
5.4291e-23 1e-26)
(define (volts->momentum v)
(let ((t (* E-CHARGE v))
(mc2 (* E-MASS (square LIGHT))))
(/ (sqrt (+ (square t) (* 2 t mc2))) LIGHT)))
; wavelength : Number -> Number
; the wavelength, in metres, of such an electron
(check-within (wavelength 10000) 1.2205e-11 1e-15)
(define (wavelength v)
(/ PLANCK (volts->momentum v)))

At ten thousand volts the wavelength is 12 millionths of a millionth of a metre. An atom is twenty times bigger.

Which is why people build electron microscopes. Now redeem a promise from Chapter 11. The strength q is the square of: charge, times peak field, times half-width, over twice the momentum. Turn it around.

; peak-field : Number Number Number -> Number
; the field, in tesla, at the centre of a Glaser
; lens of strength q and half-width a metres,
; for electrons of v volts
(check-within (peak-field 3 .002 10000) .587 1e-3)
(define (peak-field q a v)
(/ (* 2 (sqrt q) (volts->momentum v))
(* E-CHARGE a)))

.587 tesla, as you said.

And the spread of colour. In Chapter 20 you said the momentum is off by half the fraction the energy is off by. With relativity the half becomes a little more.

; momentum-spread : Number Number -> Number
; the fraction by which momentum varies in a beam
; of v volts whose energies are spread over de volts
(check-within (momentum-spread 10000 .6)
3.029e-5 1e-8)
(define (momentum-spread v de)
(let ((t (/ (* E-CHARGE v)
(* E-MASS (square LIGHT)))))
(* (/ de v) (/ (+ 1 t) (+ 2 t)))))

Now data definitions for the two ends of a column. Each is a few numbers with names.

Two structures.

; A Source is (make-source Number Number Number)
; interpretation (make-source d de v) is an
; electron source that appears d metres across,
; whose electrons have energies spread over de
; volts, accelerated through v volts.
(define-struct source (d de v))
; An Objective is
; (make-objective Number Number Number)
; interpretation (make-objective a zo zi) is a
; Glaser lens of half-width a metres that images
; the plane at zo onto the specimen at zi; zo and
; zi are in half-widths from the centre of the lens.
(define-struct objective (a zo zi))

The Objective has no strength?

Does it need one?

No: strength-for gives it, from zo and zi. The operator has already focused.

Here is a source of a common kind, a hot zirconium-coated tungsten needle, and a plausible objective: two millimetres of half-width, the source 80 millimetres up the column, the specimen 2 millimetres below the centre of the lens.

(define NEEDLE (make-source 2e-8 .6 10000))
(define OBJ (make-objective .002 -40 1))

What do you need to know about the lens, to compute the probe?

Its magnification, and its two aberration coefficients, referred to the image, in metres. Those do not depend on the aperture, so I should compute them once and keep them. A compiler again, as in Chapter 5.

; An Optics is (make-optics Number Number Number)
; interpretation (make-optics m cs cc) is what a
; lens does at its image: it magnifies by m, with
; spherical and chromatic aberration coefficients
; cs and cc, in metres, both referred to the
; slopes at the image.
(define-struct optics (m cs cc))
; objective->optics : Objective -> Optics
(define (objective->optics o)
(let* ((zo (objective-zo o))
(zi (objective-zi o))
(q (strength-for zo zi))
(m (glaser-mag q zo)))
(make-optics
m
(* (objective-a o)
(cs-at-image (cs-by-integral q zo zi) m))
(* (objective-a o)
(square m)
(cc-by-integral q zo zi)))))
(define OPT (objective->optics OBJ))
> OPT
(make-optics
-0.03534429...
0.00213946...
0.00419029...)
> (peak-field (strength-for -40 1) .002 10000)
0.3061198...

It demagnifies 28 times. Cs is 2.1 millimetres and Cc is 4.2 millimetres. The field is .31 tesla.

(check-within (optics-m OPT) -.035344 1e-6)
(check-within (optics-cs OPT) .0021395 1e-7)
(check-within (optics-cc OPT) .0041903 1e-7)

Those are respectable numbers for a real instrument. Now the budget. Your colleagues have already written its data definition.

; A Blur is
; (make-blur Number Number Number Number)
; interpretation (make-blur geo sph chr dif) is
; the probe-size budget where the source is imaged.
; Each number is the diameter, in metres, the probe
; would have if only that effect acted: geo from
; the size of the source, sph from spherical
; aberration, chr from chromatic aberration, dif
; from diffraction.
(define-struct blur (geo sph chr dif))

For rays that arrive at slopes up to b: the image of the source is its size times the magnification. The spherical disc, at the plane where it is narrowest, has a diameter of half of Cs times b cubed. The chromatic disc is Cc times b times the momentum spread. The diffraction disc is 0.61 wavelengths over b.

; probe : Source Optics Number -> Blur
; the blur budget of the probe when rays arrive
; at slopes up to b
(define (probe src opt b)
(make-blur
(* (abs (optics-m opt)) (source-d src))
(* 1/2 (optics-cs opt) (cube b))
(* (optics-cc opt) b
(momentum-spread (source-v src)
(source-de src)))
(/ (* .61 (wavelength (source-v src))) b)))

A caution. The factors 1/2 and 0.61, and a factor of 1 that you cannot see in the chromatic term, depend on what one means by the diameter of a fuzzy disc. These are the ones your colleagues’ corpus uses. Their data definition speaks of the disc that holds half the current, for which the usual factors are a little different. When they settle it, you change four numbers.

And the total? Do I add the four?

If four independent causes each nudge an electron sideways at random, the nudges do not line up. They combine as the sides of a right triangle do: square, add, take the root.

; blur-total : Blur -> Number
; the diameter of the probe when all four act
(check-expect (blur-total (make-blur 2 4 5 6)) 9)
(define (blur-total bl)
(sqrt (+ (square (blur-geo bl))
(square (blur-sph bl))
(square (blur-chr bl))
(square (blur-dif bl)))))
; in-nm : Number -> Number
; metres as nanometres, to two decimal places
(check-within (in-nm 1.234e-9) 1.23 1e-9)
(define (in-nm x) (/ (round (* x 1e11)) 100))
; budget : Blur -> [List-of Number]
; geo, sph, chr, dif and the total, in nanometres
(define (budget bl)
(map in-nm
(list (blur-geo bl) (blur-sph bl)
(blur-chr bl) (blur-dif bl)
(blur-total bl))))
> (budget (probe NEEDLE OPT .002))
(list 0.71 0.01 0.25 3.72 3.8)
> (budget (probe NEEDLE OPT .005))
(list 0.71 0.13 0.63 1.49 1.77)
> (budget (probe NEEDLE OPT .01))
(list 0.71 1.07 1.27 0.74 1.95)
> (budget (probe NEEDLE OPT .02))
(list 0.71 8.56 2.54 0.37 8.96)

At two thousandths the probe is 3.8 nanometres and nearly all of it is diffraction. At twenty thousandths it is 9 nanometres and nearly all of it is spherical. In between it dips below 2.

The four blurs and their total against the arrival slope, for the needle source and the objective of this chapter. Diffraction falls, the aberrations rise, and the probe is smallest where they trade places.

The four blurs and their total against the arrival slope, for the needle source and the objective of this chapter. Diffraction falls, the aberrations rise, and the probe is smallest where they trade places.

Find the bottom of the dip.

I could do something clever. But a list of candidate angles and a fold that remembers the best one so far will do.

; ANGLES : [List-of Number]
; slopes from 1 to 100 thousandths, 100 to a decade
(define ANGLES
(build-list
201
(lambda (i) (* 1/1000 (expt 10 (/ i 100))))))
; best-angle : Source Optics -> Number
; the arrival slope that makes the smallest probe
(define (best-angle src opt)
(define (total b) (blur-total (probe src opt b)))
(foldl
(lambda (b best) (if (< (total b) (total best)) b best))
(car ANGLES)
(cdr ANGLES)))
> (best-angle NEEDLE OPT)
0.006918...
> (budget (probe NEEDLE OPT (best-angle NEEDLE OPT)))
(list 0.71 0.35 0.88 1.08 1.6)

A probe of 1.6 nanometres, with rays arriving at slopes up to seven thousandths.

(check-within (best-angle NEEDLE OPT) .0069 2e-4)
(check-within
(blur-total (probe NEEDLE OPT (best-angle NEEDLE OPT)))
1.6e-9
1e-11)

Sixteen ångströms, from a needle, a coil and some iron. Read the budget at the best angle like a designer. Who is to blame?

Diffraction is the largest, then colour, then the source, and spherical aberration last. Nobody dominates. That must be what “best” means: if one term were far bigger than the rest, I could trade it down against the others.

What would you change to do better?

Raise the voltage. The wavelength shrinks, so diffraction shrinks. The same 0.6 volts is a smaller fraction, so colour shrinks. Both of my biggest terms improve.

And what does it cost?

For the same strength, peak-field must rise in proportion to the momentum. At 30 000 volts…

> (peak-field (strength-for -40 1) .002 30000)
0.5353...

More current in the coil, and more heat.

And iron stops helping at about two tesla, so a smaller or stronger lens soon has nowhere to go. And there are specimens that 30 000 volts will burn or see straight through. Every term in the budget is somebody’s constraint. What else?

Bring the specimen closer to the lens, so that the lens is stronger and its aberrations smaller. Exercise 19.3 hinted at it. Or move the source further away, to shrink its image, and pay in current. Or buy a source with less energy spread.

You are speaking as an opticist does. Look at the signature of what you have built: a Source and an Objective go in, a Blur comes out, and in between are a field, two rays, two sums, and a square root. Every piece of it you designed from a data definition and tested against a number you could trust.

Most of them against theorems. And some of them I proved.

That is the part your colleagues will envy.

Exercises

21.1 Run the same column at 1000, 3000 and 30 000 volts, refocusing each time (the Objective stays the same; why?). Tabulate the best angle and the budget. Which term is to blame at low voltage?

21.2 Vary the working distance: keep the source at −40 and put the specimen at zi = 0, 1/2, 1 and 2. For each, compute the Optics, the best probe, and the peak field. Explain the trend using the weight h to the fourth power from Chapter 19.

21.3 The current in the probe is the brightness of the source, times the area of the image of the source, times the solid angle of the cone, which for a narrow cone is π times b squared. Design probe-current. Our needle has a brightness of about 5·10¹¹ amperes per square metre per unit solid angle at 10 000 volts. How many electrons a second arrive in the 1.6 nanometre probe? (One ampere is 6.24·10¹⁸ electrons a second.)

21.4 The aperture that sets b is a real hole in a real plate. Suppose it sits at the centre of the lens, z = 0. Use glaser-h, the magnification, and the half-width to design hole-radius, which consumes an Objective and an arrival slope b and produces the radius of the hole in metres. How big is the hole for the best angle? Could you drill it?

22 The Fine Print🔗

A theorem has a signature. Tonight we read what Scherzer’s consumes.

Recite Scherzer’s Law.

The aberrations of a round lens are sums of squares. They cannot be zero and cannot be negative.

And the Tenth Commandment.

To beat Scherzer, break one of his assumptions, on purpose and by name.

Tonight we learn the names. Someone hands you a function and tells you it always produces a positive number. What do you ask first?

What it consumes. A function promises nothing about an argument outside its signature.

A theorem is a function of that kind. Write the signature of Scherzer’s, as Chapter 19 left it with you.

; scherzer : Lens -> PositiveNumber

That is too generous. “Lens” is not a data definition. It is a word.

Then do step 1 of the recipe. I shall read the conditions out of Harald Rose’s textbook, in his order. The fields do not change in time. The fields are the same after any turn about the axis. There is no charge in the space where the beam flies. The object and the image are real, and no electron reverses its motion along the axis.

; A ScherzerLens is a lens that is all of:
; - static: its fields do not change in time
; - round: a turn about the axis changes nothing
; - empty: no charge where the beam flies
; - one-way: real object, real image, and no
; electron turns back along the axis
; scherzer : ScherzerLens -> PositiveNumber

It is not an itemization. An itemization says “one of”, and this says “all of”. A lens must pass four tests to be a ScherzerLens. To stop being one, it need fail only one.

That is the Tenth Commandment: step 1 of the design recipe, turned on somebody else’s function. Is (kick 0 r) a ScherzerLens?

Static, round, empty. But it forms no image, so the fourth line fails. Which is as well: its aberration is zero, and the theorem says zero is impossible.

Four lines, so four ways out. Scherzer proved the theorem in 1936. In 1947 he published a way round each of his own conditions.

He built the wall, and eleven years later he drew four doors in it.

Break one-way. What must be built?

Something that sends the electrons back the way they came. A mirror?

Rempfer and Mauck, 1985. Could your programs follow an electron through one?

No. Every state since Chapter 10 begins with z, and z is the clock. An electron that turns back crosses the same z twice. My clock would have to run backwards.

Break empty.

Put charge where the beam is. But charge must sit on something.

On a thin foil, and the beam goes through the foil. Typke, 1972. The electrons scattered in it, and the scattering undid whatever the correction gained. Break static.

Fields that change while the electron is inside them. Then two electrons that arrive at different moments meet two different lenses. The beam would have to come in pulses, timed to the field. And my states have no time in them. Only z.

Schönhense and Spieker, 2002. Break round.

Fields that a turn about the axis does change: the poles of Chapter 19. A ray has been one height and one slope. A field that is not round has a left and a right, so the state needs a second direction. One data definition changes. I can see nothing else that must.

Rose calls that door the most successful, and it is the one we take. But first, three remarks about the wall, because it was never what it was said to be.

“Cannot be zero and cannot be negative.” Positive, then. Is positive large?

No. One millionth is positive.

Walter Glaser made that objection in a note at the back of his textbook of 1952. To call the error unavoidable in principle, he wrote, is unjustified until somebody proves a floor: a number greater than zero that no lens can go below.

He had a stake in it?

In 1940 he had published a field free of spherical aberration. In the same book he concedes what became of it: it was shown to be too weak to form an image.

I designed that lens in Chapter 1. It is (kick 0 r).

His own bell does have a floor, and his book prints it. For a source far away, with k² his letter for our strength q, and d his half-width:

C/d = [ πk²/(4(k²+1)^(3/2))
− (1/8)·((4k²−3)/(4k²+3))·sin(2π/√(k²+1)) ]
/ sin⁴(π/√(k²+1))

The square root of k² + 1 is (pace q), from Chapter 13. An example by hand, at strength 3. The pace is 2. The sine of 2π over 2 is the sine of π: zero, so the second term goes. The sine of π over 2 is 1. What is left is 3π over 4 times 8.

; glaser-cs-far : Number -> Number
; the spherical aberration coefficient, in
; half-widths and referred to the image, of a
; Glaser lens of strength q with its object far away
(check-within (glaser-cs-far 3) (* 3/32 pi) 1e-12)
(define (glaser-cs-far q)
(let ((w (pace q)))
(/ (- (/ (* pi q) (* 4 (cube w)))
(* 1/8
(/ (- (* 4 q) 3) (+ (* 4 q) 3))
(sin (/ (* 2 pi) w))))
(expt (sin (/ pi w)) 4))))

You have typed a formula out of a book printed in 1952. The Ninth Commandment.

A second way. Chapter 19’s cs-by-integral piles up Scherzer’s sum and has never heard of this formula. I put the object 4000 half-widths away and refer the coefficient to the image.

(check-within
(cs-at-image
(cs-by-integral 3 -4000 (glaser-image 3 -4000))
(glaser-mag 3 -4000))
(glaser-cs-far 3)
1e-4)

It passes. Glaser could integrate, and I can copy.

Now look for the floor.

> (map glaser-cs-far (list 1 3 5 7 9 20))
(list
0.7356...
0.2945...
0.2566...
0.2525...
0.2571...
0.3085...)

It falls, turns near 7, and rises again. It never goes below a quarter.

Glaser’s table has 0.294 at 3 and a flat minimum of 0.252 near 7. For his own family the floor is a quarter of a half-width.

Then the floor is a length, and I can make the half-width small.

With what field?

> (peak-field 7 .002 10000)
0.8965...
> (peak-field 7 .0005 10000)
3.586...

At two millimetres, .9 tesla. At half a millimetre, 3.6 tesla, and Chapter 21 said iron stops helping at about two. So the floor is not in Scherzer’s theorem. It is in the iron.

The theorem alone is no wall. The theorem and the materials together are. The second remark. Two years before the theorem, in 1934, Brüche and Scherzer wrote the first textbook of electron optics. For a short weak lens it works out how far the focus of an outer ray shifts, and the answer is a sum whose terms are squares.

So outer rays always cross early. The theorem is on the page.

The squares are on the page. The conclusion is not. A later section says that objectives practically free of error appear possible in principle, and that whether they are built is not least a question of economics.

He looked at a sum of squares and saw a budget.

For two years. What does that say about a passing test?

That a fact can sit in my own file and I can fail to read it. The squares in cs-law were on my screen for a whole frame before you asked what each term was.

The third remark. After 1947 the door marked round stayed shut for almost fifty years. Correctors with many poles were built in Germany, in England by Hardy in 1967, in America by Beck in 1977. Rose’s word for the results is “disappointing”. In the 1980s the attempts stopped.

The principle was wrong?

The principle was right. A corrector has many elements, each must sit where the theory puts it, and nobody could hold them there by hand.

So it was Scherzer’s wall for eleven years. After that it was a wall of screwdrivers.

One observation outlived the failures. In 1979 Beck noticed that the spherical aberration of sextupoles, elements with six poles, has the opposite sign to a round lens’s. Rose published a symmetric corrector made of them in 1981, and again in 1990. Haider began to build it in Heidelberg in 1992. In 1998 Haider, Rose, Uhlemann, Kabius and Urban corrected a microscope of 200 000 volts with it. A year later Krivanek, Dellby and Lupini corrected one of 100 000 volts by a second road, with quadrupoles and octupoles.

What changed between the 1980s and 1998?

The alignment was given to a computer. Now: which condition do we break?

Round. On purpose.

And what is the first step?

The first step is always the same. The state.

Make tea. Tomorrow needs two hands.

Exercises

22.1 glaser-cs-far turns “near 7”. Find where, with find-zero on its slope, (D glaser-cs-far), between 5 and 9. How much lower is the floor there than at 7? Why does Glaser’s table call the minimum flat?

22.2 In your mind. A column of two ScherzerLenses, with a real image between them, is a ScherzerLens. What does the theorem say about the sign of each coefficient, and so about the sign of the whole? A maker of glass lenses cancels the error of one lens with the error of another. Which line of the data definition keeps you from doing the same?

22.3 Where is the image when the coefficient is at its floor? Compute (glaser-image 7 -4000). Where must the specimen sit, relative to the lens?

22.4 In your mind. For each of the three doors we did not take, name the data definition from Chapters 1 to 21 that would have to change first, and say what would be added to it.

23 Two Directions🔗

A ray gets a second direction, and the old functions do not notice.

We are breaking round. The recipe for a piece of optics, from the top. Step 1.

State: what must be written down about an electron to know where it goes next. Since Chapter 1 that has been a height above the axis and a slope.

Above. In which direction is “above”?

Up the page. I drew the axis across the page, and every ray I ever traced stayed in the page.

And an electron that leaves the axis toward you, out of the page?

I never traced one. Not one, in twenty-two chapters.

You did not need to. A round lens bends a ray that is in the page. Which way?

Toward the axis or away from it. Never out of the page: a round lens has no left and no right to prefer. On the turntable of Chapter 11, the ray stays in its plane.

And the electron that left toward you?

Turn the apparatus a quarter turn and it is the first electron. A round lens cannot tell the difference. So one plane through the axis stood for all of them.

That was an invariant, used for twenty-two chapters without a name. Roundness is what let two numbers be enough. Now the field has a left and a right.

Then a ray can be pushed out of its plane. I must know where it is in both directions across the column, and how fast it climbs in both. Four numbers. A tuple of four: (up x y sx sy).

Before you type it. What does ray-x produce for that tuple?

Field 0, which is x. And ray-s produces field 1, which is now y. A height where a slope should be. Every function since Chapter 1 would read the wrong field.

Then keep the shape. A Ray has two fields, a height and a slope.

Let each field be two numbers. A tuple of two tuples.

; An Across is a tuple: (up Number Number)
; interpretation two numbers measured across the
; column: the first along x, the second along y,
; which is a quarter turn from x.
; A Ray2 is a Ray whose fields are Acrosses:
; (up (up x y) (up sx sy))
; interpretation an electron crossing a plane at
; x along one direction and y along the other;
; it climbs sx along x and sy along y for each
; unit it flies along the axis.
; ray2 : Number Number Number Number -> Ray2
(check-expect (ray-x (ray2 3 4 1/2 0)) (up 3 4))
(check-expect (ray-s (ray2 3 4 1/2 0)) (up 1/2 0))
(define (ray2 x y sx sy)
(make-ray (up x y) (up sx sy)))

Where is (ray2 3 4 0 0)?

Level. Three along x and four along y: five from the axis.

And (ray2 0 0 1 0)?

On the axis, climbing along x. That is the old H, lying in the page.

Send a Ray2 across a gap.

I must rewrite drift. Two heights to move, two slopes to keep. I shall call it drift2, and then kick2, and through2, and…

Run the old one first.

On a Ray2? Its signature says Ray.

Run it.

> (drift 2 (ray2 3 4 1/2 0))
(up (up 4 4) (up 1/2 0))
> (drift 'd (ray2 'x 'y 'sx 'sy))
(up (up (+ (* d sx) x) (+ (* d sy) y)) (up sx sy))

It moved x by d times sx and y by d times sy, and it kept both slopes. That is the function I was about to write!

Why did it work? Read its body.

(+ (ray-x r) (* d (ray-s r))). The height, plus d times the slope. The height is now a tuple and the slope is a tuple, and Chapter 0 said + and * go through tuples. drift never asked what a height was. It added one, and it scaled a slope.

And kick?

> (kick 'p (ray2 'x 'y 'sx 'sy))
(up (up x y) (up (+ (* -1 p x) sx) (+ (* -1 p y) sy)))

Both heights kept. Each slope lowered by p times its own height. Toward the axis, from every side.

How many functions have you rewritten?

None.

Are you sure?

through calls drift and kick. trace-ray calls through. slice-lens builds a list for trace-ray. None of them looks inside a height.

> (trace-ray TOY (ray2 0 0 'sx 'sy))
(up (up 0 0) (up (* -1/2 sx) (* -1/2 sy)))
> (drift (/ 1 'p) (kick 'p (ray2 'x 'y 0 0)))
(up (up 0 0) (up (* -1 p x) (* -1 p y)))

The toy of Chapter 2 forms its image for rays that leave the axis in any direction. And a lens of power p brings every level ray, from anywhere in the plane, to one point on the axis.

(define ANY2 (ray2 'x 'y 'sx 'sy))
(check-expect
(ray-x (trace-ray TOY (ray2 0 0 'sx 'sy)))
(up 0 0))
(check-expect
(ray-x (drift (/ 1 'p) (kick 'p (ray2 'x 'y 0 0))))
(up 0 0))

I sat down tonight to write a second ray tracer. I already had it.

Now the condition itself. Chapter 22 wrote: “round: a turn about the axis changes nothing.” That is a purpose statement. Make it a test. Begin with a quarter turn, x toward y. Where does the Across (up 1 0) go?

One along x becomes one along y: (up 0 1). And (up 0 1) goes on round to (up -1 0). So (up x y) goes to (up (- y) x).

; quarter-across : Across -> Across
; a, turned a quarter turn about the axis
(check-expect (quarter-across (up 1 0)) (up 0 1))
(check-expect (quarter-across (up 0 1)) (up -1 0))
(check-expect (quarter-across (up 3 4)) (up -4 3))
(define (quarter-across a)
(up (- (ref a 1)) (ref a 0)))
; quarter : Ray2 -> Ray2
; the ray, turned a quarter turn about the axis
(check-expect (quarter (ray2 1 0 0 2))
(ray2 0 1 -2 0))
(define (quarter r)
(make-ray (quarter-across (ray-x r))
(quarter-across (ray-s r))))

The height turns and the slope turns with it.

Now say “a quarter turn changes nothing” about a lens, as two expressions that must be equal.

Turn the ray and then send it through the lens. Or send it through the lens and then turn what comes out. If the lens cannot tell one direction from another, the two agree.

(check-expect (kick 'p (quarter ANY2))
(quarter (kick 'p ANY2)))
(check-expect (drift 'd (quarter ANY2))
(quarter (drift 'd ANY2)))

They pass. For every power, every gap, every ray.

A quarter turn is one angle. Round means every angle. Where does (up 1 0) go when it is turned through an angle t?

Chapter 12 measured angles so that a half turn is π. One along x, turned through t, is (cos t) along x and (sin t) along y.

And (up 0 1)?

It starts a quarter turn ahead and stays a quarter turn ahead: (quarter-across (up (cos t) (sin t))). Minus the sine along x, and the cosine along y.

And every other Across?

(up x y) is x of the first and y of the second. So it goes to x of where the first went plus y of where the second went. Two arrows tell all. It is Chapter 4 again.

; turn-across : Number Across -> Across
; a, turned through the angle t about the axis
(check-expect (turn-across 0 (up 3 4)) (up 3 4))
(check-within (turn-across (/ pi 2) (up 3 4))
(quarter-across (up 3 4))
1e-12)
(define (turn-across t a)
(+ (* (ref a 0) (up (cos t) (sin t)))
(* (ref a 1) (up (- (sin t)) (cos t)))))
; turn : Number Ray2 -> Ray2
; the ray, turned through the angle t about the axis
(check-within (turn (/ pi 2) (ray2 1 0 0 2))
(quarter (ray2 1 0 0 2))
1e-12)
(define (turn t r)
(make-ray (turn-across t (ray-x r))
(turn-across t (ray-s r))))

Now the test, with nothing chosen. Not even the angle.

(check-expect (kick 'p (turn 't ANY2))
(turn 't (kick 'p ANY2)))
(check-expect (drift 'd (turn 't ANY2))
(turn 't (drift 'd ANY2)))
(check-expect
(trace-ray ANY-COLUMN (turn 't ANY2))
(turn 't (trace-ray ANY-COLUMN ANY2)))

All three pass. A lens is round. A gap is round. A column of gaps and lenses is round. For every angle there is.

The Round Test.

An element is round when turning the ray and then applying the element gives the same ray as applying the element and then turning. For every ray and every angle.

Step 3 of the optics recipe: the special rays. In Chapter 4 two rays told all. How many now?

A Ray2 is four numbers, so four rays: G along x, G along y, H along x, H along y. And each comes out as four numbers. A column that is not round needs a table of sixteen.

And a round one?

Trace G and H along x. The Round Test gives me the other two: they are the same rays a quarter turn on, so they come out a quarter turn on. Four numbers again.

The symmetry of the field is the shape of the answer. What was roundness worth?

Twelve numbers out of sixteen.

Everything you own passes the Round Test. Tomorrow you build something that fails it, on purpose and by name.

Exercises

23.1 In your mind, then check. Where is (drift 4 (ray2 1 0 -1/4 1/2))? This ray reaches x = 0. Is it on the axis there? Design crossing2, which consumes a Ray2 and produces the distance it must fly to reach the axis, or #f if it never does. A ray that passes the axis without meeting it is called skew. Chapter 1 had none. Why not?

23.2 State as a check-expect with a symbolic angle that turning a ray through t and then through minus t gives the ray back. Then show that four quarter turns do nothing, and that two quarter turns are (* -1 r).

23.3 A piece of a glass cylinder focuses along x and leaves y alone. Design cylinder, which consumes a power and a Ray2. Show that it fails the Round Test for a quarter turn: print both sides for the ray (ray2 'x 'y 0 0) and say where they differ.

23.4 Trace the four special rays through TOY and write its table of sixteen numbers. How many of the sixteen are zero? How many different numbers are there among the rest?

24 Poles🔗

One function for an element that is not round, and a law about which functions can be had.

A thin element that is not round. The state is a Ray2. Step 2: planes and purpose.

Thin, so one plane goes in and the same plane comes out. It keeps the height, as kick did. It changes the two slopes, by amounts that depend on where the ray crosses.

Two changes, each depending on x and y. Two functions for every element?

The Seventh Commandment says one. Write one function for the system and derive its law.

One will do. Picture the element as a landscape laid across the column: at each point, a height. That function is the potential of the element. The element pushes an electron downhill: it lowers each slope of the ray by its strength times the slope of the landscape in that direction. You know one thin element already. What is its landscape?

kick lowers sx by p times x and sy by p times y. So I want a landscape whose slope along x is x and along y is y. Chapter 9: the slope of a square is twice the thing. Half of x squared plus half of y squared. A bowl. And Chapter 17 gave me partial for the slope of a function along one slot of a tuple.

; A Potential is a function: Across -> Number
; interpretation the height, at each point across
; the column, of the landscape of a thin element.
; bowl : Across -> Number
; half the square of the distance from the axis
(check-expect (bowl (up 3 4)) 25/2)
(define (bowl a)
(/ (+ (square (ref a 0)) (square (ref a 1))) 2))
; push : Number Potential Ray2 -> Ray2
; the ray after a thin element of strength k
; whose potential is V
(check-expect (push 1/2 bowl (ray2 2 0 0 0))
(ray2 2 0 -1 0))
(check-expect (push 'p bowl ANY2) (kick 'p ANY2))
(define (push k V r)
(let ((at (ray-x r)))
(make-ray
at
(- (ray-s r)
(* k (up (((partial 0) V) at)
(((partial 1) V) at)))))))

The second example passes with nothing chosen. A thin lens is a push down a bowl.

The Law of the Push.

A thin element keeps the height. It lowers the slopes by its strength times the slopes of its potential at that height.

Now the one law of nature this part of the book asks you to trust. Take a landscape. At a point, find the slope of its slope along x, and the slope of its slope along y. Add them. The sum is called the Laplacian of the landscape there.

; laplacian : Potential -> Potential
; at each point: the slope of the slope of V along
; x, plus the slope of the slope of V along y
(check-expect ((laplacian bowl) (up 3 4)) 2)
(define ((laplacian V) a)
(+ (((partial 0) ((partial 0) V)) a)
(((partial 1) ((partial 1) V)) a)))

The Law of Empty Space.

Where nothing changes in time and there is no charge, the potential of a thin element has Laplacian zero at every point.

Which lines of Chapter 22 are those? And what does the law say of your bowl?

Static and empty. And the bowl’s Laplacian is 2, everywhere. My oldest function is against the law!

As a push, it is. No thin element in empty space pushes every ray toward the axis. How does a round magnetic lens focus? Chapter 11.

Not by pushing inward. It pushes the electron around the axis, and the circling in the field pulls it in. The field is used twice, and we watched from a turntable. kick is what that looks like from the turntable. It was never a push down a landscape.

So nothing you build tonight is a round lens. One more landscape that is against the law. Suppose a shop sold thin elements to order. What would you order to cure spherical aberration?

A round landscape whose push grows as the cube of the distance from the axis, like the miss in Chapter 19, with a strength of whichever sign cancels. The slope of a fourth power is a cube.

; round4 : Across -> Number
; a quarter of the fourth power of the distance
; from the axis
(check-expect (round4 (up 3 4)) 625/4)
(check-expect (push 1 round4 (ray2 2 0 0 0))
(ray2 2 0 -8 0))
(check-expect ((laplacian round4) (up 'x 'y))
(* 4 (+ (square 'x) (square 'y))))
(define (round4 a)
(square (bowl a)))

At height 2 it lowers the slope by 8: the cube. But its Laplacian is four times the square of the distance. Zero on the axis and nowhere else. The shop cannot make it.

That is Scherzer’s theorem, seen from the side. Keep round4. The rest of this part of the book is a search for it, made out of things the shop can make. Now mend the bowl.

Its Laplacian is 1 from the x half and 1 from the y half. Subtract the y half instead of adding it: 1 less 1. Half of x squared minus half of y squared. A saddle.

And a legal landscape that goes as the cube?

A third of x cubed has slope of slope twice x. I need minus twice x from the y direction, and x times y squared has that with the sign turned. A third of x cubed, minus x times y squared.

And one that goes as the seventh power?

I refuse to guess a seventh power by hand.

Then build the machine that guesses. Chapter 23 turned an Across: x of (up (cos t) (sin t)) plus y of the same thing a quarter turn on. Put any Across (up a b) where the cosine and sine were.

x of (up a b) plus y of (up (- b) a). That is a rule for multiplying one Across by another, as if each were a single number.

Multiply (up x y) by itself, n times over. n is a natural number, so you know the template.

Two clauses. Multiplied by itself no times, it is the Across that changes nothing when I multiply by it: (up 1 0). Otherwise, (up x y) times the answer for one fewer.

; w-power : Number Number N -> Across
; (up x y) multiplied by itself n times, where
; (up a b) times (up x y) is
; (up (- (* a x) (* b y)) (+ (* b x) (* a y)))
(check-expect (w-power 3 4 0) (up 1 0))
(check-expect (w-power 3 4 1) (up 3 4))
(check-expect (w-power 3 4 2) (up -7 24))
(check-expect (w-power 0 1 2) (up -1 0))
(define (w-power x y n)
(cond ((= n 0) (up 1 0))
(else
(let ((w (w-power x y (- n 1))))
(up (- (* x (ref w 0)) (* y (ref w 1)))
(+ (* x (ref w 1)) (* y (ref w 0))))))))
> (w-power 'x 'y 2)
(up (+ (expt x 2) (* -1 (expt y 2))) (* 2 x y))
> (w-power 'x 'y 3)
(up
(+ (expt x 3) (* -3 x (expt y 2)))
(+ (* 3 (expt x 2) y) (* -1 (expt y 3))))

The first number of the square is twice my saddle. The first number of the cube is three times my cubic. The machine guesses what I guessed!

Then the first number of the nth power, over n, is your landscape of order n.

; pole : N -> Potential
; the potential of a pole-lens of order n: the
; first number of (up x y) to the power n, over n
; assume: n is at least 1
(check-expect ((pole 2) (up 'x 'y))
(/ (- (square 'x) (square 'y)) 2))
(define ((pole n) a)
(/ (ref (w-power (ref a 0) (ref a 1) n) 0) n))
(check-expect ((laplacian (pole 2)) (up 'x 'y)) 0)
(check-expect ((laplacian (pole 3)) (up 'x 'y)) 0)
(check-expect ((laplacian (pole 4)) (up 'x 'y)) 0)
(check-expect ((laplacian (pole 7)) (up 'x 'y)) 0)
> ((pole 7) (up 'x 'y))
(+
(* 1/7 (expt x 7))
(* -3 (expt x 5) (expt y 2))
(* 5 (expt x 3) (expt y 4))
(* -1 x (expt y 6)))

Orders 2, 3, 4 and 7 obey the Law of Empty Space at every point. And there is the seventh power I refused to guess.

Order 2. Walk once round the axis at distance 1 and read the landscape.

> (map (pole 2)
(list (up 1 0) (up 0 1) (up -1 0) (up 0 -1)))
(list 1/2 -1/2 1/2 -1/2)

Hill, valley, hill, valley.

Four poles: a quadrupole. Order 3 has six and is a hexapole. Order 4 has eight and is an octupole. What does the quadrupole do to a ray?

> (push 'p (pole 2) ANY2)
(up (up x y) (up (+ (* -1 p x) sx) (+ (* p y) sy)))

Along x it lowers the slope by p times x, like a lens. Along y it raises the slope by p times y. It focuses one direction and spreads the other.

The Round Test, with a quarter turn.

A quarter turn carries a hill onto a valley. It should fail, and turn the quadrupole into its opposite.

(check-expect
(quarter (push 'p (pole 2) ANY2))
(push (- 'p) (pole 2) (quarter ANY2)))
(check-expect
(quarter (quarter (push 'p (pole 2) ANY2)))
(push 'p (pole 2) (quarter (quarter ANY2))))

A quarter turn reverses it. A half turn changes nothing. The quadrupole is not round. It is half-round.

Where do level rays go after it?

> (drift (/ 1 'p) (push 'p (pole 2) (ray2 'x 'y 0 0)))
(up (up 0 (* 2 y)) (up (* -1 p x) (* p y)))

At the distance 1/p, every x is 0 and every y has doubled. A round beam goes in. A line comes out, twice as long as the beam was wide.

A line focus. Half a lens. Follow one quadrupole with its opposite, a distance d on.

> (push (- 'p) (pole 2)
(drift 'd (push 'p (pole 2) (ray2 'x 'y 0 0))))
(up
(up (+ (* -1 d p x) x) (+ (* d p y) y))
(up (* -1 d (expt p 2) x) (* -1 d (expt p 2) y)))

Both slopes are lowered, by the same amount: d times p squared. One focuses, one spreads, and together they focus both ways!

Why does the focusing win?

Along x the ray is bent in first, so it meets the spreading quadrupole nearer the axis, where the push is weaker. Along y it is spread first, and meets the focusing one further out, where the push is stronger. Each time the second push acts on what the first has moved. And p is squared: swap the two and the pair still focuses.

Remember the phrase “acts on what the first has moved”. It is the whole of Chapter 26. The pair is not a round lens: exercise 24.2 finds two different foci. But two elements that the shop can make have done, between them, what neither can.

Something with four corners. A paratha, cut twice.

Exercises

24.1 The second number of w-power is a legal landscape too. Design skew-pole, like pole but with the second number, and show with symbols that its Laplacian is zero for orders 2 and 3. Then show with check-within, for one ray of your choice, that a push down (skew-pole 2) is a push down (pole 2) turned an eighth of a turn: turn the ray back by π/4, push, and turn it forward again.

24.2 In the crossed pair, take p = 1/2 and d = 1. How far beyond the second quadrupole do level rays cross the axis in x? In y? Trace (ray2 'x 'y 0 0) to each of the two distances and describe what the beam looks like at each.

24.3 Which of these landscapes can the shop make? x times y. x squared. x squared plus y squared. x to the fourth less y to the fourth. x cubed less three x y squared. Predict, then ask laplacian.

24.4 What does (push 'k (pole 1) ANY2) do? How many poles has it? What would you use it for?

25 Three Corners🔗

The hexapole squares. Alone it ruins an image. Twice, it does nothing at all.

Order 3. The special rays: a level ray on the x axis, one unit out. Then two units out.

> (push 1 (pole 3) (ray2 1 0 0 0))
(up (up 1 0) (up -1 0))
> (push 1 (pole 3) (ray2 2 0 0 0))
(up (up 2 0) (up -4 0))

Minus one, and minus four.

I have typed those two answers before.

Where?

Chapter 4. (bad-kick 1 (make-ray 1 0)) was (up 1 -1), and at height 2 it was (up 2 -4). The lens that lowered the slope by the square of the height. You made it up to show what a lens must never do.

> (push 'p (pole 3) (ray2 'x 0 's 0))
(up (up x 0) (up (+ (* -1 p (expt x 2)) s) 0))

On the x axis the hexapole is bad-kick.

I said its name was in Chapter 19.

Chapter 19 had its family name: aberration. Here is the thing itself, and people build it on purpose?

They do. Say what is bad about it, as a test. The Law of Two Rays: the trace of a scaled ray is the scaled trace.

(check-expect
(push 1 (pole 3) (* 2 (ray2 1 0 0 0)))
(* 2 (push 1 (pole 3) (ray2 1 0 0 0))))
FAILED: (push 1 (pole 3) (* 2 (ray2 1 0 0 0)))
actual: (up (up 2 0) (up -4 0))
expected: (up (up 2 0) (up -2 0))

It fails. I doubled the ray and the slope went to four times, not twice.

One ray, one scale. Choose neither.

> (push 'k (pole 3) (* 'c (ray2 'x 0 0 0)))
(up
(up (* c x) 0)
(up (* -1 (expt c 2) k (expt x 2)) 0))
> (* 'c (push 'k (pole 3) (ray2 'x 0 0 0)))
(up (up (* c x) 0) (up (* -1 c k (expt x 2)) 0))

c squared on one side and c on the other. They agree when c is 0 or 1, and for no other scale.

The Eighth Commandment.

An aberration is a departure from the Law of Two Rays. This element is nothing else. It has no power, no focus, no table of four numbers. G and H tell me nothing about a third ray.

Then use a symbol for the whole ray.

> (push 'k (pole 3) ANY2)
(up
(up x y)
(up
(+ (* -1 k (expt x 2)) (* k (expt y 2)) sx)
(+ (* 2 k x y) sy)))

sx is lowered by k times x squared less y squared. sy is raised by k times twice x y. Every term is a product of two heights. A ray on the y axis is pushed along x: sideways, out of its plane. Chapter 23 was written for that ray.

Step 4: the symmetry of the field is the shape of the answer. Walk round the axis and count.

Six poles: hill, valley, hill, valley, hill, valley. A third of a turn carries a hill onto the next hill. So the Round Test should pass for a third of a turn. The sine of a third of a turn is not a fraction, so check-within.

(define THIRD (* 2/3 pi))
(check-within
(turn THIRD (push 1 (pole 3) (ray2 1 2 3 4)))
(push 1 (pole 3) (turn THIRD (ray2 1 2 3 4)))
1e-12)

It passes.

And a half turn? Send in the level ray at −1.

> (push 1 (pole 3) (ray2 -1 0 0 0))
(up (up -1 0) (up -1 0))

The ray at 1 was pushed down, toward the axis. The ray at −1 is pushed down too: away from it. A lens pushes rays a half turn apart opposite ways. The hexapole pushes them the same way. A half turn carries hill onto valley.

Give the half turn a name. You will want it.

; flip : Ray2 -> Ray2
; the ray, turned a half turn about the axis:
; every one of its four numbers reversed
(check-expect (flip (ray2 1 2 3 4)) (ray2 -1 -2 -3 -4))
(check-expect (flip ANY2) (quarter (quarter ANY2)))
(define (flip r) (* -1 r))
(check-expect (flip (push 'k (pole 3) ANY2))
(push (- 'k) (pole 3) (flip ANY2)))

A half turn makes a hexapole into its opposite, as a quarter turn did to the quadrupole.

Keep that last test in view. Now let the hexapole loose on an image. A lens of power 1 brings level rays to a point, 1 beyond it. Press a thin hexapole against the lens, and send in a ring of level rays.

A ring is a Beam, from Chapter 15, and turn will place the rays.

; spoiled : Number Ray2 -> Across
; where a ray lands, 1 beyond a lens of power 1
; with a thin hexapole of strength k against it
(check-expect (spoiled 0 (ray2 'x 'y 0 0)) (up 0 0))
(define (spoiled k r)
(ray-x (drift 1 (kick 1 (push k (pole 3) r)))))
; ring : Number N -> Beam
; n level rays, evenly spaced round a ring of
; radius rr about the axis
(check-expect (car (ring 1/10 6)) (ray2 1/10 0 0 0))
(define (ring rr n)
(build-list
n
(lambda (i)
(turn (* 2 pi (/ i n)) (ray2 rr 0 0 0)))))
> (map (lambda (r) (spoiled 1 r)) (ring 1/10 6))
(list
(up -1/100 0)
(up 0.00499... 0.00866...)
(up 0.00500... -0.00866...)
(up -0.01000... ...)
(up 0.00499... 0.00866...)
(up 0.00499... -0.00866...))

Six rays went in. Three points came out: the fourth ray lands where the first did, the fifth with the second, the sixth with the third. Rays a half turn apart land together. Three corners of a triangle, where there should have been one point.

Each corner is 1/100 from the axis. Compare the disease: a round error of the same strength, at the same ring.

> (ray-x
(drift 1 (kick 1 (push 1 round4 (ray2 1/10 0 0 0)))))
(up -1/1000 0)

A thousandth. The round error goes as the cube of the ring and the hexapole as the square. For a small ring a square is larger than a cube. The cure does ten times the harm of the disease.

So one hexapole is worse than none. Now the test you were told to keep in view. Suppose that, between two identical hexapoles, every ray were given a half turn.

The second hexapole would meet each ray on the opposite side of the axis, and push it the same way as the first did. But the ray’s slope has been reversed in between, so “the same way” is now against the first push.

It would undo it. But I cannot turn a beam half round the axis.

You have done so in every chapter since the second. What is the magnification of the toy?

−2. Upside down! An image with a negative magnification is the object given a half turn, and resized. I need a magnification of exactly −1, and the slopes reversed as well as the heights.

Exercise 3.2 called a pair of lenses with a shared focus a telescope. Take two equal lenses of focal length f, with f before, 2f between, and f after.

; unit-telescope : Number -> ModuleStack
; two lenses of focal length f: a gap f, a lens,
; a gap 2f, a lens, a gap f
(check-expect (stack-length (unit-telescope 3)) 12)
(define (unit-telescope f)
(list (make-gap f) (make-thin (/ 1 f))
(make-gap (* 2 f))
(make-thin (/ 1 f)) (make-gap f)))
(check-expect (stack->transfer (unit-telescope 'f))
(make-transfer -1 0 0 -1))
(check-expect (trace-ray (unit-telescope 'f) ANY2)
(flip ANY2))

Its table is −1, 0, 0, −1, for every f. On a Ray2 it is flip, exactly. Four focal lengths of column, to do what (* -1 r) does in none.

On the bench its two lenses are round magnetic ones with opposite currents, so that the turn of Chapter 14 cancels. Now put a hexapole at each end.

(check-expect
(push 'k (pole 3)
(trace-ray (unit-telescope 'f)
(push 'k (pole 3) ANY2)))
(flip ANY2))
(check-expect
(push 'k (pole 3) (flip (push 'k (pole 3) ANY2)))
(flip ANY2))

Both pass. Hexapole, telescope, hexapole is the telescope alone. There is no k left in it!

For which strengths, and which rays?

Every strength. Every ray. The second hexapole undoes the first, and what is left is the half turn.

The Law of Two Wrongs.

Two identical thin hexapoles, with a telescope of magnification −1 between them, are that telescope and nothing more.

What have you built tonight?

Two hexapoles, two lenses and three gaps, which together do what the lenses and gaps do without the hexapoles. Nothing.

Are you sure?

Exactly nothing. With a check-expect.

Tomorrow the hexapoles get length. A thin hexapole is as much a fiction as a thin lens.

And will two long wrongs also make nothing?

Sleep on it.

Exercises

25.1 Move the screen. Land twelve rays of the ring of radius 1/10 a distance 8/10 beyond the lens of spoiled instead of 1, with k = 1. List the twelve distances from the axis. Which turn about the axis carries the figure onto itself? How many corners has it?

25.2 A sixth of a turn carries each hill of the hexapole onto a valley. Show with check-within, for one ray, that turning a hexapole a sixth of a turn makes it its opposite, in the manner of the test for flip.

25.3 Three wrong designs. Predict what each is equal to, then check with symbols. Two identical hexapoles with no telescope between them. Two hexapoles with the telescope, the second with its current reversed. Two identical quadrupoles with the telescope. Which orders of pole cancel in identical pairs across a flip?

25.4 In your mind, then check. Three identical thin hexapoles, with a flip between the first and second and another between the second and third. What is left?

26 The Kick of a Kick🔗

Give the hexapoles length, and nothing becomes the one thing no round lens can do.

A real hexapole has length. Which chapter is that?

Chapter 7. Slices: half a gap, a thin push, half a gap. What stays the same from slice to slice is the strength per unit length, so a slice of length h pushes with k times h. The ray is what the slices hand on: an accumulator, as in flow.

; thick : Number Number N Ray2 -> Ray2
; the ray after a hexapole of length len and of
; strength k per unit length, cut into n slices
(check-expect (thick 0 'L 3 ANY2) (drift 'L ANY2))
(define (thick k len n r)
(define h (/ len n))
; Ray2 -> Ray2
; one slice: half a gap, the push, half a gap
(define (slice r)
(drift (/ h 2)
(push (* k h) (pole 3) (drift (/ h 2) r))))
; N Ray2 -> Ray2
; accumulator r: the ray with `left` slices to go
(define (go left r)
(cond ((= left 0) r)
(else (go (- left 1) (slice r)))))
(go n r))

A hexapole switched off is a gap.

Now the Law of Two Wrongs, with thick hexapoles. A thin one sat at one plane. A thick one fills a stretch. Rose is firm about where the telescope runs: from the middle of the first hexapole to the middle of the second.

But by the time the ray reaches the telescope it has left the far face. The middle is half a length behind it.

What does (drift -1/2 r) produce?

The ray as it was half a unit back, had it flown straight. A gap of negative length. It does not move the electron. It moves the plane at which I describe it.

Then write the corrector.

Through the first hexapole. Back half a length, to its middle. Flip. Back half a length again, so that the second hexapole’s middle is where the flip left off. Through the second, and back to its middle.

; corrector : Number Number N Ray2 -> Ray2
; r is a ray at the front face of the first of
; two hexapoles (length len, strength k per unit
; length, n slices each) whose middles a
; telescope of magnification -1 images on each
; other; the result is that ray, referred to
; the middle of the second
(check-expect (corrector 'k 'L 1 (ray2 'x 'y 0 0))
(flip (ray2 'x 'y 0 0)))
(define (corrector k len n r)
(let* ((back (- (/ len 2)))
(a (drift back (thick k len n r)))
(b (drift back (flip a)))
(c (drift back (thick k len n b))))
c))

With one slice each, the answer is the flip and nothing more. Two long wrongs make nothing.

One slice is a thin hexapole at its own middle. Two slices.

> (ref (ray-s (corrector 'k 'L 2 (ray2 'x 0 0 0))) 0)
(+
...
(* 1/16 (expt L 7) (expt k 4) (expt x 5))
(* -1/2 (expt L 3) (expt k 2) (expt x 3)))

Thirteen terms, and I have cut eleven. It is not nothing! The lowest term is minus a half, times k squared, times L cubed, times the cube of the height.

You want one number out of thirteen terms: what multiplies the cube. In Chapter 20 you measured a coefficient with D.

The slope of the cube is three squares. The slope of that is six times the thing. The slope of that is 6. So the slope of the slope of the slope at 0, over 6, is the number on the cube.

; cubic-part : [Number -> Number] -> Number
; the number that multiplies the cube in f near 0
(check-expect (cubic-part cube) 1)
(check-expect
(cubic-part
(lambda (x) (+ (* 5 x) (* 7 (cube x)) (expt x 5))))
7)
(define (cubic-part f)
(/ ((D (D (D f))) 0) 6))
; corrector-c : Number Number N -> Number
; the cubic part of the slope with which a level
; ray leaves a corrector, per cube of the height
; at which it went in
(check-expect (corrector-c 'k 'L 2)
(* -1/2 (square 'k) (cube 'L)))
(define (corrector-c k len n)
(cubic-part
(lambda (x)
(ref (ray-s (corrector k len n (ray2 x 0 0 0)))
0))))

Unit strength, unit length. Double the slices, and keep the numbers exact.

> (map (lambda (n) (corrector-c 1 1 n)) (list 1 2 4 8))
(list 0 -1/2 -5/8 -21/32)

The Fifth Commandment. Before sixteen slices: what must it be?

The push sits at the middle of each slice, as in Chapter 7, so the order is 2: each doubling should quarter the step. The steps were 1/2, then 1/8, then 1/32. They quarter. The next is 1/128. So: minus 85/128.

> (corrector-c 1 1 16)
-85/128

And if it goes on that way for ever?

The steps still to come add up to a third of the last one. A third of 1/128 is 1/384. And 85/128 is 255/384. One more makes 256/384.

Two thirds. Exactly.

(check-expect
(map (lambda (n) (corrector-c 1 1 n))
(list 1 2 3 4 8 16))
(map (lambda (n) (* -2/3 (- 1 (/ 1 (square n)))))
(list 1 2 3 4 8 16)))

Rose’s textbook reaches that number with integrals. In his letters it is minus 6, times the square of his strength, times the cube of the length, and his strength is a third of our k.

Six ninths. His integral and my slices agree on two thirds.

Now the sign. The ray went in at height x, above the axis. Where is it, and which way does the cubic part send it?

After the flip it is at −x, below the axis. Its slope is negative. Below and sinking: away from the axis, and growing as the cube of the height. A round lens’s error pushed outer rays toward the axis: (push c round4 r) with c positive. This has the other sign. Is it round? I have only tried rays on the x axis.

Then try one on neither axis, against round4 itself.

(check-within
(corrector 1. 1. 64 (ray2 .006 .008 0 0))
(push -2/3 round4 (flip (ray2 .006 .008 0 0)))
1e-9)

It passes. To a gentle ray, two long hexapoles and a telescope are a flip and a push down round4, with strength minus two thirds.

round4. The landscape the shop cannot make!

The Law of the Kick of a Kick.

Two hexapoles of length L and strength k per unit length, the middle of one imaged on the middle of the other with magnification −1, give a gentle ray a half turn and a round cubic push away from the axis, of strength two thirds of k squared times L cubed.

One slice gave nothing and two gave a half. What can two slices do that one cannot?

In two, the first push changes the slope, the gap turns that into a change of height, and the second push acts on a ray the first has moved. The extra is k times what k did. The kick of a kick.

Why does the telescope not cancel that as well?

The plain push is a square: the same at x and at −x. That is what the pair cancels. The kick of a kick is a cube, and a cube reverses with x, as everything a lens does. The two hexapoles add: a third each. And k is squared, so the push is outward whichever way the current runs. A round lens uses its field twice and can only focus. This uses its field twice and can only do the opposite.

Now use it. A round lens with its error is a thin lens followed by a push down round4. Chapter 21’s Objective is data. This is a function.

; objective : Number Number Ray2 -> Ray2
; the ray after a thin lens of power p that has
; a round cubic error of strength c
(check-expect (objective 'p 0 ANY2) (kick 'p ANY2))
(define (objective p c r)
(push c round4 (kick p r)))
; k-for : Number Number -> Number
; the strength per unit length at which two
; hexapoles of length len cancel a round cubic
; error of strength c
(check-expect (k-for 2/3 1) 1)
(define (k-for c len)
(sqrt (/ (* 3/2 c) (cube len))))
; off-axis : Across -> Number
; the distance of a point from the axis
(check-expect (off-axis (up 3 4)) 5)
(define (off-axis a)
(sqrt (+ (square (ref a 0)) (square (ref a 1)))))
; lands : Number Ray2 -> Across
; where a level ray lands, 1 beyond an objective
; of power 1 and error 1, after a corrector of
; length 1 and strength k in 64 slices
(define (lands k r)
(ray-x
(drift 1 (objective 1 1 (corrector k 1. 64 r)))))
; widest : Number Number -> Number
; the greatest distance from the axis at which
; any of twelve level rays lands, sent in round
; a ring of radius rr
(define (widest k rr)
(apply max
(map (lambda (r) (off-axis (lands k r)))
(ring rr 12))))

Hexapoles off, then on.

> (map (lambda (rr) (widest 0 rr))
(list .01 .02 .05 .1))
(list 9.99...e-7 8.00...e-6 0.000125... 0.00100...)
> (map (lambda (rr) (widest (k-for 1 1) rr))
(list .01 .02 .05 .1))
(list 2.81...e-10 3.15...e-9 1.47...e-7 4.00...e-6)

Switched off: the cube of the ring, as Scherzer requires. Switched on: at the ring of one tenth the spot is 250 times smaller.

Scherzer’s Law said: cannot be zero, cannot be negative.

For a ScherzerLens. This is static, empty and one-way, and it is not round. I broke one assumption, on purpose and by name, and the cube has gone.

Has everything gone? Look round the ring of one tenth.

> (map (lambda (r) (off-axis (lands (k-for 1 1) r)))
(ring .1 6))
(list
4.25...e-7 1.13...e-6 4.25...e-7
1.13...e-6 4.25...e-7 1.13...e-6)

Not round. Two numbers, said three times: the third of a turn, which is all a hexapole ever promised. And what is left grows faster than a cube: eleven-fold from .01 to .02, where a cube would be eight.

Correction is a trade: one large round error for smaller ones of higher order and other shapes. Rose lists what remains: a spherical aberration of the fifth order, a coma of the objective, and whatever the builder’s hands introduce. Move a hexapole sideways by e. What does the beam meet?

The same landscape, with its centre at e.

; shifted : Potential Number -> Potential
; the landscape V, moved a distance e along x
(check-expect ((shifted bowl 3) (up 3 0)) 0)
(define ((shifted V e) a)
(V (- a (up e 0))))
(check-expect
(push 'k (shifted (pole 3) 'e) ANY2)
(push 'k (pole 3)
(push (* -2 'k 'e) (pole 2)
(push (* 'k 'e 'e) (pole 1) ANY2))))

A misplaced hexapole is a hexapole, a quadrupole of strength 2ke, and an element of order 1 that pushes every ray alike. Order 3 has leaked down into orders 2 and 1.

And a stray quadrupole draws a point out into a line. That is why this took fifty years. Rose: the fields must hold steady to better than one part in ten million, the magnification of −1 cannot be met by machining, and the alignment is done by a computer.

So the door marked round was open from 1947. What was missing was a way to stand still in it.

Tea. You have earned the strong kind.

Exercises

26.1 Measure the cubic part along y: send in (ray2 0 y 0 0) and take the y slope, with symbols for k and L and two slices. Then send in (ray2 (* 3/5 t) (* 4/5 t) 0 0) and take both slopes. What do the answers say about the word “round” in the law?

26.2 Rose warns against running the telescope from face to face. Design face-to-face, which is corrector without the three negative gaps. With one slice and symbols, what has survived in the height? Tabulate its cubic part for 1, 2, 4 and 8 slices, exactly. What does it close in on, and what is wrong with the sign?

26.3 The 64 slices of lands are worth a little less than two thirds. Compute (+ 1 (corrector-c (k-for 1 1) 1 64)). How much of the spot at the ring of one hundredth is that leftover cube? Divide k by the root of one less 1/64², tabulate widest again, and say what power of the ring the remainder follows now.

27 Four Corners🔗

The other road: an element that cannot correct, and a beam reshaped until it can.

Order 4. The special rays, on the x axis first.

> (push 1 (pole 4) (ray2 2 0 0 0))
(up (up 2 0) (up -8 0))
> (push 'o (pole 4) (ray2 'x 0 0 0))
(up (up x 0) (up (* -1 o (expt x 3)) 0))
> (push 'c round4 (ray2 'x 0 0 0))
(up (up x 0) (up (* -1 c (expt x 3)) 0))

A cube. The same cube as round4 gives. On the x axis the octupole is round4.

But (pole 4) is legal: its Laplacian is zero, by a test in Chapter 24. And its strength may have either sign. Then last night was unnecessary! One octupole of negative strength against the objective, and the cube is gone.

You have tested one axis. Try a ray on neither.

> (push 1 (pole 4) (ray2 1 1 0 0))
(up (up 1 1) (up 2 2))
> (push 1 round4 (ray2 1 1 0 0))
(up (up 1 1) (up -2 -2))

Opposite. On the diagonal, round4 pushes toward the axis and the octupole pushes away. An octupole of negative strength would cure the error along x and y, and make it worse along the diagonals.

Count the poles, and say which turns it passes.

Eight poles: four hills and four valleys. A quarter turn carries hill to hill. An eighth of a turn carries hill to valley, and should make the octupole its opposite.

(check-expect (quarter (push 'o (pole 4) ANY2))
(push 'o (pole 4) (quarter ANY2)))
(check-within
(turn (/ pi 4) (push 1 (pole 4) (ray2 1 2 3 4)))
(push -1 (pole 4) (turn (/ pi 4) (ray2 1 2 3 4)))
1e-12)

Both pass. Four corners where it helps and four where it harms.

How much of the octupole is round? You need a definition before a number. What is true of a round landscape, all the way round a ring about the axis?

It has one height. A landscape that is not round goes up and down as I walk the ring. Its round part is what is left when the ups and downs are evened out: the average round the ring. And Chapter 14 adds up a function.

; ring-mean : Potential -> Number
; the average height of V round the ring of
; radius 1 about the axis
(check-within (ring-mean bowl) 1/2 1e-10)
(check-within (ring-mean round4) 1/4 1e-10)
(define (ring-mean V)
(/ (definite-integral
(lambda (t) (V (up (cos t) (sin t))))
0 (* 2 pi) 1e-12)
(* 2 pi)))
(check-within (ring-mean (pole 4)) 0 1e-10)

The octupole averages to nothing. Is that all?

That is all. The hills and the valleys cancel. It can move the error round the ring and cannot take any away. Your colleagues have that as a theorem, and its name is octupole_alone_cannot_correct. Now make the measurement a formula. Average x⁴ round the ring, and x²y².

> (ring-mean (lambda (a) (expt (ref a 0) 4)))
0.37499999999999994
> (ring-mean
(lambda (a) (* (square (ref a 0)) (square (ref a 1)))))
0.12500000000000003

They smell like fractions. Three eighths and one eighth. And y⁴ is x⁴ a quarter turn on, so three eighths again.

And x² + y², squared, averages to what?

It is 1 everywhere on the ring, so 1. Then the round part of such a quartic, counted in units of that one, is three eighths of the outer two numbers plus an eighth of the middle one.

; iso : Number Number Number -> Number
; the round part of c40 x^4 + c22 x^2 y^2 + c04 y^4:
; how many times (x^2 + y^2)^2 it holds, on
; average round a ring
(check-expect (iso 1 2 1) 1)
(check-expect (iso 1 -6 1) 0)
(define (iso c40 c22 c04)
(+ (* 3/8 (+ c40 c04)) (* 1/8 c22)))

1, 2, 1 is x² + y² squared, and it holds itself once. 1, −6, 1 is four times (pole 4). Nothing.

Your colleagues call that formula iso_quartic. So the octupole offers a beam no round part. Read that sentence for its assumption. Which beam?

One that meets the octupole as it will meet the objective: a ray bound for the point x, y of the objective crosses the octupole at x, y.

Who promised that?

Nobody. A quadrupole squeezes a beam along x and spreads it along y. After one, a ray bound for x, y is at a times x and b times y, for some a and b that the quadrupoles set.

Then say what landscape such a beam meets.

; stretched : Potential Number Number -> Potential
; the landscape V as it is met by a beam that
; has been stretched a-fold along x and b-fold
; along y
(check-expect ((stretched bowl 2 3) (up 1 1)) 13/2)
(define ((stretched V a b) at)
(V (up (* a (ref at 0)) (* b (ref at 1)))))
> (* 4 ((stretched (pole 4) 'a 'b) (up 'x 'y)))
(+
(* (expt a 4) (expt x 4))
(* -6 (expt a 2) (expt b 2) (expt x 2) (expt y 2))
(* (expt b 4) (expt y 4)))

The three numbers are a⁴, −6a²b² and b⁴. No longer 1, −6, 1.

Its round part.

> (iso (expt 'a 4)
(* -6 (square 'a) (square 'b))
(expt 'b 4))
(+
(* 3/8 (expt a 4))
(* -3/4 (expt a 2) (expt b 2))
(* 3/8 (expt b 4)))

Three eighths of a⁴ − 2a²b² + b⁴. That is a square!

(check-expect
(iso (expt 'a 4)
(* -6 (square 'a) (square 'b))
(expt 'b 4))
(* 3/8 (square (- (square 'a) (square 'b)))))

Zero when a equals b, which is the round beam and the theorem. Greater than zero for every other beam.

Greater than zero. A sum of squares again?

One square. But it is multiplied by the octupole’s strength, and I choose the sign of that. A stretched beam finds a round part in an octupole, of whichever sign I like.

The Law of the Stretched Beam.

An octupole met by a round beam has no round part. Met by a beam stretched a-fold one way and b-fold the other, its round part is three eighths of the square of a² − b², times its strength, and the strength may have either sign.

One thing should trouble you. (pole 4) has Laplacian zero. Its round part, for a stretched beam, is a multiple of round4. And round4 is against the law.

> ((laplacian (stretched (pole 4) 2 1)) (up 'x 'y))
(+ (* 36 (expt x 2)) (* -9 (expt y 2)))

Not zero. The octupole obeys the law where it stands. The beam does not meet it as it stands. The law binds the element. It says nothing about the shape in which the beam arrives.

That is the whole trick. Be clear which part of it you have built. You have computed what a stretched beam meets. That the image answers in proportion, your colleagues have proved: in a column of quadrupoles and octupoles that forms a sharp image, the round cubic coefficient of the image is a straight line in the octupole’s strength. If the line is not level, some strength makes the coefficient zero, and another makes it negative.

And the line is level when the octupole finds no round part: when a equals b. No quadrupoles, no slope.

The stretched octupole is not all round. What else does it hold?

Whatever iso evened out: parts with corners. They average to nothing round the ring and still smear the image.

Rose says the least that will do is three octupoles. Two sit where the quadrupoles have drawn the beam out into a line: one line along x, one along y. The third sits where the beam is round. Take the lines to be A long for a beam 1 wide.

On the first line a is A and b is 0. On the second, the other way round. Give both the strength o. Between them they hold o A⁴ over 4, times x⁴ plus y⁴, and that has four corners in it. The third, where the beam is round, must take out the corners and nothing else.

(check-expect
(+ (* 'o ((stretched (pole 4) 'A 0) (up 'x 'y)))
(* 'o ((stretched (pole 4) 0 'A) (up 'x 'y)))
(* -1/4 'o (expt 'A 4) ((pole 4) (up 'x 'y))))
(* 3/4 'o (expt 'A 4) (round4 (up 'x 'y))))

It passes. Three octupoles, each of them legal, and the beam meets round4: all of it round, with a strength of either sign. The landscape the shop could not make, made of three it can.

Two roads, then. On the hexapole road the round part goes as k squared. On this one?

As o itself. A square has one sign, and last night it was the useful one. A straight line has both.

Rose notes that hexapoles ask less of their power supplies than a round lens does, while the quadrupoles of this road must be held extremely steady. Why would that be?

A quadrupole is half a lens. If its current drifts, the focus moves. A hexapole’s first effect is a square, and the pair cancels that.

But this road reaches one thing the other cannot. Scherzer’s sum for colour is positive, and Rose adds: unless the column holds an electric quadrupole. Quadrupoles of crossed electric and magnetic fields, set at the line images, can make faster electrons focus sooner.

Chapter 20 ended with a filter that throws electrons away. Here is a cure that keeps them.

It is the older road. Scherzer proposed correctors that are not round, and Glaser’s book of 1952 records that Seeliger had tried them. Krivanek, Dellby and Lupini made this one work in 1999. Four years earlier Zach and Haider had built a corrector of quadrupoles for a scanning electron microscope: the kind your colleagues study. Their corpus has the theorem under a blunt name.

scherzer_fails_without_symmetry. Chapter 19 said: cannot be zero, cannot be negative. Tonight both are on the menu.

Before you order. In Chapter 21, at the best angle, the four blurs were .71, .35, .88 and 1.08 nanometres. Which was spherical?

The .35. The smallest of the four.

Six evenings, to remove the smallest number on the list?

At that angle. How was the angle chosen?

With Cs in the budget. Take Cs out and the best angle is another angle. A wider one. And then diffraction falls, and colour rises…

I cannot do that in my head.

Nobody can. What does the budget of Chapter 21 become when its spherical term can be set to nothing, and would your colleagues’ column be the better for it? That is Chapter 28: The Corrected Probe.

probe consumes an Optics. I shall have to decide what a corrected Optics is.

Data first.

Tea, and whatever has four corners.

Exercises

27.1 Compute ring-mean of (pole n) for n from 1 to 6. Then explain all six answers at once, without a sum, using the turn that makes each pole its opposite.

27.2 Find 3/8 and 1/8 with no sum at all. Call the average of x⁴ round the ring m and the average of x²y² w. One fact comes from x² + y² squared, which is 1 on the ring. The other comes from the octupole, which an eighth of a turn reverses. Solve for m and w.

27.3 A quadrupole has no round part either. Work out (ring-mean (stretched (pole 2) a b)) from the averages of x² and of y², then check with numbers. Which round landscape of Chapter 24 does a stretched quadrupole hold, and for which beams? Chapter 24 built this without knowing it. Where?

27.4 Leave out the third octupole. State with symbols what the two on the lines hold between them, as so much round4 and so much (pole 4). Then put a single octupole on one line: what does (iso (expt 'A 4) 0 0) say is round, and what is wrong with the rest?

28 The Corrected Probe🔗

What a corrector buys, and for whom.

You have a corrector. Chapter 26 built one from hexapoles, Chapter 27 another from quadrupoles and octupoles. Each removes the round cubic error of an objective. In Chapter 21 that error had a column of its own in the budget. Which?

sph. Half of Cs times the cube of the arrival slope.

Design the function that says what a perfect corrector does to an Optics.

It consumes an Optics and produces one. The magnification stays. The chromatic coefficient stays: nothing in the last six chapters touched colour. Cs becomes zero.

; corrected : Optics -> Optics
; the same lens, with its spherical aberration
; removed and nothing else changed
(check-expect (corrected (make-optics -1/4 2 3))
(make-optics -1/4 0 3))
(define (corrected opt)
(make-optics (optics-m opt) 0 (optics-cc opt)))

One example. Is one enough?

An Optics is a structure with no cases, so the function has no cond. One example with three different numbers in it shows which field goes where.

Before you run anything. The needle and the objective of Chapter 21 made a probe of 1.6 nanometres. The corrector deletes one of four blurs. What do you expect?

A quarter off?

No. The blurs add as squares, so the largest ones rule. At the best angle the budget was 0.71, 0.35, 0.88, 1.08. The spherical term was the smallest. I expect very little.

Run it.

I want the budget at the best angle, and the best angle will move.

; best-probe : Source Optics -> [List-of Number]
; the budget, in nanometres, at the arrival slope
; that makes the probe smallest
(check-expect (best-probe NEEDLE OPT)
(budget (probe NEEDLE OPT
(best-angle NEEDLE OPT))))
(define (best-probe src opt)
(budget (probe src opt (best-angle src opt))))
> (best-probe NEEDLE OPT)
(list 0.71 0.35 0.88 1.08 1.6)
> (best-probe NEEDLE (corrected OPT))
(list 0.71 0 0.96 0.98 1.55)

From 1.60 to 1.55.

Three parts in a hundred, for a device the world needed fifty years to build. Read the second line and say why.

With sph gone the best angle opened a little: nothing cubic punished it. Diffraction fell from 1.08 to 0.98. But the chromatic blur grows with the angle, and it rose from 0.88 to 0.96. Colour took the place the cube left.

Scherzer proved two sums of squares. We broke one.

And the other was waiting behind it.

The Law of the Budget.

A correction is worth what the corrected term was worth in the sum. Read the budget before you build.

Then find a machine in which the cube is a large term. Which numbers in a Source make the other three blurs small?

geo is the size of the source: make it finer. chr is the energy spread: make it narrower. dif is the wavelength: make the electrons faster.

Make one. Two nanometres across, three tenths of a volt, two hundred thousand volts.

; a fine, cold source of fast electrons
(define SHARP (make-source 2e-9 .3 200000))
> (best-probe SHARP OPT)
(list 0.07 0.17 0.02 0.28 0.34)
> (best-probe SHARP (corrected OPT))
(list 0.07 0 0.07 0.07 0.13)
> (best-angle SHARP OPT)
0.00537...
> (best-angle SHARP (corrected OPT))
0.02041...

Now the cube is the second-largest term. Removing it lets the angle open four times wider, and the probe falls from 0.34 nanometres to 0.13.

By what factor?

2.6. And 0.13 nanometres is about the distance between two atoms in a crystal.

That is the instrument the corrector was invented for: a fine source, fast electrons, a thin specimen. Now a machine of the other kind. Your colleagues have studied a real column with a tungsten hairpin for a source. At ten thousand volts their table gives it a magnification of 7.88e-5 on a source fifty micrometres across, Cs of 76.6 millimetres, Cc of 20.3, and a half-angle of 2.7 thousandths. Whose conventions is their table in?

Not Chapter 21’s. I have read it. Their diffraction disc is 1.22 wavelengths over the half-angle, and their chromatic disc is Cc times the half-angle times the energy spread over the energy. So I must not reuse probe. Two budgets with one name and two meanings is how a factor of two gets into a meeting.

Then the first step again.

A data definition, with every convention in its interpretation.

; A Row is
; (make-row Number Number Number Number
; Number Number Number)
; interpretation (make-row v m d0 cs cc de alpha) is
; one line of the column study: beam voltage v in
; volts; magnification m; source diameter d0, and
; coefficients cs and cc at the image, in metres;
; energy spread de in volts; half-angle alpha at
; the image.
(define-struct row (v m d0 cs cc de alpha))
(define TUNGSTEN
(make-row 10000 7.88e-5 50e-6 .0766 .0203 1 .0027))
; row-budget : Row -> [List-of Number]
; the study's four discs and the root of the sum of
; their squares, in nanometres: source, spherical,
; chromatic, diffraction, total
(define (row-budget r)
(let* ((a (row-alpha r))
(four
(list (* (abs (row-m r)) (row-d0 r))
(* 1/2 (row-cs r) (cube a))
(* (row-cc r) a (/ (row-de r) (row-v r)))
(/ (* 1.22 (wavelength (row-v r))) a))))
(map in-nm
(append four
(list (sqrt (foldl + 0
(map square four))))))))
> (row-budget TUNGSTEN)
(list 3.94 0.75 5.48 5.51 8.75)

Their table says 3.9, 0.7, 5.5, 5.6 and 8.8. It is their row.

Which step of the recipe was that?

The sixth. Their table was the example, and it came before the function.

Correct the row.

; row-corrected : Row -> Row
; the same line with the spherical aberration removed
(define (row-corrected r)
(make-row (row-v r) (row-m r) (row-d0 r) 0
(row-cc r) (row-de r) (row-alpha r)))
> (row-budget (row-corrected TUNGSTEN))
(list 3.94 0 5.48 5.51 8.72)

8.75 to 8.72.

Three hundredths of a nanometre. The coefficient of that lens is 77 millimetres. In Chapter 21 two millimetres seemed large. How can 77 not matter?

Because it is multiplied by the cube of 2.7 thousandths. The aperture keeps the beam so narrow that the cube never bites. And the aperture is that narrow because of the other two terms: 5.48 and 5.51. They are balanced already.

That is an assertion. Open the aperture and look.

; row-at : Row Number -> Row
; the same line seen through another aperture
(define (row-at r a)
(make-row (row-v r) (row-m r) (row-d0 r) (row-cs r)
(row-cc r) (row-de r) a))
> (row-budget (row-at TUNGSTEN .002))
(list 3.94 0.31 4.06 7.44 9.36)
> (row-budget (row-at (row-corrected TUNGSTEN) .004))
(list 3.94 0 8.12 3.72 9.76)
> (row-budget (row-at (row-corrected TUNGSTEN) .006))
(list 3.94 0 12.18 2.48 13.04)

Narrower, and diffraction takes over: 9.36. Wider and corrected, and colour takes over: 9.76, then 13. Whoever chose 2.7 thousandths knew where the two terms cross.

So what limits that machine?

Colour and the wave, in equal parts, and behind them the size of the source. A hot hairpin a volt wide, at ten thousand volts. To make its probe smaller: a colder, finer source, or faster electrons, or a smaller Cc. A corrector for Cs is the one thing that would not help.

And you know it from one line of a budget.

Before building anything.

One more reading. In the corrected sharp instrument, what is left?

0.07, 0, 0.07, 0.07. Source, colour and the wave, in equal parts. To halve it, all three must fall together.

And colour needs a corrector of its own, which we have not built. A hexapole does not touch the first-order rays, and Scherzer’s second sum stays positive until an electric quadrupole joins the magnetic ones. That corrector exists. It is a harder machine than the one in Chapter 26, and it asks more of the power supplies: for a probe under a tenth of a nanometre, fields steady to one part in ten million.

Each sum of squares that is broken uncovers the next thing that was hiding behind it.

That is the whole history of the microscope.

Is that all?

That is all.

The kettle has been on since Chapter 22.

Exercises

28.1 Chapter 26’s k-for consumes the round cubic error c of a thin lens. A real lens is described by its coefficient Cs and its focal length f, and it errs toward the axis by Cs over the fourth power of f, times the cube of the height. Design k-for-lens, which consumes Cs, f and the length of each hexapole and produces the strength that cancels. Write one of its examples with symbols only, so that it is the purpose statement, run.

28.2 For a corrected lens only two terms of the total depend on the angle, one growing and one shrinking. Find the best angle on paper, as the angle at which they are equal, and design corrected-best-angle. Compare it with best-angle on (corrected OPT). How close is close enough, given how ANGLES was built?

28.3 Design dominant, which consumes a budget and produces the name of its largest blur: one of 'source, 'spherical, 'chromatic, 'diffraction. That is an enumeration; write its data definition first. What should it say of the corrected sharp instrument?

28.4 row-at and row-corrected are one template filled in twice: each copies six fields and changes one. Abstract them, and say which recipe from HtDP you used.

29 The Wishlist🔗

What you have, what you were told, and what to build next.

When you design a large program, and a function you need does not exist yet, what do you do?

I write its signature and purpose on the wishlist, pretend it exists, and carry on.

This book did that with nature. Four times I said “take this on trust”. Each was an entry on a wishlist: something to be derived later. Read them back to me.

  1. A magnetic field pushes a moving electron sideways, across its motion and across the field. (Chapter 11.)

  2. In a round magnetic lens, seen from a turntable turning at the rate k, the ray obeys the lens law with stiffness k squared. (Chapters 11 and 14.)

  3. The law of motion can be derived from one function by Hamilton’s recipe, and for a round magnetic lens that function is true-H. (Chapters 17 and 18.)

  4. An electron is a wave, with a wavelength of Planck’s constant over its momentum. (Chapter 21.)

The fourth belongs to quantum mechanics, and is another journey. The first three are one fact seen from three distances, and SICM derives them in this order. You have been using its tools all along, so you can read it as a user, not a tourist.

To discharge

Read in SICM

You already use

Why Hamilton’s recipe is right

1.1–1.5 (the action, Lagrange’s equations); 3.1 (Hamilton’s equations)

partial, Hamiltonian->state-derivative

Where the sideways push and true-H come from

1.6 (how to find a Lagrangian); 3.1 (the Legendre transform)

true-H

Why z may be used as the clock

1.7 (evolution of state); 5.4

state-advancer, (up z x p)

Why a round lens must turn the image

1.8 (conserved quantities, Noether); 3.4

glaser-turn

Why area on the chart is conserved

3.8 (Liouville); 5.2 (symplectic maps)

determinant, area

Why changing the description solved the lens

5.1 (canonical transformations)

gaze, apparent

Why Cs is a sum along the paraxial ray

5.9–5.11 (Lie series); chapter 6 (perturbation theory)

cs-law

The section numbers are those of the second edition, which is free to read on the publisher’s site. The copy on your desk is the first; its chapters are the same and its sections nearly so.

SICM writes its states as (up t q p), with the time first. Ours were (up z x p).

The same tuple. In this book the distance along the axis played the part of time: it was the clock. When SICM says “time”, read “z”; when it says “coordinate”, read “x”. Its first three chapters build Hamiltonians out of an older kind of function, the Lagrangian. The first thing to try, when you get there, is to recover lens-H from a Lagrangian with Lagrangian->Hamiltonian.

Now your own wishlist. What does our simulator not do?

Let me write them as wishes.

; field-on-axis : Lens -> [Number -> Number]
; the k of a real lens, from its coils and iron

We only ever had the bell. But lens-law, slice-lens, cs-law and cc-law all consume k or kk as a function. None of them knows about Glaser. If a field solver hands me k as a function of z, they all work at once.

That is your colleagues’ Generate_Field. With one caution: state-advancer wants a law-maker whose knobs are numbers. For a solved field the knob might be the coil current. And off the axis?

; field-off-axis :
; [Number -> Number] -> [Number Number -> Number]
; the disc-averaged field in the bore, from
; the field on the axis

bell-off was handed to me. You said the field in an empty bore is fixed by its values on the axis. There must be a function that does that for any k.

There is, and it is an integral, due to Whittaker. Exercise 18.3 gave you its first two terms, which you could write today with D. With it, true-H works for any lens. Next.

; trace-3d : Field State6 Number -> State6
; the true path in space: three positions and
; three momenta, with the time as the clock

Our true ray started on the axis, and we rode the turntable. A ray that starts off the axis, aimed to one side, is not confined to a plane through the axis. To follow it I need all six numbers. And then I can see the aberrations that only off-axis points suffer.

That is your colleagues’ Ray_Tracer. There is a stepper for it, named after Boris, which keeps the electron’s speed exactly constant at every step, as your slices kept the determinant. You know why one would choose such a stepper.

Because the first law says the speed cannot change. An approximation should keep the truths I care about. Chapters 8 and 10.

; a true law that state-advancer can swallow whole
; electric lenses, where the speed does change
; a Beam of Beamlets that carry current and energy
; a Column that is a list of Lenses and Apertures
; at positions, as the team defines it
; a corrector for colour, which needs an electric field

Each of the last four is a variant added to a data definition you already have, and you know what happens then.

The functions tell me where they must change.

Here is how what you built lines up with your colleagues’ definitions.

Their definition

In this book

Chapter

Initial_Beam_Specs, a Beam of Beamlets

Source, Beam, fan

15, 16, 21

Lens, Generate_Field

bell, bell-off (one analytic lens)

11, 18

Paraxial_diff_eqn

lens-law, lens-H

10, 17

the two principal rays

H and G; glaser-h

4, 13

Image_Plane

find-zero on h; glaser-image

11, 13

Demagnification

magnification; glaser-mag

5, 13

Ray_Tracer

runge-kutta on the compiled true-H law (rays from the axis only)

18

Aberration_Coefficients, by Scherzer_Integral

cs-by-integral, cc-by-integral

19, 20

Aberration_Coefficients, by Ray_Tracer

cs-by-rays, CC-BY-RAYS

19, 20

Probe_Sizes, Blur

probe, blur-total, best-angle

21

Transmission_Current

transmit, acceptance

16

One thing puzzles me in their document. It calls the ray that starts at height 1 with slope 0 the axial ray, and the one that starts on the axis with slope 1 the field ray. We have it the other way round.

So does their own proof, and so do most books: the axial ray is the one that leaves the axial point of the object. Mention it to them. Getting two names crossed in a data definition is exactly the kind of mistake that a test against a theorem catches and a meeting does not.

One last question. In the preface I claimed that three habits you already had were most of optics. Were they?

The data definition told me what a ray is and what a column is, and after that trace-ray wrote itself. The examples were where I learned things: I did not understand an image until three fractions all came out zero. And the tests…

The tests changed character, twice. In HtDP a test said “my function does what I meant”. Here the good ones said “nature does what the theorem says”: the determinant is 1; the area is 4; the image is at one quarter. And then, when I stopped choosing numbers, a test became a proof.

And what did optics teach you about programming that you did not know?

That a function consuming a function is not an advanced topic. It is how the subject is spoken. A lens is a function. A law is a function made from it. D is a function that reads functions.

That an unchosen number is still a number, and a program that works on one has been tested on all of them.

And that before writing a loop I should ask what the loop cannot change.

Then you are an opticist. A little one. Go and build the column.

The end. Have whatever you like.

Interlude A Language of One’s Own🔗

The first line of every file names a language. Somebody wrote it.

Read TOY aloud.

(list (make-gap 3) (make-thin 1/2) (make-gap 6)). “Make”, three times. I am describing a column. I am not making anything. I want to write this.

(column (gap 3) (thin 1/2) (gap 6))

Can a function called column give you that? What happens to the arguments of a function?

They are worked out before the function sees them. So (gap 3) would have to be a call that exists, and I never defined gap. No function can do it. I need something stronger than a function: a macro.

Are you sure?

Yes.

> (gap 3)
(make-gap 3)

No.

The define-struct of this language is Racket’s, and it lets gap stand for make-gap. Nobody told you. So your column is?

list. I have designed nothing.

Then want something that a function cannot give you. What are the first two Laws called?

The Drift and the Kick. Those are the words I use when I talk about a column.

(column (drift 3) (kick 1/2) (drift 6))

Can a function give you that?

> (drift 3)
drift: arity mismatch;
the expected number of arguments does not match the given number
expected: 2
given: 1

No. drift is taken: it consumes a distance and a ray. And (drift 3) is worked out before column is called. A function sees values. It never sees what I wrote.

What would have to see what you wrote?

Something that runs before the program runs, and whose data is the program’s text.

That is a macro: a function from program text to program text. It is designed by the recipe, like any function. What does this one consume, and what does it produce?

It consumes the text (column (drift 3) (kick 1/2)). It produces text that the language already understands. The word must not be worked out, so the macro puts a quote on it, and it becomes a symbol. The number must be worked out as usual, so the macro leaves it alone.

(column (drift 3) (kick 1/2))
; becomes, before the program runs,
(list (column-module 'drift 3)
(column-module 'kick 1/2))

That is my example. It leaves a wish: column-module, an ordinary function.

Grant the wish first. What kind of data is the word?

One of three words: an enumeration. One cond clause for each, and a last clause for everything else, which complains in our words.

; column-module : Symbol Number -> Module.v2
; the module that word names, with n for its number;
; word is one of 'drift, 'kick, 'stop
(check-expect (column-module 'drift 3) (make-gap 3))
(check-expect (column-module 'kick 1/2)
(make-thin 1/2))
(check-expect (column-module 'stop 1) (make-stop 1))
(define (column-module word n)
(cond
((equal? word 'drift) (make-gap n))
((equal? word 'kick) (make-thin n))
((equal? word 'stop) (make-stop n))
(else
(error 'column
"~a is not a kind of module" word))))

Now the macro. define-syntax-rule takes a pattern and what the pattern becomes. Three dots after a part of the pattern mean: any number of these.

; column : program text -> program text
; (column (word e) ...) becomes, before the program
; runs, (list (column-module 'word e) ...)
(define-syntax-rule (column (word e) ...)
(list (column-module 'word e) ...))
(check-expect (column (drift 3) (kick 1/2) (drift 6))
TOY)
(check-expect
(column (drift 3) (stop 1) (kick 1/2) (drift 6))
STOPPED)
(check-expect (column (drift 'u) (kick 'p))
(list (make-gap 'u) (make-thin 'p)))

The two ways of writing the toy are the same list. And I can read the column aloud without saying “make”.

Misspell a word.

> (column (drift 3) (lens 1/2))
column: lens is not a kind of module

My own sentence, from the last clause of the cond. The arity a moment ago was the machine’s.

Matthias Felleisen, in an essay called “Developing Developers”, states that as a theorem: compilers and run-time systems write their error messages assuming that the programmer knows the whole language. His corollary is a series of small languages, each of which knows only what its student knows. Who decides which language a file is in?

Its first line. #lang little-opticist.

Which is what?

A library. Four small files, printed in the last chapter, “The Kit”. It is sicm, and check-expect, and tidy printing, and follows, and a define-struct that can be seen into.

And the first line of the chapter you are in?

#lang little-opticist/book. So this chapter is a program. The tests of column ran when the chapter ran.

And these sentences? What runs them?

Nothing. The reader of that language blanks out every line that is not program text, and hands the rest to #lang little-opticist. I am a comment.

You have been called worse. Where is that reader?

In the last chapter: the last of the four files, some hundred and fifty lines of plain Racket. So the book contains the program that reads the book. And that program reads the chapter it is printed in.

It reads every chapter twice. What is the second reading for?

The page. The same reader hands the whole file, sentences and all, to Scribble, and Scribble sets the type. One file, read twice: Run takes what it computes, and the press takes what it says.

And the answers printed after each >?

The same reader collects them, and Run compares each with what the prompt says. (gap 3) answered (make-gap 3) on this page because it answers so at the prompt. Had I printed what I was sure of, the chapter would not pass.

Your colleagues are building a small language of their own, for column design. Their Data Definitions document states that theorem as its motivation, and then gives a grammar: definitions, applications, cond, atomic data, structures. An application begins with a primitive or a variable. drift, kick and through can be written in it as they stand. What can that grammar not say?

A function as an argument. A function as an answer. Every function there has a name, and every name is applied.

When did the optics of this book first demand a function as an argument?

Chapter 7. A lens with length is described by its stiffness, and the stiffness is a function of z. Then a Law was a function. Then D consumed a function and produced one. A language for optics needs lambda.

The corollary was a series, each language adding one idea when the problems demand it. Their problems have reached the next one.

One thing more. The prime, the dot over a letter, the long S of the integral, d/dz. Each of those is a little language too.

Mathematicians and physicists have been inventing them for three hundred years, and not one came with a grammar.

We write the grammar. And their lenses focus.

They do. The joke is theirs to keep. Now count. Three times in this book a thing has been handed itself.

A function, in Y. A column, settled by one of its own cells. And a book, read by a program that is printed in it. Is that all?

That is all.

Make tea. Then open the last chapter and read the reader.

Exercises

L.1 The other people who say “lens” are down the corridor. To a functional programmer, a lens is two functions for one field of a structure: a getter, which consumes the whole and produces the field, and a setter, which consumes a new value for the field and the whole, and produces a new whole. Design one for ray-s. It should obey three laws: set what you got, and nothing changes; get what you set, and it is what you set; set twice, and only the second counts. State each as a check-expect with symbols.

L.2 Teach column a fourth word, lens, for a thick lens of stiffness 1: (lens 2) stands for a uniform lens of length 2 in 100 slices. One word now names a hundred slices. Which function changes, what does it produce now, and what must the macro do with the answers?

L.3 In your mind. Chapter 0 said: “Here a language is a library, and a file names the one it wants.” Open “The Kit” and find the two lines that make that sentence true.

Coda🔗

The first question, asked again.

An electron is flying down the middle of a microscope. If you could stop the film on one frame, what would you need to write down, so that you could say where the electron goes next?

A state. A law that consumes it. And the name of the thing the law cannot change.

That is not what you said in Chapter 1.

In Chapter 1 I said: where it is, and which way it is going. It is the same answer. I have learned what its parts are called.

And the microscope?

A list.

And tracing a ray through it?

A fold. Or a table of four numbers, if I compile the list first.

And a lens that is not thin?

A list I build from a function.

And the function?

A bell. Or whatever your colleagues’ field solver hands me. Nothing I wrote will know the difference.

And an error that no round lens can avoid?

A sum of squares. Until something is not round.

And this book?

A program. Its last chapter is the language its first chapter is written in.

Then where does a program go when it reaches its last line?

It depends on what the last line says.

What does it say?

(define (opticist you)
(opticist (read you)))

Does that function ever produce an answer?

No. It is the column with no last module.

Then you know which page to turn to.

Chapter 1. With a real column this time.

This space is reserved for tea stains.

The Laws and the Commandments🔗

To keep by the keyboard.

The Commandments🔗

First

Take your examples from numbers you can check exactly. Then try a symbol: it is every example at once.

Second

Let the shape of the data be the shape of the function. A column is a list, so tracing is a fold, and the ray is what the fold remembers.

Third

Name the invariant before you compute. What nothing can change tells you more than what something happens to do.

Fourth

Exact numbers for theorems. Inexact numbers for journeys.

Fifth

Know your order. Before you halve the step, say what the error must do. Then look.

Sixth

When a problem is hard, change how you describe it, until it is one you have already solved.

Seventh

Write one function for the system, and derive its law. Never copy out by hand what a machine can derive.

Eighth

An aberration is a departure from the Law of Two Rays. To find one, look for what does not double when the ray doubles.

Ninth

Compute every number that matters in two ways that share as little as possible.

Tenth

To beat Scherzer, break one of his assumptions, on purpose and by name.

The Commandments are the two recipes🔗

Each Commandment is a step of a design recipe, said for physics.

Commandment

In the recipe for a function

In the recipe for a piece of optics

First: exact examples, then a symbol

3 Examples; 6 Tests

3 Special rays; 6 Checks

Second: the shape of the data is the shape of the function

4 Template

Third: name the invariant before you compute

4 Invariant

Fourth: exact for theorems, inexact for journeys

6 Tests

6 Checks

Fifth: know your order

6 Tests, of a method that approximates

6 Checks

Sixth: change the description until the problem is solved

1 Data

1 State

Seventh: one function for the system; derive its law

abstraction

5 Law

Eighth: an aberration is a departure from the Law of Two Rays

refinement

6 Checks

Ninth: every number that matters, two ways

6 Tests

6 Checks

Tenth: to beat Scherzer, break an assumption by name

1 Data: read the definition of the thing you are told is impossible

2 Planes and purpose

The Laws🔗

Chapter

The Drift

In empty space the slope stays. The height grows by the distance times the slope.

1

The Kick

A thin lens keeps the height. It lowers the slope by the power times the height.

1

Two Rays

The trace of a sum is the sum of the traces; the trace of a scaled ray is the scaled trace.

4

The Image

A column forms an image where h is zero. There, g is the magnification.

5

The Determinant

For every column, g times dh minus h times dg is exactly 1.

6

The Round Lens

On a turntable turning at the rate k, the slope of the slope of a ray is minus k squared times its height.

9, 11, 14

Glaser

By gaze and apparent height, every ray of the bell lens of strength q is a ray of the uniform lens of stiffness 1 + q.

12, 13

Area

No column of gaps and lenses changes the area a beam covers on the chart.

15

Scherzer

The aberrations of a round lens are sums of squares. They cannot be zero and cannot be negative.

19, 20

The Round Test

An element is round when turning the ray and then applying it equals applying it and then turning.

23

Empty Space

In empty space a static potential has no Laplacian: its second slope one way is minus its second slope the other.

24

The Push

A thin element keeps the height. It lowers the slope by its strength times the slopes of its potential.

24

Two Wrongs

A thin hexapole, a telescope of magnification minus one, and the same hexapole again, undo each other exactly.

25

The Kick of a Kick

A hexapole with length does not cancel. What survives is round, cubic, and pushes away from the axis.

26

The Stretched Beam

An octupole alone has no round part. On a beam stretched by quadrupoles it has one, of the sign the designer chooses.

27

The Budget

A correction is worth what the corrected term was worth in the sum.

28

Proved, not only tested🔗

Each of these is a check-expect in the book in which nothing was chosen, so it holds for every number.

Claim

For every

Chapter

A thin lens of power p brings level rays to the axis at 1/p

height, power

1

image-distance is where the image is

power, distance, slope

2

The Law of Two Rays

gap, lens, gap; two rays; a scale

4

Following columns multiplies determinants

two tables of four numbers

6

A column of five parts has determinant 1

three gaps, two powers

6

(/ (sin (* k z)) k) is the axial ray of a uniform lens

pace, place

9

glaser-h is the axial ray of Glaser’s lens

strength, object, place

13

h-exact is that ray for strength 3

place

13

The slope of the gaze is the bell

place

14

A gap, a lens and a gap keep the area of a square

gap, power, gap

15

Hamilton’s recipe gives the lens law

stiffness function, state

17

A Hamiltonian that does not mention z is conserved

stiffness, state

17

Numbers worth knowing by heart🔗

All for the Glaser lens of strength 3, with its object 4 half-widths before its centre. Each is a theorem in the proof corpus, and a passing test in this book.

Quantity

Exactly

About

Tested in

image plane

1/4

.25

11, 13

magnification

−1/4

−.25

11, 13

slope of the axial ray at the image

−4

−4

11

turn of the image

√3 · π/2

2.7207 (156°)

14

spherical aberration, at the object

102/5 + 867π/32

105.5175

19

chromatic aberration, at the object

51π/8

20.0277

20

The program🔗

The book is its own program. Every chapter in book/ begins #lang little-opticist/book: open one in DrRacket, for example 13-glaser-in-disguise.scrbl, and press Run. You have everything the book has built up to there, that chapter’s tests are run, and every interaction it prints is checked against the prompt. The same file is the page: raco scribble prints it, and this book is what it printed. The folder code/ holds the same programs with the prose taken out, one file per chapter. To run the whole book at once, type raco test book in a terminal.

In order of appearance:

Chapter

Data definitions

Functions

1

Ray

make-ray, ray-x, ray-s, drift, kick

2

toy, image-distance

3

Module, ModuleStack

make-gap, make-thin, through, trace-ray, stack-length

4

G, H

5

Transfer

make-transfer, stack->transfer, apply-transfer, image?, magnification

6

then

7

slice-lens

8

wave

9

slope-near, h-uniform

10

State, Law

lens-law, euler-step, flow, euler, rk4-step, runge-kutta, swing, uniform-law

11

bell, bell-kk, glaser-law, glaser-ray, h-traced, g-traced, find-zero

12

gaze, swept, apparent, watched

13

MaybeNumber

pace, glaser-h, glaser-image, glaser-mag, h-exact, strength-for

14

integrate, turn-traced, glaser-turn

15

Beam

trace-beam, cross, area

16

Module.v2, MaybeRay

make-stop, through.v2, trace-ray.v2, transmit, fan, acceptance

17

Hamiltonian

lens-H, hamiltonian->law

18

true-H, bell-off, landing

19

cs-by-ray, cs-by-rays, cs-law, cs-by-integral, cs-at-image

20

detuned, off-colour, cc-law, cc-by-integral

21

Source, Objective, Optics, Blur

volts->momentum, wavelength, peak-field, momentum-spread, objective->optics, probe, blur-total, best-angle

22

glaser-cs-far

23

Across, a Ray in two directions

ray2, quarter, turn

24

Potential

bowl, push, laplacian, round4, w-power, pole

25

flip, spoiled, ring, unit-telescope

26

thick, corrector, corrector-c, objective, k-for, lands, widest, shifted

27

ring-mean, iso, stretched

28

Row

corrected, best-probe, row-budget, row-corrected, row-at

interludes

Y; cells, forever, half-corner-sum; column

From sicm itself the book uses: up, ref, matrix-by-rows, matrix-ref, determinant, D, partial, literal-function, state-advancer, definite-integral, and Hamiltonian->state-derivative. From the language itself: check-expect, check-within, follows, pi, compile-law and formula-size.

The Kit🔗

The files in this book that you did not write.

The language of the book, #lang little-opticist, is four small files. They are printed here in full, so that nothing in the book is hidden from you, and so that the book contains its own language. They are written in plain Racket, and they use things HtDP did not teach: assignment (set!), macros (define-syntax), modules inside modules (module+), readers, and eval. The Seasoned Schemer teaches the first; The Little Schemer ends with the last; the Racket Guide has the rest. Read them when you are curious, not before.

The kit🔗

check-expect, check-within, the tidy answers at the prompt, follows, and two tools for Chapter 18.

little-opticist/kit.rkt

#lang racket/base
(require (for-syntax racket/base)
racket/pretty racket/string
(only-in racket/class object?)
(only-in racket/math pi)
(only-in sicm
simplify expression up
literal-number? matrix? down?
matrix->array))
(provide check-expect check-within run-tests interactions
install-tidy-printer!
follows pi compile-law formula-size
(rename-out [top-interaction #%top-interaction]))
;;; ------------------------------------------------------------
;;; Testing: check-expect, check-within, run-tests
;;; ------------------------------------------------------------
;; A Check is
;; (list expression line actual-thunk expected-thunk judge)
;; Checks are only remembered where they are written; they are
;; run by (run-tests). That is why an example may come before
;; the definition it is an example of.
(define *checks* '())
(define (remember-check! c)
(set! *checks* (cons c *checks*)))
;; a formula, a tuple or a matrix: something that sicm
;; knows how to simplify
(define (formula? x)
(or (literal-number? x) (matrix? x) (down? x) (vector? x)))
(define (quantity? x)
(or (number? x) (symbol? x) (formula? x)))
;; structure? : Any -> Boolean
;; is x made by a transparent define-struct? (A picture
;; from the plot library is not: leave those alone.)
(define (structure? x)
(and (struct? x) (not (object? x))))
;; fields : Structure -> [List-of Any]
;; the name of a structure, then what is in its fields
(define (fields s)
(vector->list (struct->vector s)))
;; same? : Any Any -> Boolean
;; are a and b the same, once every formula is simplified?
(define (same? a b)
(cond [(equal? a b) #t]
[(and (quantity? a) (quantity? b))
(equal? (simplify a) (simplify b))]
[(and (pair? a) (pair? b))
(and (same? (car a) (car b))
(same? (cdr a) (cdr b)))]
[(and (structure? a) (structure? b))
(same? (fields a) (fields b))]
[else #f]))
;; close? : Any Any Number -> Boolean
;; are a and b the same to within tol, number by number?
(define (close? a b tol)
(cond [(and (number? a) (number? b))
(<= (magnitude (- a b)) tol)]
[(and (matrix? a) (matrix? b))
(close? (matrix->array a) (matrix->array b) tol)]
[(and (vector? a) (vector? b))
(close? (vector->list a) (vector->list b) tol)]
[(and (pair? a) (pair? b))
(and (close? (car a) (car b) tol)
(close? (cdr a) (cdr b) tol))]
[(and (structure? a) (structure? b))
(close? (fields a) (fields b) tol)]
[else (equal? a b)]))
;; The checks of a file go into a part of it called "test".
;; DrRacket runs that part when you press Run in that file,
;; and not when a later chapter requires the file. So Run
;; tests the chapter you are looking at, and no other.
(define-syntax (check-expect stx)
(syntax-case stx ()
[(_ actual expected)
(with-syntax ([line (syntax-line stx)])
#'(module+ test
(remember-check!
(list 'actual 'line
(lambda () actual)
(lambda () expected)
same?))))]))
(define-syntax (check-within stx)
(syntax-case stx ()
[(_ actual expected tol)
(with-syntax ([line (syntax-line stx)])
#'(module+ test
(remember-check!
(list 'actual 'line
(lambda () actual)
(lambda () expected)
(lambda (a b) (close? a b tol))))))]))
(define-syntax (run-tests stx)
(syntax-case stx ()
[(_) #'(module+ test (run-remembered-checks!))]))
;; run-check : Check -> Number
;; runs one check; says what went wrong, if anything did;
;; produces 0 if it passed and 1 if it did not
(define (run-check c)
(define-values (what line actual expected judge)
(apply values c))
(define outcome
(with-handlers
([exn:fail? (lambda (e) (list 'stopped (exn-message e)))])
(let ([a (actual)] [e (expected)])
(if (judge a e) 'passed (list 'differ a e)))))
(cond
[(eq? outcome 'passed) 0]
[else
(printf "FAILED, line ~a: ~s\n" line what)
(if (eq? (car outcome) 'stopped)
(printf " it stopped with: ~a\n" (cadr outcome))
(printf " actual: ~s\n expected: ~s\n"
(tidy (cadr outcome)) (tidy (caddr outcome))))
1]))
(define (run-remembered-checks!)
(define cs (reverse *checks*))
(set! *checks* '())
(define bad (apply + (map run-check cs)))
(cond [(null? cs) (void)]
[(= bad 0)
(printf "All ~a tests passed!\n" (length cs))]
[else
(printf "~a of ~a tests FAILED.\n" bad (length cs))])
(run-remembered-interactions!))
;;; ------------------------------------------------------------
;;; Interactions: what the page says the prompt answers
;;; ------------------------------------------------------------
;; An Interaction is (list line typed expected): on that line
;; of a chapter, the page shows `typed` at the prompt and
;; `expected` as the answer. Three dots in an expected answer
;; stand for anything.
(define *interactions* '())
(define (remember-interactions! ns is)
(set! *interactions*
(append *interactions*
(map (lambda (i) (cons ns i)) is))))
;; (interactions i ...) is written for you by the reader of
;; #lang little-opticist/book, once in each chapter.
(define-syntax (interactions stx)
(syntax-case stx ()
[(_ i ...)
#'(begin
(define here (#%variable-reference))
(module+ test
(remember-interactions!
(variable-reference->namespace here)
'(i ...))))]))
;; answer : Namespace String -> String
;; what the prompt of that module prints when you type that;
;; if it complains, the complaint
(define (answer ns typed)
(define out (open-output-string))
(with-handlers
([exn:fail?
(lambda (e) (exn-message e))])
(parameterize ([current-namespace ns])
(call-with-values
(lambda ()
(eval (list* '#%top-interaction
(read (open-input-string typed)))))
(lambda vs
(for-each (lambda (v)
(unless (void? v) (print v out) (newline out)))
vs))))
(get-output-string out)))
(define (squash s)
(string-trim (regexp-replace* #px"\\s+" s " ")))
;; agrees? : String String -> Boolean
(define (agrees? expected actual)
(regexp-match?
(regexp
(string-append
"^"
(string-join
(map regexp-quote
(regexp-split #rx"[.][.][.]" (squash expected)))
".*")
"$"))
(squash actual)))
;; run-interaction : (cons Namespace Interaction) -> Number
(define (run-interaction i)
(define-values (ns line typed expected) (apply values i))
(define actual (answer ns typed))
(cond
[(agrees? expected actual) 0]
[else
(printf "DIFFERS, line ~a: > ~a\n" line typed)
(printf " the page says: ~a\n the prompt says: ~a\n"
(squash expected) (squash actual))
1]))
(define (run-remembered-interactions!)
(define is *interactions*)
(set! *interactions* '())
(define bad (apply + (map run-interaction is)))
(cond [(null? is) (void)]
[(= bad 0)
(printf "All ~a interactions agree with the page.\n"
(length is))]
[else
(printf "~a of ~a interactions DIFFER from the page.\n"
bad (length is))]))
;;; ------------------------------------------------------------
;;; Answers at the prompt
;;; ------------------------------------------------------------
;; ->written : Any -> S-expression
;; a value, as you would write it in a program
(define (->written v)
(cond [(formula? v) (simplify v)]
[(null? v) ''()]
[(list? v) (cons 'list (map ->written v))]
[(pair? v)
(list 'cons (->written (car v)) (->written (cdr v)))]
[(structure? v)
(let ([fs (fields v)])
(cons (string->symbol
(string-append
"make-"
(substring (symbol->string (car fs)) 7)))
(map ->written (cdr fs))))]
[else v]))
;; A Shown is (shown S-expression): something that prints
;; as that expression and nothing more.
(struct shown (written)
#:property prop:custom-write
(lambda (v port mode)
(parameterize ([pretty-print-columns 56])
(pretty-write (shown-written v) port #:newline? #f))))
;; tidy : Any -> Any
;; numbers, booleans and strings as they are;
;; everything else, as you would write it
(define (tidy v)
(if (or (symbol? v) (pair? v) (null? v)
(formula? v) (structure? v))
(shown (->written v))
v))
(define (tidy-values thunk)
(call-with-values
thunk
(lambda vs (apply values (map tidy vs)))))
;; install-tidy-printer! : -> Void
;; from now on, whatever is printed is tidied first. The
;; language calls this once, so that an expression in the
;; definitions window prints as it would at the prompt.
(define tidy-printer-installed? #f)
(define (install-tidy-printer!)
(unless tidy-printer-installed?
(set! tidy-printer-installed? #t)
(let ([print-it (current-print)])
(current-print (lambda (v) (print-it (tidy v)))))))
;; Everything typed in the interactions window passes
;; through here. A definition is left alone; the answer to
;; an expression is tidied.
(define-syntax (top-interaction stx)
(syntax-case stx ()
[(_ . form)
(let ([e (local-expand
#'form 'top-level
(list #'define-values #'define-syntaxes
#'begin #'#%require))])
(syntax-case e (define-values define-syntaxes
begin #%require)
[(define-values . _) e]
[(define-syntaxes . _) e]
[(begin . _) e]
[(#%require . _) e]
[_ #`(tidy-values (lambda () #,e))]))]))
;;; ------------------------------------------------------------
;;; One chapter after another
;;; ------------------------------------------------------------
;; (follows "file.rkt") brings in everything that file
;; defines, and everything it brought in, and passes all of
;; it on to whichever file follows this one. (The language
;; passes on this file's own definitions.)
(define-syntax (follows stx)
(syntax-case stx ()
[(_ file)
#'(begin (require file)
(provide (all-from-out file)))]))
;;; ------------------------------------------------------------
;;; Speed: turning a derived law into a fast one (Chapter 18)
;;; ------------------------------------------------------------
;; compile-law : Law -> Law
;; A law that sicm derived from a Hamiltonian works out its
;; slopes afresh every time it is asked. This asks it once,
;; for the unchosen state (up z x p); the answer is a formula,
;; which is a list; and eval turns that list into a procedure
;; that only does arithmetic.
(define-namespace-anchor here)
(define plain-arithmetic (namespace-anchor->namespace here))
(define (compile-law law)
(let ([formula (expression (law (up 'z 'x 'p)))])
(eval `(lambda (y)
(let ([z (vector-ref y 0)]
[x (vector-ref y 1)]
[p (vector-ref y 2)])
(vector ,@(cdr formula))))
plain-arithmetic)))
;; formula-size : Law -> Number
;; how many symbols and numbers there are in that formula
(define (formula-size law)
(define (count e)
(if (pair? e) (+ (count (car e)) (count (cdr e))) 1))
(count (expression (law (up 'z 'x 'p)))))

The language🔗

sicm, the kit, and five kindnesses.

little-opticist/main.rkt

#lang racket/base
;; #lang little-opticist
;; It is sicm, and the kit, and five kindnesses to a student
;; who learned to program from How to Design Programs.
(require (for-syntax racket/base)
(except-in sicm #%module-begin #%top-interaction)
(only-in racket/list
first rest second third empty empty?)
(only-in racket/local local)
"kit.rkt")
(provide (except-out (all-from-out sicm) define-struct)
(all-from-out "kit.rkt")
first rest second third empty empty? local sqr
(rename-out [module-begin #%module-begin]
[define-clear-struct define-struct]))
;; 1. The tests of a file run when the file is run.
;; 2. What the definitions window prints is tidied too.
;; And every file hands on what it defines, so that
;; another file may follow it.
(define-syntax (module-begin stx)
(syntax-case stx ()
[(_ form ...)
(with-syntax ([mine (datum->syntax stx '(all-defined-out))])
#'(#%module-begin
(install-tidy-printer!)
(provide mine)
form ...
(run-tests)))]))
;; 3. A structure can always be looked into, to compare it
;; and to print it, as in the student languages.
(define-syntax (define-clear-struct stx)
(syntax-case stx ()
[(_ name (field ...))
#'(define-struct name (field ...) #:transparent)]))
;; 4. The old words still work: first, rest, empty?, local.
;; 5. And sqr.
(define (sqr x) (square x))

The reader of #lang little-opticist is two lines: read the file as usual, and hand it to the language above.

little-opticist/lang/reader.rkt

#lang s-exp syntax/module-reader
little-opticist/main

The book’s own reader🔗

Every chapter of this book begins with the line #lang little-opticist/book. That makes the chapter a program: open book/01-toys.scrbl in DrRacket, press Run, and Chapter 1 runs, tests and all, with everything it defines at your prompt.

It also makes the chapter a page. The words of a chapter are written for Scribble, the language in which Racket’s own manuals are written: raco scribble asks the same file for its other reading and sets it in type. This is the reader that gives a file both.

little-opticist/book/lang/reader.rkt

#lang racket/base
;; #lang little-opticist/book
;; A chapter of this book is one file with two readings.
;; Read as a program, every line that is not program text is
;; blanked out and the rest is handed to #lang little-opticist;
;; the interactions the chapter prints are collected, so that
;; Run can check the page against the prompt.
;; Read as a page, the whole file is a Scribble document. It
;; is kept in a module of its own, called doc, inside the
;; program, where raco scribble looks for it.
(require racket/list racket/string racket/port racket/file
(only-in scribble/reader read-syntax-inside))
(provide (rename-out [chapter-read read]
[chapter-read-syntax read-syntax])
get-info)
;; A Kind is one of 'prose, 'code, 'repl.
;; classify : [List-of String] -> [List-of (list Kind String)]
;; each line of a chapter, with the kind of block it is in;
;; the lines that open and close a block are prose
(define (classify lines)
(let loop ([ls lines] [in 'prose] [out '()])
(cond
[(null? ls) (reverse out)]
[else
(define l (car ls))
(cond
[(and (eq? in 'prose) (equal? l "@scheme|{"))
(loop (cdr ls) 'code (cons (list 'prose l) out))]
[(and (eq? in 'prose) (equal? l "@repl|{"))
(loop (cdr ls) 'repl (cons (list 'prose l) out))]
[(and (not (eq? in 'prose)) (equal? l "}|"))
(loop (cdr ls) 'prose (cons (list 'prose l) out))]
[else
(loop (cdr ls) in (cons (list in l) out))])])))
;; program-text : [List-of (list Kind String)] -> String
;; the chapter with every line that is not code turned to
;; spaces, so that each parenthesis stays where it was
(define (program-text classified)
(string-join
(map (lambda (kl)
(if (eq? (car kl) 'code)
(cadr kl)
(make-string (string-length (cadr kl)) #\space)))
classified)
"\n"))
;; interactions-of :
;; [List-of (list Kind String)] Number -> [List-of Interaction]
;; In a repl block, a line that begins "> " is typed; lines
;; after it that begin with two spaces continue it; the
;; rest, up to the next "> ", is the answer on the page.
(define (interactions-of classified first-line)
(let loop ([ls classified] [n first-line] [cur #f] [out '()])
(define (closed)
(if cur
(cons (list (car cur) (cadr cur)
(string-join (reverse (caddr cur)) "\n"))
out)
out))
(cond
[(null? ls) (reverse (closed))]
[else
(define kind (car (car ls)))
(define l (cadr (car ls)))
(cond
[(not (eq? kind 'repl))
(loop (cdr ls) (add1 n) #f (closed))]
[(string-prefix? l "> ")
(loop (cdr ls) (add1 n)
(list n (substring l 2) '()) (closed))]
[(and cur (null? (caddr cur)) (string-prefix? l " "))
(loop (cdr ls) (add1 n)
(list (car cur)
(string-append (cadr cur) "\n" l)
'())
out)]
[cur
(loop (cdr ls) (add1 n)
(list (car cur) (cadr cur) (cons l (caddr cur)))
out)]
[else (loop (cdr ls) (add1 n) cur out)])])))
;; previous-chapter : Any -> (or String #f)
;; the nearest earlier chapter in the same folder that has
;; program text in it: the one this chapter follows
(define (previous-chapter src)
(cond
[(path? src)
(define-values (dir name must-be-dir?) (split-path src))
(define folder (if (path? dir) dir (current-directory)))
(define me (path->string name))
(define earlier
(filter
(lambda (f)
(and (regexp-match? #rx"^[0-9][0-9].*[.]scrbl$" f)
(string<? f me)
(regexp-match? #rx"\n@scheme[|]{\r?\n"
(file->string (build-path folder f)))))
(sort (map path->string (directory-list folder))
string<?)))
(if (null? earlier) #f (last earlier))]
[else #f]))
;; read-all : Any String (-> Port Any) Any Any Any -> Any
;; what read-one makes of text, as if text stood in the file
;; src at the given place
(define (read-all src text read-one line col pos)
(define in (open-input-string text))
(port-count-lines! in)
(when line (set-port-next-location! in line col pos))
(read-one in))
(define (chapter-read-syntax src in)
(define-values (line col pos) (port-next-location in))
(define text (port->string in))
(define classified (classify (regexp-split #rx"\r?\n" text)))
(define program
(read-all src (program-text classified)
(lambda (code)
(let loop ()
(define form (read-syntax src code))
(if (eof-object? form) '() (cons form (loop)))))
line col pos))
(define page
(read-all src text
(lambda (words)
(syntax->list (read-syntax-inside src words)))
line col pos))
(define previous (previous-chapter src))
(datum->syntax
#f
`(module chapter little-opticist/main
,@(if previous `((follows ,previous)) '())
,@program
(interactions
,@(interactions-of classified (or line 1)))
(module doc scribble/doclang2
(require little-opticist/press)
,@page))))
(define (chapter-read in)
(syntax->datum (chapter-read-syntax #f in)))
;; get-info : what DrRacket asks a language about itself.
;; Colour a chapter as Scribble does, and offer its buttons.
(define (get-info in mod line col pos)
(lambda (key default)
(case key
[(color-lexer)
(dynamic-require 'syntax-color/scribble-lexer
'scribble-inside-lexer)]
[(drracket:toolbar-buttons)
(dynamic-require 'scribble/tools/drracket-buttons
'drracket-buttons)]
[else default])))

The second reading needs one file more. press.rkt says what a frame, a law and a block of program text are when they are printed, and a style sheet beside it says how they look. That is typography and not language, so it is not printed here. It sits in the same folder as these four.

1 Maintainer🔗

Commits and builds are signed with the keys listed at https://atharvashukla.com.

Built from 924c9d4a6d07cf85dc2ba9f672dc380ffcb4f9f7 of svayam.