For seven chapters we have studied one oscillator: a mass on a spring with a dashpot, ringing at a single period. A real building has many floors, each free to move sideways, so it has many degrees of freedom and many periods. It might seem that we have to start over, but we do not, because of a central result of structural dynamics.
A linear multi-degree-of-freedom (MDOF) structure with classical damping is not one complicated system but a set of independent SDOF oscillators in disguise. Each one is exactly the oscillator we already know how to solve, with its own period, its own damping and its own share of the load. The method that reveals them is modal analysis. By the end of this chapter you will take a three-story building, find its hidden oscillators, drive each one with the Chapter-3 engine, add the answers back up, and watch them reproduce a full direct integration of the coupled building to machine precision.
1A shear building and its matrices¶
Picture a three-story frame whose floors are rigid and heavy and whose columns are light and flexible, the classic shear building. The mass piles up at the floor levels, and the only motion that matters is the sideways displacement of each floor. With one horizontal degree of freedom per floor, the building has three DOFs, the floor displacements relative to the ground, numbered from the bottom floor up.
Figure 1:A three-story shear building (left) and its idealization (right) as lumped floor masses joined by story springs , with the floor displacements as the degrees of freedom.
Two matrices encode the structure, playing the roles that the single numbers and played for the SDOF. The mass matrix is diagonal (each floor’s inertia sits on its own DOF, with no coupling), so it is just the lumped floor masses on the diagonal:
The stiffness matrix is where the floors talk to each other. Story has a shear stiffness (the combined lateral stiffness of its columns), and it resists the story drift, the difference between the displacements of the floors above and below it. Assembling the story springs into a chain gives the familiar tridiagonal form:
Each diagonal entry collects the stiffness of the springs meeting at that floor; each off-diagonal is minus the spring shared between two floors. We build both matrices in code for a slightly top-light building, whose roof carries less mass, with stiffer lower stories, as is common in real buildings.
# Three-story shear building. SI units: tonnes, kN, m, s.
masses = np.array([3.0, 3.0, 2.0]) # floor masses m1, m2, m3 (t)
ks = np.array([2400.0, 1800.0, 1200.0]) # story stiffnesses k1,k2,k3 (kN/m)
n = masses.size
M = np.diag(masses)
# Assemble the tridiagonal shear-building stiffness from the story springs.
K = np.zeros((n, n))
for i in range(n):
K[i, i] += ks[i] # spring below floor i
if i + 1 < n:
K[i, i] += ks[i + 1] # spring above floor i
K[i, i + 1] -= ks[i + 1]
K[i + 1, i] -= ks[i + 1]
print("M (t) =\n", M)
print("\nK (kN/m) =\n", K)M (t) =
[[3. 0. 0.]
[0. 3. 0.]
[0. 0. 2.]]
K (kN/m) =
[[ 4200. -1800. 0.]
[-1800. 3000. -1200.]
[ 0. -1200. 1200.]]
The equation of motion is the SDOF equation of motion from Chapter 1 with the scalars promoted to matrices and the response promoted to a vector :
Read it exactly as before, inertia plus damping plus stiffness equals load, only now , , are and the three equations are coupled: the off-diagonal , terms mean floor 1’s motion pushes on floor 2, and so on. That coupling is what makes a building feel complicated, and modal analysis will untangle it.
2Modes and frequencies¶
Set the damping and load aside (, ) and ask the question that worked so well for the single oscillator in Chapter 2: can the building vibrate in a fixed shape that simply scales up and down in time? Figure 2 shows such a motion: the building is released from rest in its first mode, which we compute later in this section, and vibrates freely. Every floor moves in sync with the others: all floors reach their extremes together and pass through zero together (their circles on the time axis nest into one), and the ratios between the floor displacements stay fixed at 0.35, 0.73 and 1.00 throughout the motion, so every floor is always at the same fraction of its released displacement, as the readout at the top of the figure reports. The selector releases the building in its second or third mode instead: some floors then move in exact anti-phase with the roof, but the shape still only scales, now with a shorter period. Released with all floors displaced equally, a shape that is not a mode, the floors fall out of step and the deflected shape changes from instant to instant, because that shape mixes all three modes and each of them keeps its own period.
Figure 2:Free vibration of the chapter’s building released from rest in one of its modes or in a shape that is not a mode: the building with its displacements magnified (left) and the floor displacements as fractions of the released roof displacement, with open circles at each floor’s zero crossings (right).
To find such motions, we try exactly that synchronous form,
a single time-independent shape vector whose amplitude breathes in and out at one frequency . This is the MDOF echo of the sine-plus-cosine trial that fixed in Chapter 2; here also carries the spatial pattern. Differentiating twice brings down a factor , so . Substitute both into the undamped, unforced equation :
The scalar is nonzero at almost every instant, so the bracket itself must vanish, exactly as the bracket had to vanish for the SDOF. That leaves a purely algebraic condition on the shape and the frequency, the generalized eigenvalue problem
Each solution is a pair: a mode shape (the fixed
deflected shape the building holds while it sways) and a natural frequency
(how fast it sways in that shape). A nonzero
exists only when is singular, i.e. when
, and that determinant is a polynomial of
degree in , so an -DOF building has exactly such pairs (here,
three). Notice is fixed only up to a scale: if it solves
(6), so does any multiple of it, because the equation is
homogeneous. We pin that freedom down with a normalization in a moment.
scipy.linalg.eigh solves (6) directly, returning the eigenvalues
and the mode-shape columns at once.
from scipy.linalg import eigh
w2, Phi = eigh(K, M) # K phi = w^2 M phi ; columns of Phi are the modes
wn = np.sqrt(w2) # natural circular frequencies (rad/s)
fn = wn / (2 * np.pi) # in Hz
Tn = 2 * np.pi / wn # natural periods (s)
# Scale each mode so its ROOF (top-floor) entry equals 1 (unit roof displacement).
Phi = Phi / Phi[-1, :] # divide each column by its last component
Mr = np.diag(Phi.T @ M @ Phi).copy() # modal masses M_r = phi_r^T M phi_r (t)
for r in range(n):
print(f"mode {r+1}: Tn = {Tn[r]:.3f} s fn = {fn[r]:.2f} Hz "
f"wn = {wn[r]:5.2f} rad/s M_r = {Mr[r]:5.2f} t "
f"phi = [{', '.join(f'{v:+.2f}' for v in Phi[:, r])}]")mode 1: Tn = 0.494 s fn = 2.02 Hz wn = 12.72 rad/s M_r = 3.98 t phi = [+0.35, +0.73, +1.00]
mode 2: Tn = 0.205 s fn = 4.87 Hz wn = 30.60 rad/s M_r = 4.52 t phi = [-0.73, -0.56, +1.00]
mode 3: Tn = 0.144 s fn = 6.94 Hz wn = 43.61 rad/s M_r = 36.31 t phi = [+2.59, -2.17, +1.00]
The building has three periods, from a slow first mode at s down to a fast third mode near 0.14 s. The first mode is the soft, dominant one (the whole building leaning the same way), and as we go up in mode number the shapes get more wiggly and the periods get shorter, just as a guitar string’s overtones do.
We now spend the leftover scale freedom noted above, following a convention
common in earthquake engineering: scale each mode so its roof (top-floor)
component is 1, the line Phi = Phi / Phi[-1, :]. The deflected shapes are then
read directly against a unit roof displacement, and the first mode,
, gives the ratios drawn in
Figure 2. With the scale pinned this way each mode has its own modal mass
, the generalized
mass that mode presents, a number we will lean on shortly. Whatever the
normalization, the modes share a deeper property: they are orthogonal through
both matrices (different modes do not share inertia or stiffness).
That orthogonality is not luck; it falls straight out of (6) together with the symmetry of and . Take two different modes , write the eigenproblem for each, and pre-multiply by the other mode shape:
Because and are symmetric, the two left-hand sides are equal (each is just a number, and transposing it leaves it unchanged: , and likewise for ). Subtracting the two equations therefore kills the left side and leaves . For distinct frequencies the prefactor is nonzero, so the only escape is
The modes are therefore M-orthogonal and K-orthogonal, and with the modes stacked into the columns of , orthogonality makes both triple products diagonal: , the modal masses, and (using ). The zeros off the diagonal are the orthogonality; the diagonal entries are the modal mass and modal stiffness. We can check both in one line each.
print("Phi^T M Phi =\n", np.round(Phi.T @ M @ Phi, 4)) # diagonal = modal masses M_r
print("\nPhi^T K Phi =\n", np.round(Phi.T @ K @ Phi, 1)) # diagonal = wn^2 * M_rPhi^T M Phi =
[[ 3.9767 -0. -0. ]
[-0. 4.5249 -0. ]
[-0. -0. 36.3132]]
Phi^T K Phi =
[[ 643. 0. 0. ]
[ 0. 4237.6 -0. ]
[ 0. 0. 69060.1]]
Both products come out diagonal, zero off the diagonal (the orthogonality), with the modal masses on one and on the other. This orthogonality is the whole engine of modal analysis: it is what lets us collapse the coupled system into three separate scalar equations.
Before trusting the shapes, let us see them. We plot each mode shape against floor height, anchoring the ground at zero, so the building’s deflected silhouette is read off the page.
heights = np.arange(n + 1) # ground = 0, floors 1..n
fig, axes = plt.subplots(1, n, figsize=(8.4, 3.6), sharey=True)
for r, ax in enumerate(axes):
shape = np.concatenate([[0.0], Phi[:, r]]) # pin the ground (0); roof entry = 1
ax.plot(shape, heights, "-o", color=sd.PLT[r], lw=2.4, ms=7)
ax.axvline(0, color="#9aa3ab", lw=1.0)
ax.set_title(rf"mode {r+1}" "\n" rf"$T_{{{r+1}}} = {Tn[r]:.2f}$ s")
ax.set_xlabel(r"$\phi$")
mx = 1.25 * np.max(np.abs(shape)) # per-mode scale (roof-norm spans vary)
ax.set_xlim(-mx, mx)
axes[0].set_ylabel("floor")
axes[0].set_yticks(heights)
fig.tight_layout()
plt.show()

