Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Computational thinking for engineers in Python: representation, scaling, dynamic programming, search, reduction, information and emergence

School of Engineering, Nazarbayev University

How to turn an engineering problem into a computation that can be trusted, with every method written out in NumPy and checked against an exact result or a brute-force oracle.

Much of the work of an engineer with a computer is deciding what to compute. This book collects 24 habits for making those decisions, the Mental Moves, and teaches each one by computing with it, in five parts. The first part treats representation: what a float64 can hold, how sums and variances lose digits and how to keep them, how dimensionless groups reduce a parameter sweep, and how loop invariants and state machines make code correct by construction. The second part treats cost: how to measure the growth of a computation, and how prefix sums, monotonic queues, cell lists, divide and conquer, trees and the FFT change it. The third part treats optimal decisions: dynamic programming, decisions under uncertainty, greedy rules and when they are safe, and informed search on terrain. The fourth part translates new problems into known ones (exact cover, critical paths, flows) and measures information: entropy, divergence, diagnosis with the fewest tests, and summaries of data streams in fixed memory. The fifth part treats systems whose behaviour changes abruptly (percolation, traffic jams, flocking), random search, and the testing of code for which no reference answer exists, and closes with a project that uses the methods of all five parts.

Each lecture is an executed Jupyter notebook of about one hour. It states the idea and its equations, works through four short demonstrations, and then repeats by hand the calculation of a function of the package that it has used. The notebooks share a small Python package, engthink, written to be read as much as to be used; its core needs NumPy alone. Each lecture has numbered, captioned figures and ends with three exercises: one that verifies a result, one that looks for a way in which the method fails, and one that asks the reader to write a function. A worked solution to every exercise is given in the Worked solutions part of the book.

Data that stand for measurements are synthetic: they are generated in the notebooks from stated laws, so that the answer is known and a method can be judged against it. Assumed parameters are labelled as assumed, and the scenario of the closing project is fictional.

The level is that of the second or third undergraduate year in engineering or the physical sciences, and of graduate students who want a systematic account of these methods. The lectures assume calculus, a little linear algebra and probability, and Python with NumPy. The 24 moves are collected in the playbook, symbols in Notation and conventions, a plan for a semester in the syllabus, the checks of the package in the validation report, and original papers and books for further study in Suggested references.

Part I. Representation, precision and dimensional invariants

LectureTopics
0. Floating-point numbers, cancellation and compensated summationthe bits of a float64; absorption and cancellation; compensated summation; Welford’s running variance; log-sum-exp
1. Dimensional analysis: the Buckingham Pi theorem and Taylor’s estimate of the Trinity yieldthe Buckingham Pi theorem with exact rational null spaces; Taylor’s estimate of the Trinity energy; collapse of pipe-flow data; scale models
2. Loop invariants, state machines and conservation laws as code contractsloop invariants and variants; binary exponentiation; the Dutch national flag partition; state machines and reachability; conservation in flux updates

Part II. Scaling, divide and conquer, spatial and frequency hierarchies

LectureTopics
3. Measuring cost: doubling ratios, prefix sums, monotonic queues and cell listsdoubling ratios; summed-area tables; monotonic deques; cell lists; two pointers
4. Divide and conquer: recursion trees, binary search on the answer and inversion countingthe master theorem; binary search on the answer; inversion counting with merge sort; golden-section search; quickselect
5. Spatial and frequency hierarchies: Barnes–Hut quadtrees and the fast Fourier transformBarnes–Hut quadtrees; the radix-2 FFT; convolution and matched filtering; bit-reversal FFT
LectureTopics
6. Dynamic programming: knapsack, sequence alignment and seam carvingoverlapping subproblems; the 0/1 knapsack; sequence alignment and edit distance; seam carving; two-row tables
7. Decisions under uncertainty: stochastic dynamic programming for energy storagestochastic dynamic programming for storage; the flaw of averages; the value of perfect information; the efficiency deadband; value iteration
8. Greedy algorithms: exchange arguments, optimal caching and Bélády’s anomalyexchange arguments; interval scheduling; Bélády’s optimal cache; the FIFO anomaly; coin systems
9. Shortest paths on terrain: breadth-first search, Dijkstra and A*breadth-first search, Dijkstra and A* on terrain; weighted A*; 4- and 8-neighbour grids; bidirectional search

Part IV. Problem reduction, information and data streams

LectureTopics
10. Problem reduction: exact cover with Algorithm Xexact cover and Algorithm X; NN queens; Latin squares; MRV branching
11. Dependency graphs: critical paths, maximum flow and Braess’s paradoxcritical paths and slack; crashing; single points of failure; Braess’s paradox; maximum flow and minimum cut
12. Information: entropy, Kullback–Leibler divergence and fault diagnosissurprise and entropy; the Kullback–Leibler divergence; fault-isolation trees; noisy tests
13. Data streams: reservoir sampling, Bloom filters and count–min sketchesreservoir sampling; Bloom filters; count–min sketches; HyperLogLog; Misra–Gries

Part V. Emergence, randomness and verification

LectureTopics
14. Percolation: critical thresholds and cluster connectivitysite percolation; finite-size scaling; tortuosity; union-find; resistor networks
15. Emergence: traffic jams in a cellular automaton and flockingthe Nagel–Schreckenberg traffic model; the fundamental diagram; Vicsek flocking; Schelling’s model
16. Random search and testing: simulated annealing, Latin hypercubes and metamorphic testsLatin hypercube sampling; simulated annealing; metamorphic testing; shrinking a failing input
17. Project: planning a relief mission after an earthquakea relief mission planned with the methods of all five parts (synthetic data, assumed aircraft parameters)

Where to start

If you are…Read
writing numerical code that sums or averages long recordsLecture 0
planning experiments or simulations with many parametersLecture 1
finding that your code is too slowLectures 3 to 5
optimizing a schedule, a route or an allocationLectures 6 to 11
designing diagnostics or monitoring a data streamLectures 12 and 13
testing code that has no reference answerLecture 16
short of timeLectures 0, 3, 6, 9 and 16

Companion books

Author and licence

Yanwei Wang, Department of Chemical and Materials Engineering, School of Engineering, Nazarbayev University, Astana, Kazakhstan (yanwei.wang@nu.edu.kz, ORCID 0000-0002-8488-9833). The code is under the MIT licence; the text, figures and notebook outputs are under CC BY 4.0. The source is at github.com/ktwyw/engthink.