Vector calculus: fields, line integrals and integral theorems
Vector fields, work and flux, divergence and curl, and the theorems relating behavior inside a region to behavior on its boundary (Green, Gauss and Stokes). Special attention is paid to what recurs in generative AI: score fields as conservative fields, divergence as a flow's expansion rate, and multivariable integration by parts underlying score matching.
After this lesson you can
- Compute line and flux integrals of vector fields in the plane and in space.
- Decide whether a field is conservative, construct its potential and explain the role of simple connectivity.
- Interpret divergence and curl as densities of expansion and rotation, and calculate them.
- State, numerically verify and apply Green's, divergence and Stokes' theorems.
- Derive multivariable integration by parts and Hyvärinen's score matching identity.
Before you start
Motivation: an arrow at every point
Until now, a multivariable function gave a number at each point and its gradient gave an arrow. In this lesson the arrow is the main object: a rule assigning a vector to each point . It appears in three places that matter to you.
- Velocities. At each point of a fluid, the velocity of a particle passing through is a vector. The field answers questions like how much fluid crosses a wall or whether a drop of ink disperses or concentrates.
- Scores. A diffusion-based generative model does not store a density : it learns field , pointing in the direction of fastest density increase. Generating an image means releasing a particle and following this field with a little noise. This arrow does not depend on the normalization constant of , so it can be learned without knowing it.
- Artificial potentials. A navigating robot can define a potential with a minimum at the goal and hills over obstacles, and move following field . The field coming from a potential guarantees that the robot always descends and never circles.
Three questions organize what follows. When does a field come from a potential? This decides whether work between two points depends on the path. What does divergence measure? How much what the field carries expands or contracts. And the deepest: how does what happens inside a region relate to what happens on its boundary? Green’s, divergence and Stokes’ theorems answer the same way in three forms: an integral of a derivative inside is an integral of the field on the boundary. This is the one-variable fundamental theorem of calculus raised to several variables. Finally we use it to prove Hyvärinen’s identity, turning score training into a problem solvable without knowing the true score.
Vector fields and flow lines
An integral curve is the trajectory of a particle carried by the field, hence the name flow line. If is of class , existence and uniqueness of ODE solutions (proved in lesson 16) give exactly one through each point, so flow lines fill the domain without crossing.
The field has an important distinction from scalar functions. Its Jacobian matrix is square and, like every square matrix, splits into symmetric and skew-symmetric parts. Each has geometric meaning: one describes how distances stretch and compress near , the other how the neighborhood rotates. In the next interactive you can see this before defining it.
These three ingredients already reveal the two local quantities that matter. Divergence measures the relative rate of volume change of a piece of matter (what the drop does to its area). Curl measures rotation (what the wheels do). Scores only contract or expand: they do not rotate. This is not an accident of the chosen mixture, but a consequence of a score being a gradient, which we will prove.
Line integrals: work along a curve
If a particle moves along a curve while a force field pushes it, work is the sum of the force component in the direction of motion times distance traveled. Dividing the curve into small steps and summing yields a Riemann sum converging to an integral.
Proof
By the chain rule, . Then is, by the change of variable , equal to . If increases, and : this is the original integral. If it decreases, the bounds are swapped and the sign changes.
∎Thus the line integral depends on the curve as a set and its orientation, but not the speed at which it is traversed. Two concrete cases clarify.
One final result used constantly for bounds: , with the curve length (Cauchy–Schwarz inequality in the integrand).
Conservative fields: when the path does not matter
The second example suggests a question. What does have that does not? The first is the gradient of .
Proof
On each smooth segment, by the chain rule, . Thus the integrand is the derivative of , and the fundamental theorem of calculus gives the difference in endpoint values. Adding segments cancels intermediate values in a chain.
∎Only endpoint behavior matters in this result. The converse also holds, turning the property into a characterization.
Proof
(1) (2) is the previous theorem. (2) (3): a closed curve is the union of a path from to and another, , from to ; circulation is (minus sign from reversing orientation) and vanishes if and only if the two paths from to agree. (2) (1): fix and define by any path (one exists because an open connected set is polygonally connected). To compute , travel to and append the straight segment to :
when , by continuity of . Thus , and the partial derivatives are continuous, so .
∎A testable criterion: symmetric Jacobian
Checking path independence requires testing every path. A local condition can be checked with derivatives. If with , then by Schwarz’s theorem: the Jacobian of (the Hessian of ) is symmetric. In the condition is one equation, , and in there are three, grouped into (defined next section).
Is it sufficient? It depends on the domain. When the domain is a ball, rectangle or all , yes:
Proof
Write and . Differentiating under the integral sign (Leibniz’s rule; everything is continuous on ),
By symmetry, , and by the chain rule. The bracket becomes , whose integral from to is .
∎The theorem’s formula is also an algorithm: to construct a potential integrate along a ray. By hand it is often faster to integrate component by component. With , integrating with respect to gives ; differentiating with respect to gives , hence ; differentiating with respect to gives , hence . The potential is up to a constant, and work from to is regardless of path.
The vortex: zero curl without a potential
The local condition ceases to suffice if the domain has a hole. Consider the vortex field
Compute : the condition holds throughout the domain. But its circulation around the unit circle is . By the characterization theorem, it has no potential on the punctured plane. What fails? Locally it is a gradient: with the polar angle. But is not a function on the punctured plane: after a circuit around the origin it increases by . Work along a path is the change in angle, and two paths from to passing opposite sides of the origin differ by one full turn.
What matters is not the hole’s size but that the loop formed by the two paths encircles it: the difference is times the loop’s winding number around the origin. This is topology’s first appearance in calculus: the domain is part of the statement. The right condition is a simply connected domain (every closed curve can be contracted to a point without leaving it), like a ball or all ; then a symmetric Jacobian does imply a potential. We will not prove that generalization of Poincaré’s lemma here; the star-shaped version proved above covers all domains we use. In minus a point, zero curl does suffice (the sphere is simply connected), but in minus a line the vortex remains a counterexample.
What this has to do with generative models
A score is conservative by construction, with potential , so its Jacobian, the Hessian of , is symmetric. An arbitrary network , in contrast, has an arbitrary Jacobian and is not generally a gradient; it must be parametrized as to be one. Similarly, a navigation field has no loops: follow its flow lines downward and decreases strictly, while a field with rotational component can make the robot traverse a closed orbit.
Divergence and curl
A field’s Jacobian decomposes as with symmetric and skew-symmetric. With linearization , near the neighborhood deforms as follows: stretches and compresses it along its eigenvectors, and rotates it as a rigid body. Two numbers summarize the parts that cannot be hidden:
Both are the parts of the Jacobian that interest us. is the sum of stretches along axes; curl components are the three independent entries of , because for every (check entry by entry). Field is infinitesimal rotation of angular velocity : that is why the wheels in the earlier figure turn at half the curl.
| Field | Behavior | ||
|---|---|---|---|
| uniform source | |||
| rigid-body rotation | |||
| (outside origin) | vortex: circles without rotating locally | ||
| (outside origin) | point source, flux | ||
| (score of ) | sink with one rest point |
Two rows deserve attention. The vortex has zero curl yet particles move in circles: curl measures local rotation of a small piece (a small wheel in the flow does not turn because its inner side moves faster than its outer side, compensating), not whether trajectories curve. The point source has zero divergence everywhere it is defined (in , and sum to zero), yet flux leaves it through any closed curve surrounding it. This is the divergence version of the vortex’s hole, seen in the interactive below.
Divergence as expansion rate
Let be the flow of : the map taking each point to its position after time . For small , , whose Jacobian is , and expanding the determinant,
By the change-of-variables formula, the volume of the image of a region changes at rate . Divergence is the density of expansion, confirmed by the magenta drop: at its position. This reappears in continuous flows in generative AI: if a density is transported by , its logarithm along a trajectory evolves as (see instantaneous change of variables and continuous normalizing flows).
Identities inherited from Schwarz
Proof
(1) The first component of is , and the others cancel likewise, all by Schwarz’s theorem. (2) contains six terms canceling in pairs, with , etc. (3) This is the definition. (4) Apply the product rule to each .
∎The first identity is the differential version of what you already know: a gradient has zero curl. The second says a field that is a curl has zero divergence: it neither creates nor destroys volume (these are incompressible or solenoidal fields, like the velocity of an incompressible fluid or a magnetic field). And the third, the Laplacian, is the divergence of the gradient: applied to the score it gives the field’s divergence, , negative near mixture modes (the field converges) and positive between them (the field opens out), as in the red-and-blue map.
Surfaces and flux
The line integral sums the field along a curve. Its analog one dimension higher sums how much field crosses a surface. If parametrizes surface , vectors and are tangent and the cross product is normal to , with norm equal to the area of the parallelogram generated by and : it is the area element, .
Changing parametrization with a diffeomorphism multiplies the cross product by , and the change-of-variables formula compensates: flux is preserved if and changes sign if it is negative (surface orientation is reversed, like curve direction). Every flux integral therefore requires choosing an orientation, normally the outward normal on a closed surface.
In the plane the analog is flux through a curve. If curve is traversed counterclockwise, the outward normal is and flux is . This form converts Green’s theorem into the planar divergence theorem, as we will see. (For a surface that is graph , parametrized by , the cross product is , the upward-pointing normal.)
The integral theorems
A relationship between integrals over a region and its boundary reappears in three disguises. We state them and then prove them using the same ingredient, the fundamental theorem of calculus.
This is the first of the Green and Stokes theorems: they relate circulation along the boundary to curl inside. The second, for surfaces in space, is stated below. The proof for the simplest regions reduces the problem to the fundamental theorem of calculus.
Proof
Suppose with of class (a “type I” region). By Fubini’s theorem and the fundamental theorem of calculus,
Line integral has four segments: lower curve left to right, contributing ; the right side, where ; the upper curve traversed right to left, contributing ; and the left side, also with . Thus . If is also type II, , the same argument with and interchanged gives (now positive orientation traverses the right side upward). Adding gives the theorem.
For any region divisible into regions of both types, apply it to each piece and sum. Circulations along internal cuts are traversed twice in opposite directions and cancel: only the boundary of remains.
∎Green’s planimeter
If you choose , its curl is everywhere and Green says
To measure a plot’s area simply traverse its boundary. This is the principle of the planimeter, the mechanical instrument used before computers. For a polygon with vertices , each straight edge contributes exactly , the signed area of its triangle with the origin: this is the shoelace formula you will implement below.
Three lessons from the figure. First, sign: reversing traversal changes the sign of every line integral and thus area. Second, independence of : graphically, matters only through its curl. Adding any gradient to does not change circulation around a closed curve; , and differ by gradients and give the same area. Third, what the integral really measures: in a self-intersecting curve, each region counts as often as its winding number, with the direction’s sign; in a figure eight with equal opposite lobes the signed area is zero.
Flux form: the divergence theorem
Apply Green to field : its “curl” is and . The result is the same theorem written for flux and generalizes to any dimension.
The proof follows Green’s script. For a region “simple in the direction”, , Fubini and the fundamental theorem give , the flux of component through the top and bottom caps (the side boundary contributes nothing because ). Repeat for each component and axis, and split general regions into pieces. A rigorous proof for general boundaries requires partitions of unity; the mechanism is what matters here.
A consequence gives divergence physical meaning without coordinates: apply the theorem to a small ball and divide by its volume,
the net flux per unit volume. Curl has its own version using circulation around small loops, used in the lab to detect whether an unknown field is a gradient.
Stokes: flux of curl
In space, a field’s curl integrated over a surface gives circulation around its boundary.
Proof
Everything reduces to Green on the parameter domain. Let be the Jacobian of evaluated at . By the chain rule and symmetry (Schwarz),
which by the scalar triple product is : the flux integrand. Then , and by Green applied to on this is .
∎One principle
The four results in this lesson (the fundamental theorem for , Green, Stokes and Gauss) are the same statement: the integral of a derivative over an object is the integral of the original object over its boundary.
| Dimension | Region | Boundary | Statement |
|---|---|---|---|
| 1 | |||
| 1, on a curve | curve from to | ||
| 2 | region | curve | (Green) |
| 2, 3 | surface | curve | (Stokes) |
| region | hypersurface | (Gauss) |
The language of differential forms unifies them as (the generalized Stokes theorem), and the cell figure shows why: an object’s “local” derivative measures its net outflow from an infinitesimal cell, and when cells are added everything leaving one enters its neighbor except at the external boundary. This is the same telescoping cancellation as the fundamental theorem of calculus.
The theorems also explain the domain’s role in the vortex. Stokes applied to a loop with on a surface bounded by it inside the domain gives , proving that in a simply connected domain (where every loop bounds a surface) a curl-free field is conservative. In the punctured plane, the unit circle is not the boundary of any disk lying inside the domain: the origin, where concentrates its “”, is in the way. The same holds for the point source with Gauss.
Integration by parts and score matching
From the product rule and divergence theorem, if and ,
This is integration by parts in and generalizes . With we obtain Green’s identities, , used for instance to prove that the Dirichlet problem for Laplace’s equation has at most one solution. When decays rapidly at infinity, the boundary term vanishes and remains: is the adjoint of . In weak form this lets us differentiate a nondifferentiable function by transferring the derivative to the test function.
Hyvärinen’s identity
Let be an unknown density on from which we have samples, and a model of its score . The natural objective is Fisher divergence,
but it contains , precisely what we want to learn. Integration by parts removes it.
Proof
Expand the square: . Only the cross term needs attention. Since ,
On each ball , integration by parts with and gives . The first term tends to by hypothesis, and the second converges to by dominated convergence, since . Thus .
∎We call the explicit objective (explicit score matching) and the implicit objective (implicit score matching): the identity says . The implicit one contains only the model and expectations under , approximated with samples: . It also does not depend on the normalization constant, because the score of is the same. Three comments.
- Cost. requires the diagonal derivatives of the Jacobian, i.e. backward passes (each a vector-Jacobian product, as in lesson 8). In high dimensions this is prohibitive, motivating score matching with random projections (estimating the trace with random vectors, like randomized trace estimation) and denoising score matching, avoiding the Jacobian entirely. These methods are studied in the score matching lesson.
- Model. The minimizer of is the true score, a gradient. But the objective can be evaluated for any field , conservative or otherwise.
- The boundary hypothesis is real. If has support with a boundary, integration by parts leaves a nonzero term , and the computable objective is no longer the true one. This is the lesson’s final interactive.
The exponential case can be solved by hand. With on the score is , and the exact model is , that is, . The implicit objective with is , with and , and setting its gradient to zero yields : a score rising when it should fall. The difference between the objectives is exactly the boundary term : linear in , shifting the minimum.
Implementation from scratch
We begin with what needs only an integration rule: work of a field along a curve, parametrization independence, and area by the shoelace formula. We use 5-point Gauss–Legendre quadrature on each subinterval, integrating polynomials of degree 9 exactly.
import numpy as np
GL_X, GL_W = np.polynomial.legendre.leggauss(5)
def line_integral(F, gamma, dgamma, a=0.0, b=1.0, n=64):
"""Trabajo de F a lo largo de gamma: integral de F(gamma(t)) . gamma'(t) con Gauss-Legendre compuesta."""
edges = np.linspace(a, b, n + 1)
total = 0.0
for lo, hi in zip(edges[:-1], edges[1:]):
t = 0.5 * (hi - lo) * GL_X + 0.5 * (hi + lo)
total += 0.5 * (hi - lo) * np.dot(GL_W, [F(gamma(ti)) @ dgamma(ti) for ti in t])
return total
def work_polyline(F, pts):
"""Trabajo de F a lo largo de la poligonal que une los puntos de pts, lado a lado."""
pts = np.asarray(pts, float)
total = 0.0
for a, b in zip(pts[:-1], pts[1:]):
t = 0.5 * (GL_X + 1)
total += 0.5 * sum(w * (F(a + ti * (b - a)) @ (b - a)) for w, ti in zip(GL_W, t))
return total
def shoelace_area(poly):
"""Área con signo de un polígono cerrado: (1/2) sum (x_i y_{i+1} - x_{i+1} y_i)."""
p = np.asarray(poly, float)
q = np.roll(p, -1, axis=0)
return 0.5 * np.sum(p[:, 0] * q[:, 1] - q[:, 0] * p[:, 1])
giro = lambda p: np.array([-p[1], p[0]])
circ = lambda t: np.array([np.cos(2 * np.pi * t), np.sin(2 * np.pi * t)])
dcirc = lambda t: 2 * np.pi * np.array([-np.sin(2 * np.pi * t), np.cos(2 * np.pi * t)])
print("circulación de (-y, x) por la circunferencia unidad:", line_integral(giro, circ, dcirc))
print("con la parametrización t -> t^2: ", line_integral(giro, lambda t: circ(t**2), lambda t: 2 * t * dcirc(t**2)))
print("recorrida al revés: ", line_integral(giro, lambda t: circ(1 - t), lambda t: -dcirc(1 - t)))
# un gradiente, F = (2xy, x^2) con potencial x^2 y: cuatro caminos de (0,0) a (1,2)
F = lambda p: np.array([2 * p[0] * p[1], p[0] ** 2])
parab, dparab = (lambda t: np.array([t, 2 * t**2])), (lambda t: np.array([1.0, 4 * t]))
ondul = lambda t: np.array([t, 2 * t + 0.5 * np.sin(6 * np.pi * t)])
dondul = lambda t: np.array([1.0, 2 + 3 * np.pi * np.cos(6 * np.pi * t)])
print("\ngradiente: rectángulo, recta, parábola, ondulado:",
work_polyline(F, [(0, 0), (0, 2), (1, 2)]), work_polyline(F, [(0, 0), (1, 2)]),
line_integral(F, parab, dparab), line_integral(F, ondul, dondul), " f(B) - f(A) = 2")
print("giro (-y, x): recta y rectángulo:", work_polyline(giro, [(0, 0), (1, 2)]), work_polyline(giro, [(0, 0), (0, 2), (1, 2)]))
# Green: el área de un polígono estrellado aleatorio, como cordón y como circulación de (-y/2, x/2)
rng = np.random.default_rng(3)
ang = np.sort(rng.uniform(0, 2 * np.pi, 12)); rad = rng.uniform(0.6, 1.6, 12)
P = np.c_[rad * np.cos(ang), rad * np.sin(ang)]
verde = lambda p: 0.5 * np.array([-p[1], p[0]])
print("\nárea por el cordón:", shoelace_area(P), " circulación de (-y/2, x/2):", work_polyline(verde, np.vstack([P, P[:1]])))
print("en sentido horario:", shoelace_area(P[::-1]))
from matplotlib.path import Path
pts = rng.uniform(-1.6, 1.6, (400000, 2))
print("Monte Carlo con 400000 puntos:", Path(P).contains_points(pts).mean() * 3.2**2)Work of rotation around the circle is to the last displayed digit, unchanged by reparametrizing with and changing sign when traversal is reversed, as the theorem says. The gradient gives (the potential difference) along all four paths, including one oscillating and moving backward vertically, and rotation gives and along the first two. A random polygon’s area agrees by shoelace and circulation of , and matches Monte Carlo point counting within statistical error (with 400,000 points, the estimator’s standard deviation is about ).
Now divergence and curl on a grid by centered differences, the divergence theorem checked numerically on a square and a circle, circulation around small loops as a gradient detector, and flux through spatial surfaces using the cross product.
import numpy as np
def div_curl(Fx, Fy, h):
"""Divergencia y rotacional escalar de un campo en rejilla Fx[j, i] = Fx(x_i, y_j), por diferencias centradas."""
dFx_dx = (Fx[1:-1, 2:] - Fx[1:-1, :-2]) / (2 * h)
dFy_dy = (Fy[2:, 1:-1] - Fy[:-2, 1:-1]) / (2 * h)
dFy_dx = (Fy[1:-1, 2:] - Fy[1:-1, :-2]) / (2 * h)
dFx_dy = (Fx[2:, 1:-1] - Fx[:-2, 1:-1]) / (2 * h)
return dFx_dx + dFy_dy, dFy_dx - dFx_dy
campo = lambda p: np.array([p[0]**2 + p[1] * np.sin(p[0]), p[0] * p[1]**2 - np.cos(p[0]) + p[1]**3])
div_exacta = lambda x, y: 2 * x + y * np.cos(x) + 2 * x * y + 3 * y**2
rot_exacto = lambda x, y: y**2
h = 0.01
x = -2 + h / 2 + h * np.arange(400) # centros de celda: las fronteras caen entre celdas
X, Y = np.meshgrid(x, x) # X[j, i] = x_i, Y[j, i] = y_j
Fx, Fy = campo((X, Y))
div, rot = div_curl(Fx, Fy, h)
Xi, Yi = X[1:-1, 1:-1], Y[1:-1, 1:-1]
print("error máximo de la divergencia:", np.abs(div - div_exacta(Xi, Yi)).max())
print("error máximo del rotacional: ", np.abs(rot - rot_exacto(Xi, Yi)).max())
# rot(grad f) = 0 en la rejilla: el gradiente de una función suave arbitraria no gira
f = np.sin(X) * np.exp(Y) + X * Y**2
gx, gy = np.gradient(f, h, axis=1), np.gradient(f, h, axis=0)
print("máx |rot grad f| (np.gradient):", np.abs(div_curl(gx, gy, h)[1]).max(), " frente a máx |rot| del campo:", np.abs(rot).max())
def flux_polygon(F, poly, n=5):
"""Flujo saliente de F por el borde de un polígono antihorario: integral de F_x dy - F_y dx."""
gx_, gw_ = np.polynomial.legendre.leggauss(n)
p = np.asarray(poly, float)
total = 0.0
for a, b in zip(p, np.roll(p, -1, axis=0)):
d = b - a
for w, xi in zip(gw_, gx_):
Fq = F(a + 0.5 * (xi + 1) * d)
total += 0.5 * w * (Fq[0] * d[1] - Fq[1] * d[0])
return total
full = np.zeros_like(X); full[1:-1, 1:-1] = div
cuadrado = [(-1, 0), (1, 0), (1, 1.5), (-1, 1.5)]
dentro = (np.abs(X) < 1) & (Y > 0) & (Y < 1.5)
print("\ncuadrado: flujo por el borde =", flux_polygon(campo, cuadrado), " suma de div sobre las celdas =", full[dentro].sum() * h**2)
t = np.linspace(0, 2 * np.pi, 2000, endpoint=False)
disco = np.c_[0.3 + np.cos(t), 0.2 + np.sin(t)]
dentro = (X - 0.3)**2 + (Y - 0.2)**2 < 1
print("disco: flujo por el borde =", flux_polygon(campo, disco), " suma de div sobre las celdas =", full[dentro].sum() * h**2)
fuente = lambda p: p / (p @ p)
print("\nfuente puntual (x, y)/r^2: flujo por el círculo unidad =", flux_polygon(fuente, np.c_[np.cos(t), np.sin(t)]),
" por un cuadrado que no la contiene =", round(flux_polygon(fuente, [(1, 1), (3, 1), (3, 3), (1, 3)]), 6))
# ¿es un gradiente? Circulación por lazos pequeños dividida por su área: tiende a rot F en el centro
def rot_por_lazo(F, c, r=1e-3):
"""Circulación de F por el cuadrado de lado 2r centrado en c, dividida por su área."""
sq = np.asarray(c) + r * np.array([(-1, -1), (1, -1), (1, 1), (-1, 1)])
girado = lambda p: (lambda v: np.array([v[1], -v[0]]))(F(p)) # flujo de (F_y, -F_x) = circulación de F
return flux_polygon(girado, sq) / (2 * r) ** 2
caja_negra = {
"gradiente de sin(x) e^y + x y^2": lambda p: np.array([np.cos(p[0]) * np.exp(p[1]) + p[1]**2, np.sin(p[0]) * np.exp(p[1]) + 2 * p[0] * p[1]]),
"campo de la rejilla (rot = y^2)": campo,
"vórtice (-y, x)/r^2": lambda p: np.array([-p[1], p[0]]) / (p @ p),
}
centros = np.random.default_rng(1).uniform(-1.5, 1.5, (200, 2))
centros = centros[np.linalg.norm(centros, axis=1) > 0.2]
print()
for nombre, G in caja_negra.items():
print(f"máx |circulación / área| en {len(centros)} lazos, {nombre}:", max(abs(rot_por_lazo(G, c)) for c in centros))
# flujo por superficies del espacio y el teorema de Stokes
GX, GW = np.polynomial.legendre.leggauss(5)
def surface_flux(F, r, ru, rv, u_range, v_range, n=6):
"""Flujo de F por la superficie r(u, v): integral doble de F . (r_u x r_v), Gauss-Legendre en cada celda."""
us, vs = np.linspace(*u_range, n + 1), np.linspace(*v_range, n + 1)
total = 0.0
for u0, u1 in zip(us[:-1], us[1:]):
for v0, v1 in zip(vs[:-1], vs[1:]):
for wi, xi in zip(GW, GX):
for wj, xj in zip(GW, GX):
u, v = 0.5 * (u1 - u0) * xi + 0.5 * (u1 + u0), 0.5 * (v1 - v0) * xj + 0.5 * (v1 + v0)
total += wi * wj * 0.25 * (u1 - u0) * (v1 - v0) * (F(r(u, v)) @ np.cross(ru(u, v), rv(u, v)))
return total
r_esf = lambda t, p: np.array([np.sin(t) * np.cos(p), np.sin(t) * np.sin(p), np.cos(t)])
r_t = lambda t, p: np.array([np.cos(t) * np.cos(p), np.cos(t) * np.sin(p), -np.sin(t)])
r_p = lambda t, p: np.array([-np.sin(t) * np.sin(p), np.sin(t) * np.cos(p), 0.0])
print("\nflujo de (x, y, z) por la esfera unidad:", surface_flux(lambda q: q, r_esf, r_t, r_p, (0, np.pi), (0, 2 * np.pi)), " 4 pi =", 4 * np.pi)
# Stokes en el hemisferio superior con F = (z, x, y), rot F = (1, 1, 1)
F3 = lambda q: np.array([q[2], q[0], q[1]])
flujo_rot = surface_flux(lambda q: np.ones(3), r_esf, r_t, r_p, (0, np.pi / 2), (0, 2 * np.pi))
tt = np.linspace(0, 2 * np.pi, 4001)[:-1]
ecuador = sum(F3(np.array([np.cos(s), np.sin(s), 0.0])) @ np.array([-np.sin(s), np.cos(s), 0.0]) for s in tt) * (2 * np.pi / 4000)
print("Stokes, hemisferio: flujo de rot F =", flujo_rot, " circulación por el ecuador =", ecuador)
print("con (phi, theta) intercambiados el flujo cambia de signo:",
surface_flux(lambda q: q, lambda p, t: r_esf(t, p), lambda p, t: r_p(t, p), lambda p, t: r_t(t, p), (0, 2 * np.pi), (0, np.pi)))What the figures say. Centered differences have error (with , on the order of in divergence and in curl), and the curl of a gradient is zero up to rounding because discrete derivative operators commute: Schwarz’s theorem on graph paper. On the square, whose boundary coincides with cell edges, boundary flux and sum of divergence agree up to centered-difference error; on the circle, whose boundary cuts cells, their difference, on the order of , is region discretization error. The point source gives through the circle and zero through a region not containing it (residual of order is quadrature error with a nearby singularity). Small loops separate fields without seeing their formula: circulation per unit area is zero (rounding) for the gradient and reaches for the grid field, whose curl is . But the vortex also passes: small loops not surrounding the origin detect only curl, not holes; for that a large loop is needed. Orientation appears in the last two lines: the flux of through the sphere is and changes sign on swapping parameters, because that reverses .
Finally, one-dimensional score matching. Parametrize the score as a linear combination of basis functions . Then with and , minimized by solving : a linear system with samples. The explicit objective, which in the lab we can calculate because we know , gives .
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
def sample_mix(n):
comp = rng.random(n) < 0.4
return np.where(comp, rng.normal(-1.3, 0.55, n), rng.normal(1.1, 0.8, n))
def true_score(x):
a = 0.4 * np.exp(-0.5 * ((x + 1.3) / 0.55) ** 2) / 0.55
b = 0.6 * np.exp(-0.5 * ((x - 1.1) / 0.8) ** 2) / 0.8
return (a * (-(x + 1.3) / 0.55**2) + b * (-(x - 1.1) / 0.8**2)) / (a + b)
x = sample_mix(20000)
def base(K, w):
"""Funciones base: 1, x y K bumps gaussianos en [-3, 3]; devuelve phi y phi'."""
c = np.linspace(-3, 3, K)
phi = lambda x: np.column_stack([np.ones_like(x), x] + [np.exp(-0.5 * ((x - ci) / w) ** 2) for ci in c])
dphi = lambda x: np.column_stack([np.zeros_like(x), np.ones_like(x)] + [-(x - ci) / w**2 * np.exp(-0.5 * ((x - ci) / w) ** 2) for ci in c])
return phi, dphi
grid = np.linspace(-2.5, 2.5, 500)
fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
ax[0].plot(grid, true_score(grid), "k--", label="score verdadero")
for K in (2, 4, 8, 16):
phi, dphi = base(K, 5.4 / (K - 1))
P, dP = phi(x), dphi(x)
A = P.T @ P / len(x) + 1e-6 * np.eye(P.shape[1])
th_ism = np.linalg.solve(A, -dP.mean(axis=0)) # implícito: sin conocer p
th_esm = np.linalg.solve(A, P.T @ true_score(x) / len(x)) # explícito: usa el score verdadero
e_ism = np.sqrt(np.mean((phi(grid) @ th_ism - true_score(grid)) ** 2))
e_esm = np.sqrt(np.mean((phi(grid) @ th_esm - true_score(grid)) ** 2))
print(f"K = {K:2d} bumps: error del score implícito {e_ism:.3f} explícito {e_esm:.3f}")
if K in (4, 16):
ax[0].plot(grid, phi(grid) @ th_ism, label=f"implícito, K = {K}")
ax[0].set_xlabel("x"); ax[0].set_title("score aprendido sin conocer p"); ax[0].legend(fontsize=8)
ax[1].hist(x, bins=60, density=True, color="C0", alpha=0.5); ax[1].set_title("muestras de p"); ax[1].set_xlabel("x")
plt.tight_layout(); plt.show()
# familia gaussiana: s(x) = th0 + th1 x. El score matching coincide con la máxima verosimilitud
P1, dP1 = np.column_stack([np.ones_like(x), x]), np.column_stack([np.zeros_like(x), np.ones_like(x)])
th = np.linalg.solve(P1.T @ P1 / len(x), -dP1.mean(axis=0))
print("\nscore matching lineal: mu =", -th[0] / th[1], " sigma^2 =", -1 / th[1])
print("máxima verosimilitud gaussiana: mu =", x.mean(), " sigma^2 =", x.var())
# datos con frontera: Exp(1) en [0, inf). La integración por partes deja un término de frontera
e = rng.exponential(1.0, 20000)
Pe = np.column_stack([np.ones_like(e), e]); dPe = np.column_stack([np.zeros_like(e), np.ones_like(e)])
th_i = np.linalg.solve(Pe.T @ Pe / len(e), -dPe.mean(axis=0))
th_e = np.linalg.solve(Pe.T @ Pe / len(e), Pe.T @ (-np.ones_like(e)) / len(e))
print("\nExp(1): theta implícito =", np.round(th_i, 3), " theta explícito =", np.round(th_e, 3), " (el verdadero es (-1, 0))")Three observations. With few basis functions, implicit (samples only) and explicit (true score) estimators have practically the same error: the identity works. With 16 bumps, implicit worsens relative to explicit: the price of estimating with 20,000 samples instead of knowing the score, variance increasing with model capacity. For a Gaussian family, score matching agrees with maximum likelihood (sample mean and variance): this is no accident, and an exercise in the score matching lesson explores exponential families. With the exponential, the implicit estimator converges to , not : the boundary term the interactive showed in action.
The library version
All the above exists ready-made. np.gradient calculates centered-difference derivatives (second order inside, first order at boundaries) on nonuniform grids too; scipy.integrate.quad and dblquad integrate with error control; and sympy checks this chapter’s identities symbolically for generic functions.
import numpy as np
import sympy as sp
from scipy import integrate
# 1) np.gradient en lugar de diferencias a mano
h = 0.01
x = -2 + h / 2 + h * np.arange(400)
X, Y = np.meshgrid(x, x)
Fx, Fy = X**2 + Y * np.sin(X), X * Y**2 - np.cos(X) + Y**3
div_np = np.gradient(Fx, h, axis=1) + np.gradient(Fy, h, axis=0)
rot_np = np.gradient(Fy, h, axis=1) - np.gradient(Fx, h, axis=0)
print("np.gradient, error de la divergencia en el interior:", np.abs(div_np[1:-1, 1:-1] - (2 * X + Y * np.cos(X) + 2 * X * Y + 3 * Y**2)[1:-1, 1:-1]).max())
print("np.gradient, error del rotacional en el interior: ", np.abs(rot_np[1:-1, 1:-1] - (Y**2)[1:-1, 1:-1]).max())
# 2) quad: el trabajo de F = (2xy, x^2) por una parábola, y la circulación del vórtice con el módulo del error estimado
F = lambda t: (2 * t * (2 * t**2) * 1.0 + t**2 * (4 * t)) # F(gamma) . gamma' con gamma = (t, 2 t^2)
print("\nquad, trabajo por la parábola:", integrate.quad(F, 0, 1))
vortex = lambda t: (np.sin(t) ** 2 + np.cos(t) ** 2) # F(gamma) . gamma' sobre la circunferencia unidad
print("quad, circulación del vórtice:", integrate.quad(vortex, 0, 2 * np.pi))
# 3) dblquad: integral de la divergencia sobre el disco de radio 1 centrado en (0.3, 0.2), en polares
div_f = lambda x, y: 2 * x + y * np.cos(x) + 2 * x * y + 3 * y**2
inner, err = integrate.dblquad(lambda r, th: div_f(0.3 + r * np.cos(th), 0.2 + r * np.sin(th)) * r, 0, 2 * np.pi, 0, 1)
borde = integrate.quad(lambda th: ((0.3 + np.cos(th))**2 + (0.2 + np.sin(th)) * np.sin(0.3 + np.cos(th))) * np.cos(th)
+ ((0.3 + np.cos(th)) * (0.2 + np.sin(th))**2 - np.cos(0.3 + np.cos(th)) + (0.2 + np.sin(th))**3) * np.sin(th), 0, 2 * np.pi)[0]
print("\ndblquad, integral de la divergencia sobre el disco:", inner, " quad, flujo por el borde:", borde)
# 4) sympy: rot(grad f) = 0 y div(rot F) = 0 para funciones genéricas
x_, y_, z_ = sp.symbols("x y z")
f = sp.Function("f")(x_, y_, z_)
curl = lambda F: [sp.diff(F[2], y_) - sp.diff(F[1], z_), sp.diff(F[0], z_) - sp.diff(F[2], x_), sp.diff(F[1], x_) - sp.diff(F[0], y_)]
div = lambda F: sum(sp.diff(Fi, v) for Fi, v in zip(F, (x_, y_, z_)))
print("\nsympy, rot(grad f) =", [sp.simplify(c) for c in curl([sp.diff(f, v) for v in (x_, y_, z_)])])
G = [sp.Function(n)(x_, y_, z_) for n in "PQR"]
print("sympy, div(rot F) =", sp.simplify(div(curl(G))))The first two output lines use np.gradient and give exactly the same interior errors as handwritten centered differences (ten-thousandths in divergence, hundred-thousandths in curl), because the interior formula is identical. Boundary flux and divergence integral agree with dblquad and quad up to rounding: the same numbers compared in the interactive, now with integration error control. And identities and are zero symbolically for arbitrary functions, exactly what Schwarz’s theorem said.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 3. What is the first component of for ?
Step 1 of 4. How do you rewrite to get an integral without ?
shoelace_area(poly) returns the signed area of a closed polygon with vertices poly (array (m, 2), without repeating the first at the end): positive counterclockwise. line_integral(F, path) returns the work of a field F (function of a point (2,) returning a vector (2,)) along the open polyline joining points in path (array (m, 2)), integrating each side exactly with 5-point Gauss-Legendre quadrature.import numpy as np
def shoelace_area(poly):
"""Área con signo de un polígono cerrado (positiva en sentido antihorario)."""
# tu código
return 0.0
def line_integral(F, path):
"""Trabajo de F a lo largo de la poligonal que une los puntos de path."""
# tu código
return 0.0Summary
- Line integral is parametrization-independent but depends on orientation. It is the Riemann sum of work.
- A field is conservative if and only if its work is path-independent. It requires a symmetric Jacobian (zero curl), sufficient on a simply connected domain. The vortex on the punctured plane has zero curl and circulation : the domain matters.
- Divergence is the Jacobian trace and relative volume-change rate of the flow; curl is twice the local angular velocity. Identities and are Schwarz’s theorem.
- Green’s, divergence and Stokes’ theorems are proved using Fubini and the fundamental theorem of calculus, and require hypotheses (field throughout the region, positive orientation). With interior singularities, flux concentrated there is invisible in the divergence.
- Integration by parts in is the divergence theorem applied to . Hence Hyvärinen’s identity: , allowing a score to be trained without knowing it, provided vanishes at infinity.