Figure 3:The three natural mode shapes of the building, plotted against floor height with the ground pinned at zero, normalized to unit roof displacement and drawn on separate horizontal scales.
The fundamental mode in Figure 3 is what you picture when you imagine a building swaying: every floor moves the same direction, the roof furthest. Mode 2 crosses zero once and mode 3 twice: the higher modes are the finer, faster corrections. For an earthquake, the first mode usually does most of the work, a fact we will make quantitative in a moment.
Cross-check the frequencies with OpenSeesPy
The eigenfrequencies are easy to verify with an independent program. We build
the same shear-building chain in OpenSeesPy, n mass nodes linked to each other
and to the fixed base by Elastic zero-length springs of stiffness , and
call ops.eigen. For a small dense system the -fullGenLapack solver is the
right choice, because the default ARPACK solver can only return fewer modes than
there are DOFs. The frequencies match scipy.linalg.eigh to machine precision,
as they must, because both programs solve (6).
import openseespy.opensees as ops
ops.wipe()
ops.logFile('opensees.log', '-noEcho') # keep the solver banner out of the output
ops.model('basic', '-ndm', 1, '-ndf', 1)
ops.node(0, 0.0); ops.fix(0, 1) # fixed base
for i in range(n):
ops.node(i + 1, 0.0)
ops.mass(i + 1, float(masses[i]))
for i in range(n): # story springs in a chain
ops.uniaxialMaterial('Elastic', i + 1, float(ks[i]))
ops.element('zeroLength', i + 1, i, i + 1, '-mat', i + 1, '-dir', 1)
lam = ops.eigen('-fullGenLapack', n) # eigenvalues = wn^2
wn_ops = np.sqrt(np.array(lam))
print("wn (scipy) =", np.round(wn, 4))
print("wn (OpenSees) =", np.round(wn_ops, 4))
print("max relative difference =", np.max(np.abs(wn_ops - wn) / wn))wn (scipy) = [12.7163 30.6024 43.6095]
wn (OpenSees) = [12.7163 30.6024 43.6095]
max relative difference = 1.3969166806936946e-16
3Each mode is an SDOF¶
Here is the idea the whole chapter turns on, previewed in Figure 4 before we derive it. At the instant of its peak roof displacement under the synthetic earthquake record that we apply later in the chapter, the building’s deformed shape is the sum of three modal shapes. The first mode supplies -22.4 mm of the -23.0 mm at the roof, the second -0.58 mm and the third +0.03 mm. Each modal shape moves in time as the response of its own SDOF oscillator, which has the mode’s period and feels the ground motion scaled by a factor that we derive below.
Figure 4:The deformed shape at the instant of peak roof displacement as the sum of three modal shapes, each the response of an SDOF oscillator with its own period and participation factor , with modes 2 and 3 drawn 5 and 50 times larger.
The mode shapes form a basis: any motion of the building, however complicated, can be written as a weighted sum of the fixed mode shapes, with time-varying weights called modal coordinates:
Substitute this into the MDOF equation (3); since is a constant matrix, and , so
This is still fully coupled, so we premultiply every term by and watch orthogonality do its work:
The two structural triple products are precisely the orthogonality results (8) we just proved: and . For the damping term we assume the damping matrix is built so that is diagonal too. This is classical (modal) damping (Caughey, 1960), the natural MDOF generalization of a single , and we write its -th diagonal entry as so each mode carries its own damping ratio (we construct exactly such a later). With all three matrices diagonal, (11) no longer mixes the modal coordinates at all: row reads . Dividing each row through by its modal mass leaves independent scalar equations, one per mode:
where is the -th entry of the modal force vector and the modal mass. This is already the punchline: each obeys a unit-mass SDOF equation of frequency and damping , the very oscillator of Chapters 1 to 3, driven by the modal force per unit modal mass.
For an earthquake the right-hand side takes a particularly clean form. As in Chapter 6, base shaking enters every floor as an inertial effective force. With all floors dragged by the same ground acceleration, the load vector is , where is the influence vector, which marks the DOFs that the ground motion drives (here, all of them). The -th modal force is then , and dividing through by the modal mass puts (12) in its standard earthquake form
Equation (13) is, letter for letter, the normalized SDOF earthquake equation from Chapter 6: a unit-mass oscillator of frequency and damping , driven by the ground motion scaled by a single number. That number, the participation factor , measures how strongly the ground motion excites mode . It is large for modes whose shape resembles the rigid sideways push the earthquake delivers, and small (even zero) for modes nearly orthogonal to it. The denominator is the modal mass printed above, which is not 1 for our roof-normalized modes, so keeps its full ratio form. Unlike the response, depends on how the mode is scaled: multiplying by a factor multiplies the numerator by and by , so and are divided by while the physical response is unchanged.
ones = np.ones(n) # the influence vector (all floors pushed)
zeta = 0.05 # 5% damping, assumed equal in every mode
L = Phi.T @ M @ ones # modal excitation factors L_r = phi_r^T M 1
Gamma = L / Mr # participation factors Gamma_r = L_r / M_r
for r in range(n):
print(f"mode {r+1}: L_r = {L[r]:+6.2f} M_r = {Mr[r]:5.2f} t "
f"Gamma = {Gamma[r]:+.3f}")mode 1: L_r = +5.25 M_r = 3.98 t Gamma = +1.321
mode 2: L_r = -1.86 M_r = 4.52 t Gamma = -0.411
mode 3: L_r = +3.27 M_r = 36.31 t Gamma = +0.090
How much of the building does each mode actually represent? The effective modal mass answers that: it is the portion of the total mass that mode mobilizes in an earthquake, and (unlike on its own) it is the same number whatever scaling we picked for the modes. Its sum across all modes is exactly the total building mass, by the orthogonality bookkeeping again. Expanding the influence vector in the mode basis, , and sandwiching gives , whose left side is the total mass . This is the number that tells us, in advance, how few modes we can get away with.
Meff = Gamma**2 * Mr # effective modal mass M*_r = Gamma_r^2 M_r (t)
for r in range(n):
print(f"mode {r+1}: effective mass = {Meff[r]:.3f} t "
f"= {100*Meff[r]/masses.sum():4.1f} % of total")
print(f"\nsum of effective masses = {Meff.sum():.3f} t "
f"(total building mass = {masses.sum():.3f} t)")mode 1: effective mass = 6.940 t = 86.7 % of total
mode 2: effective mass = 0.765 t = 9.6 % of total
mode 3: effective mass = 0.295 t = 3.7 % of total
sum of effective masses = 8.000 t (total building mass = 8.000 t)
The first mode alone carries about 87 % of the building’s mass; the first two together exceed 96 %. Already we can guess that two modes, perhaps even one, will reproduce the roof motion, and the next section tests that guess by solving the modal equations. First, Example 1 works through the same quantities by hand for a smaller building, where the eigenvalue problem reduces to a quadratic.
The next cell repeats Example 1 with eigh and prints every
number quoted in it.
# Two-story shear building of ex-ch08-two-story: equal masses and equal story stiffnesses.
m_ex, k_ex = 2.0, 1000.0 # t, kN/m
M_ex = m_ex * np.eye(2)
K_ex = np.array([[2 * k_ex, -k_ex], [-k_ex, k_ex]])
w2_ex, Phi_ex = eigh(K_ex, M_ex)
Phi_ex = Phi_ex / Phi_ex[-1, :] # unit roof component
Mr_ex = np.diag(Phi_ex.T @ M_ex @ Phi_ex)
Gamma_ex = (Phi_ex.T @ M_ex @ np.ones(2)) / Mr_ex
Meff_ex = Gamma_ex**2 * Mr_ex
for r in range(2):
w_ex = np.sqrt(w2_ex[r])
print(f"mode {r+1}: wn = {w_ex:.2f} rad/s Tn = {2*np.pi/w_ex:.3f} s "
f"phi = [{Phi_ex[0, r]:+.3f}, {Phi_ex[1, r]:+.3f}] M_r = {Mr_ex[r]:.3f} t")
print(f" Gamma = {Gamma_ex[r]:+.3f} effective mass = {Meff_ex[r]:.2f} t "
f"({100*Meff_ex[r]/M_ex.trace():.1f} % of the total)")mode 1: wn = 13.82 rad/s Tn = 0.455 s phi = [+0.618, +1.000] M_r = 2.764 t
Gamma = +1.171 effective mass = 3.79 t (94.7 % of the total)
mode 2: wn = 36.18 rad/s Tn = 0.174 s phi = [-1.618, +1.000] M_r = 7.236 t
Gamma = -0.171 effective mass = 0.21 t (5.3 % of the total)
4Solving the modal oscillators and recombining¶
Every modal equation (13) is an SDOF with unit mass ,
stiffness , damping , and applied force
. So we hand each one to the very same solver
we have used since Chapter 3 (sd.sdof_response), loop over the three modes, and
collect the modal coordinates . We drive the building with the synthetic
record sd.demo_record().
t, ag = sd.demo_record() # ground acceleration (m/s^2), uniform dt
dt = t[1] - t[0]
# Solve each modal SDOF with the Chapter-3 engine. m_r = 1, k_r = wr^2, c_r = 2 zeta wr.
Q = np.zeros((t.size, n))
for r in range(n):
kr = wn[r]**2
cr = 2 * zeta * wn[r]
p_r = -Gamma[r] * ag # = -Gamma_r * m_r * ag, with m_r = 1
_, qr, _, _ = sd.sdof_response(1.0, cr, kr, p_r, dt, method="newmark")
Q[:, r] = qr
# Recombine the physical response: u = Phi q.
U_modal = (Phi @ Q.T).T # shape (N, n): columns are floor displacements
roof_modal = U_modal[:, -1]
print(f"roof peak displacement (modal sum) = {np.max(np.abs(roof_modal))*1000:.1f} mm")roof peak displacement (modal sum) = 23.0 mm
To prove the modal sum is right, we need something to compare it against: a direct integration of the full coupled building, treating (3) as one system without ever mentioning modes. We write a compact matrix Newmark: it is the scalar average-acceleration scheme from Chapter 3 with every coefficient promoted to a matrix and the division by the effective stiffness replaced by its matrix inverse, computed once.
def mdof_newmark(M, C, K, P, dt, gamma=0.5, beta=0.25):
"""Average-acceleration Newmark for M u'' + C u' + K u = P(t).
P has shape (N, n); returns the displacement history u of the same shape."""
N, n = P.shape
u = np.zeros((N, n)); v = np.zeros((N, n)); a = np.zeros((N, n))
a[0] = np.linalg.solve(M, P[0] - C @ v[0] - K @ u[0])
a1 = M / (beta * dt**2) + C * (gamma / (beta * dt))
a2 = M / (beta * dt) + C * (gamma / beta - 1.0)
a3 = M * (1.0 / (2 * beta) - 1.0) + C * dt * (gamma / (2 * beta) - 1.0)
Khat_inv = np.linalg.inv(K + a1) # effective stiffness, inverted once
for i in range(N - 1):
phat = P[i + 1] + a1 @ u[i] + a2 @ v[i] + a3 @ a[i]
u[i + 1] = Khat_inv @ phat
v[i + 1] = (gamma / (beta * dt)) * (u[i + 1] - u[i]) \
+ (1 - gamma / beta) * v[i] + dt * (1 - gamma / (2 * beta)) * a[i]
a[i + 1] = (1.0 / (beta * dt**2)) * (u[i + 1] - u[i]) \
- (1.0 / (beta * dt)) * v[i] - (1.0 / (2 * beta) - 1.0) * a[i]
return uThe direct solver needs an actual damping matrix . We build the one that is consistent with our modal assumption of in every mode, classical (modal) damping, by assembling it from the modes themselves: . Sandwiching it between the modes and using twice collapses it to , exactly the diagonal damping the decoupling (11) assumed (the built into cancels one of the two factors of from the sandwiching ). So the modal decoupling is exact and the two methods must agree.
# Classical damping consistent with zeta in every mode (1/M_r keeps Phi^T C Phi
# at diag(2 zeta wr M_r), matching the decoupling for roof-normalized modes).
C = M @ Phi @ np.diag(2 * zeta * wn / Mr) @ Phi.T @ M
# Effective earthquake force on every floor: P = -(M 1) ag(t).
P = np.outer(-ag, M @ ones) # shape (N, n)
U_direct = mdof_newmark(M, C, K, P, dt)
roof_direct = U_direct[:, -1]
err = np.max(np.abs(U_modal - U_direct)) / np.max(np.abs(U_direct))
print(f"roof peak displacement (direct) = {np.max(np.abs(roof_direct))*1000:.1f} mm")
print(f"max relative difference (modal vs direct) = {err:.2e}")roof peak displacement (direct) = 23.0 mm
max relative difference (modal vs direct) = 1.81e-14
The two solutions agree to about 10-14, machine precision. That is not a coincidence or a good approximation: for a linear system with classical damping, Newmark applied to the modal equations and Newmark applied to the coupled system are algebraically identical. Solving three small SDOFs and adding them up is genuinely the same calculation as integrating the coupled building step by step, as Figure 5 shows.
fig, ax = plt.subplots(figsize=(7.8, 3.2))
ax.plot(t, roof_direct * 1000, color="#9aa3ab", lw=3.2, label="direct MDOF Newmark")
ax.plot(t, roof_modal * 1000, color=sd.PLT[1], lw=1.6, ls="--",
label=r"modal sum $\mathbf{u}=\boldsymbol{\Phi}\mathbf{q}$")
ax.axhline(0, color="#c7ccd1", lw=1.0)
ax.set_xlabel(r"time $t$ (s)")
ax.set_ylabel(r"roof displacement $u_3$ (mm)")
ax.set_xlim(0, t[-1])
ax.legend(loc="upper right")
plt.show()

Figure 5:Roof displacement under the ground motion from a direct Newmark integration of the coupled system (solid gray) and from the three modal SDOFs, solved with the Chapter-3 engine and recombined through (dashed).
5Modal truncation: how few modes are enough¶
We have just done the full calculation with all three modes. But the effective masses warned us that the first mode carries 87 % of the action. Modal truncation is the practical art of keeping only the lowest few modes and throwing the rest away, the reason modal analysis scales to building models with thousands of DOFs, where computing every mode would be wasteful and the lowest handful suffice.
First, look at what each mode contributes to the roof separately. The roof component of mode is , the modal coordinate scaled by how much that mode shows up at the roof.
fig, ax = plt.subplots(figsize=(7.8, 3.2))
for r in range(n):
contrib = Phi[-1, r] * Q[:, r]
peak = np.max(np.abs(contrib)) * 1000
ax.plot(t, contrib * 1000, color=sd.PLT[r], lw=1.8,
label=rf"mode {r+1} (peak {peak:.1f} mm)")
ax.axhline(0, color="#c7ccd1", lw=1.0)
ax.set_xlabel(r"time $t$ (s)")
ax.set_ylabel(r"roof contribution (mm)")
ax.set_xlim(0, t[-1])
ax.legend(loc="upper right")
plt.show()

Figure 6:The individual modal contributions to the roof displacement, : mode 1 in blue, mode 2 in orange, mode 3 in green.
The hierarchy in Figure 6 is stark: mode 1’s roof contribution peaks near 23 mm, mode 2 adds under 3 mm, and mode 3 is a fraction of a millimeter. Now rebuild the roof history with one mode, then two, then all three, and overlay them on the exact answer.
fig, ax = plt.subplots(figsize=(7.8, 3.6))
ax.plot(t, roof_direct * 1000, color="#9aa3ab", lw=3.4, label="all modes (direct)")
styles = ["-", "--", ":"]
for nm in range(1, n + 1):
roof_nm = (Phi[:, :nm] @ Q[:, :nm].T).T[:, -1]
peak = np.max(np.abs(roof_nm)) * 1000
ax.plot(t, roof_nm * 1000, color=sd.PLT[nm - 1], lw=1.8, ls=styles[nm - 1],
label=rf"{nm} mode{'s' if nm > 1 else ''} (peak {peak:.1f} mm)")
ax.axhline(0, color="#c7ccd1", lw=1.0)
ax.set_xlabel(r"time $t$ (s)")
ax.set_ylabel(r"roof displacement $u_3$ (mm)")
ax.set_xlim(0, t[-1])
ax.legend(loc="lower left", bbox_to_anchor=(0.0, 1.0), ncol=2, frameon=False)
plt.show()

Figure 7:The roof displacement reconstructed from a growing number of modes: one mode (blue), two (orange), and all three (green), overlaid on the direct integration (gray).
# Roof peak and largest miss over the record for one, two, and three modes.
peak_all = np.max(np.abs(roof_direct))
for nm in range(1, n + 1):
roof_nm = (Phi[:, :nm] @ Q[:, :nm].T).T[:, -1]
pk = np.max(np.abs(roof_nm))
print(f"{nm} mode{'s' if nm > 1 else ' '}: roof peak {pk*1000:.1f} mm (off by {abs(pk / peak_all - 1):.1%})"
f" largest miss {np.max(np.abs(roof_nm - roof_direct))*1000:.2f} mm")1 mode : roof peak 23.1 mm (off by 0.7%) largest miss 2.28 mm
2 modes: roof peak 23.0 mm (off by 0.2%) largest miss 0.17 mm
3 modes: roof peak 23.0 mm (off by 0.0%) largest miss 0.00 mm
The one-mode curve in Figure 7 gets the roof peak within 0.7 %, although at other instants it misses the roof displacement by up to 2.3 mm, and the two-mode curve is visually exact. The third mode, with under 4 % of the mass, never moves the roof by more than 0.2 mm. This is why a design office can analyze a forty-story tower with a handful of modes: the lowest modes hold most of the mass, and the rest add little to the displacements, although they matter more for story shears and floor accelerations. Seismic codes formalize this with a rule of thumb: include enough modes for their effective masses to add up to at least 90 % of the total mass, which here means two modes, as the picture confirms.
▶ Interactive: the building swaying, split into mode 1 and the rest
The timeline covers three seconds of strong shaking, from 4 to 7 s: ▶ plays them at a quarter of real speed, and the step buttons move one sample (0.02 s) at a time. On the left the building sways with its displacements magnified, its columns in blue and the mode-1 part of the motion as a dashed orange outline. The profile beside it plots the floor displacements: the total (blue), the mode-1 part (orange), and the part from modes 2 and 3 (green). Below, the roof history fills in across the shaded window, with the part from modes 2 and 3 in green. The note splits the roof displacement into the two parts.
Pause at 5.34 s, the instant of the peak: the roof is at -23.0 mm, of which mode 1 supplies -22.4 mm, so the blue and orange shapes almost coincide. At 5.08 s modes 2 and 3 reach their largest share at the roof, -2.28 mm of a total of +15.9 mm, and the blue shape bends visibly away from the orange one. Through most of the window the green shape stays close to the vertical axis, which is the truncation result of Figure 7 seen one instant at a time.
6The whole building in OpenSees¶
We built the modal machinery by hand to understand it. In day-to-day practice you would instead hand the whole building to a finite-element program and let it integrate the coupled system directly, and we now do exactly that in OpenSeesPy and check it against everything above. The model is the shear-building chain from the eigen cross-check; the only two new ingredients are patterns we have already met:
the ground motion enters through a
UniformExcitationpattern, exactly as in Chapter 6, now shaking every floor at once;damping is set with
modalDamping, which applies our chosen to every mode, the OpenSees way of asking for the classical damping the decoupling (11) assumed.
import openseespy.opensees as ops
def opensees_building(masses, ks, zeta, ag, dt):
"""Full MDOF earthquake response history in OpenSees."""
n = masses.size
ops.wipe(); ops.logFile('opensees.log', '-noEcho')
ops.model('basic', '-ndm', 1, '-ndf', 1)
ops.node(0, 0.0); ops.fix(0, 1) # fixed base
for i in range(n):
ops.node(i + 1, 0.0); ops.mass(i + 1, float(masses[i]))
for i in range(n): # story springs in a chain
ops.uniaxialMaterial('Elastic', i + 1, float(ks[i]))
ops.element('zeroLength', i + 1, i, i + 1, '-mat', i + 1, '-dir', 1)
ops.eigen('-fullGenLapack', n) # modes, so modalDamping can use them
ops.modalDamping(zeta) # zeta in every mode (classical damping)
ops.timeSeries('Path', 1, '-dt', dt, '-values', *map(float, ag))
ops.pattern('UniformExcitation', 1, 1, '-accel', 1) # shake every floor by ag(t)
ops.constraints('Transformation'); ops.numberer('Plain'); ops.system('BandGeneral')
ops.test('NormDispIncr', 1e-10, 50); ops.algorithm('Newton')
ops.integrator('Newmark', 0.5, 0.25); ops.analysis('Transient')
U = np.zeros((ag.size, n))
for i in range(ag.size - 1):
ops.analyze(1, dt)
U[i + 1] = [ops.nodeDisp(j + 1, 1) for j in range(n)]
return U
U_ops = opensees_building(masses, ks, zeta, ag, dt)
err_ops = np.max(np.abs(U_ops - U_direct)) / np.max(np.abs(U_direct))
print(f"roof peak displacement (OpenSees) = {np.max(np.abs(U_ops[:, -1]))*1000:.1f} mm")
print(f"max difference vs NumPy direct integration = {err_ops:.2e}")roof peak displacement (OpenSees) = 23.0 mm
max difference vs NumPy direct integration = 8.57e-10
The OpenSees building reproduces our NumPy integration to about 10-9, so
three independent routes (the modal sum, the direct matrix Newmark, and a
production finite-element program) now agree on the same history. The book’s
osdof module packages these lines as osdof.opensees_mdof_ground, ready for
your own scripts. A designer reads two peak profiles off such a run rather than
the whole history: the peak displacement of each floor, and the peak story
drift, the largest difference between the displacements of adjacent floors. The
story drift times the story stiffness is the story shear that the columns carry,
so the drift profile is the one that sets their demands. The next cell extracts
both profiles and confirms that the two engines agree floor by floor.
peak_ops = np.max(np.abs(U_ops), axis=0) * 1000 # peak floor displacement (mm)
peak_dir = np.max(np.abs(U_direct), axis=0) * 1000
# Story drift u_j - u_(j-1), with the ground at zero; its peak over the record (mm).
drift_ops = np.max(np.abs(np.diff(U_ops, axis=1, prepend=0.0)), axis=0) * 1000
drift_dir = np.max(np.abs(np.diff(U_direct, axis=1, prepend=0.0)), axis=0) * 1000
floors = np.arange(1, n + 1)
fig, (axu, axd) = plt.subplots(1, 2, figsize=(8.4, 3.6))
for ax, v_ops, v_dir, xl, yl in ((axu, peak_ops, peak_dir, "peak floor displacement (mm)", "floor"),
(axd, drift_ops, drift_dir, "peak story drift (mm)", "story")):
ax.barh(floors, v_ops, color=sd.PLT[4], height=0.55, label="OpenSees")
ax.plot(v_dir, floors, "o", color=sd.PLT[6], ms=7, label="NumPy direct")
ax.set_yticks(floors); ax.set_ylabel(yl); ax.set_xlabel(xl)
axd.set_xlim(0, 1.25 * drift_ops.max())
axu.legend(loc="lower right")
fig.tight_layout()
plt.show()

Figure 8:Peak floor displacements (left) and peak story drifts (right) from the OpenSees response history (bars), with the NumPy direct integration overlaid (dots).
print("peak floor displacement (mm):", np.round(peak_ops, 1))
print("peak story drift (mm): ", np.round(drift_ops, 1))
print("peak story shear (kN): ", np.round(ks * drift_ops / 1000, 1))peak floor displacement (mm): [ 8.4 17.1 23. ]
peak story drift (mm): [8.4 9. 7.3]
peak story shear (kN): [20.2 16.3 8.7]
The floor displacements grow with height, the roof moving most, as the dominant first mode dictates, but the story drifts do not: the second story drifts most, 9.0 mm, and the top story least, 7.3 mm. The story shears grow downward, from 8.7 kN in the top story to 20.2 kN in the first, because each story carries the inertia forces of all the floors above it.
7The loop, closed¶
Step back and see what just happened in this chapter. We took a building with three coupled degrees of freedom, found its three hidden oscillators by solving one eigenvalue problem, drove each oscillator with the same SDOF engine we built in Chapter 3, and added the answers up to recover the full response, exactly. Then we kept only the first oscillator and still had the roof peak within 0.7 %, and finally let a production finite-element program confirm the whole calculation.
That is the conceptual core of the book, distilled into one chapter. The single oscillator of Chapter 1 was never a toy or a special case: it is the irreducible unit out of which every linear structure is assembled, and modal analysis is the act of taking a structure apart into those units. Everything you learned about one oscillator (its period, its damping, its response spectrum, its resonance) applies to each mode of a linear structure of any size.
That equivalence also has a practical payoff for design. Because each mode is just an SDOF, the response spectrum of Chapter 6 gives a peak demand straight from each modal period, with no response history needed. Codes then reduce the resulting design forces with the ductility-based -factor of Chapter 7, as they do for one oscillator. Turning those two ideas into the procedures a code actually mandates (modal response-spectrum analysis and the equivalent lateral force method) is the subject of Chapter 9, where the same steps turn the modes of a five-story building into its design forces.
8Summary¶
A shear building is an MDOF system: a diagonal mass matrix (1) and a tridiagonal stiffness matrix (2) turn the SDOF equation of motion into its matrix form (3) (Figure 1).
The generalized eigenvalue problem (6) yields the natural frequencies and orthogonal mode shapes (Figure 2), here scaled to a unit roof component (Figure 3);
scipy.linalg.eighand OpenSeesPy agree on the frequencies to machine precision.Writing (9) and using orthogonality decouples the system into independent modal SDOFs (13) (Figure 4), each driven by the ground motion scaled by its participation factor .
Solving the modal SDOFs with the Chapter-3 engine and recombining reproduces a direct MDOF Newmark integration to machine precision (Figure 5), because for classical damping the two calculations are algebraically identical.
Modal truncation keeps only the lowest few modes; the effective modal mass tells you how few. For this building one mode gives the roof peak within 0.7 % and two are indistinguishable from the full answer (Figure 6, Figure 7), which is why modal analysis scales to the largest structures.
The whole building also runs in OpenSeesPy in a few lines, with
UniformExcitationfor the ground motion andmodalDampingfor in every mode. It reproduces the NumPy solutions to about 10-9 and hands back the peak floor displacements and story drifts (Figure 8), and the story drifts set the demands on the columns.