Module contents
Lesson 12 of 20Core 120 min

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 F(x)\vb{F}(\vb{x}) to each point x\vb{x}. 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 pp: it learns field s(x)≈∇log⁡p(x)\vb{s}(\vb{x}) \approx \grad \log p(\vb{x}), 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 pp, so it can be learned without knowing it.
  • Artificial potentials. A navigating robot can define a potential UU with a minimum at the goal and hills over obstacles, and move following field −∇U-\grad U. 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 F\vb{F} is of class C1C^1, 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 JF(x)\mat{J}_{\vb{F}}(\vb{x}) 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 x\vb{x}, the other how the neighborhood rotates. In the next interactive you can see this before defining it.

InteractiveParticles in a field
  • red: div⁡F>0\operatorname{div}\vb{F} > 0 (expansion)
  • blue: div⁡F<0\operatorname{div}\vb{F} < 0 (contraction)
  • wheel: rotates at 12rot⁡F\tfrac12\operatorname{rot}\vb{F} (counterclockwise if rot⁡F>0\operatorname{rot}\vb{F} > 0)
  • clockwise wheel (rot⁡F<0\operatorname{rot}\vb{F} < 0)
  • droplet: closed curve of particles
Ingredients of F
1.00
0.00
0.00
0.70×
At cursor: F\vb{F}(−0.96, 0.60)
div⁡F\operatorname{div}\vb{F} at cursor−1.04
rot⁡F\operatorname{rot}\vb{F} at cursor0.00
Droplet area A/A0A / A_01.000
Measured  ⁣dln⁡A/ ⁣dt\dd \ln A / \dd t0.00
div⁡F\operatorname{div}\vb{F} at droplet0.00
Score only: rot⁡F=0\operatorname{rot}\vb{F} = 0 everywhere, since it is a gradient, and the wheels do not turn. Divergence is g Δlog⁡pg\,\Delta\log p and changes sign: it compresses near modes and expands between them.
The field is F=g ∇log⁡p+r (−y,x)+s (x,y)\vb{F} = g\,\grad\log p + r\,(-y, x) + s\,(x, y): a score of a three-Gaussian mixture, a rotation and a source, with adjustable weights. Particles (dots with trails) follow flow lines. The background is divergence (red: the field expands what it carries; blue: it compresses it) and each wheel turns at half the local curl. The magenta drop is a closed curve of particles: its area grows or shrinks at the divergence rate at its position. With score alone, wheels turn nowhere and divergence changes sign; with pure rotation the drop rotates without changing area; with the source it inflates uniformly. Drag the drop elsewhere and release it (press ‘Release drop here’): which score regions compress 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 Δri\Delta\vb{r}_i and summing F(ri)⋅Δri\vb{F}(\vb{r}_i)\cdot\Delta\vb{r}_i yields a Riemann sum converging to an integral.

Proof

By the chain rule, γ~′(s)=γ′(φ(s)) φ′(s)\tilde{\vb{\gamma}}'(s) = \vb{\gamma}'(\varphi(s))\,\varphi'(s). Then ∫cdF(γ(φ(s)))⋅γ′(φ(s)) φ′(s)  ⁣ds\int_c^d \vb{F}(\vb{\gamma}(\varphi(s)))\cdot\vb{\gamma}'(\varphi(s))\,\varphi'(s)\,\dd s is, by the change of variable t=φ(s)t = \varphi(s), equal to ∫φ(c)φ(d)F(γ(t))⋅γ′(t)  ⁣dt\int_{\varphi(c)}^{\varphi(d)}\vb{F}(\vb{\gamma}(t))\cdot\vb{\gamma}'(t)\,\dd t. If φ\varphi increases, φ(c)=a\varphi(c) = a and φ(d)=b\varphi(d) = b: 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: ∣∫CF⋅ ⁣dr∣≤max⁡C∥F∥⋅L(C)\abs{\int_C \vb{F}\cdot\dd\vb{r}} \le \max_C\norm{\vb{F}}\cdot L(C), with L(C)L(C) 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 (2xy,x2)(2xy, x^2) have that (−y,x)(-y, x) does not? The first is the gradient of f(x,y)=x2yf(x, y) = x^2 y.

Proof

On each smooth segment, by the chain rule,  ⁣d ⁣dtf(γ(t))=∇f(γ(t))⋅γ′(t)\frac{\dd}{\dd t}f(\vb{\gamma}(t)) = \grad f(\vb{\gamma}(t))\cdot\vb{\gamma}'(t). Thus the integrand is the derivative of t↦f(γ(t))t \mapsto f(\vb{\gamma}(t)), 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) ⇒\Rightarrow (2) is the previous theorem. (2) ⇔\Leftrightarrow (3): a closed curve is the union of a path C1C_1 from AA to BB and another, C2C_2, from BB to AA; circulation is ∫C1−∫−C2\int_{C_1} - \int_{-C_2} (minus sign from reversing orientation) and vanishes if and only if the two paths from AA to BB agree. (2) ⇒\Rightarrow (1): fix x0∈U\vb{x}_0 \in U and define f(x)=∫x0xF⋅ ⁣drf(\vb{x}) = \int_{\vb{x}_0}^{\vb{x}}\vb{F}\cdot\dd\vb{r} by any path (one exists because an open connected set is polygonally connected). To compute ∂if(x)\partial_i f(\vb{x}), travel to x\vb{x} and append the straight segment to x+hei\vb{x} + h\vb{e}_i:

f(x+hei)−f(x)h=1h∫0hFi(x+sei)  ⁣ds  ⟶  Fi(x)\frac{f(\vb{x} + h\vb{e}_i) - f(\vb{x})}{h} = \frac1h\int_0^h F_i(\vb{x} + s\vb{e}_i)\,\dd s \;\longrightarrow\; F_i(\vb{x})

when h→0h \to 0, by continuity of FiF_i. Thus ∇f=F\grad f = \vb{F}, and the partial derivatives are continuous, so f∈C1f \in C^1.

∎

A testable criterion: symmetric Jacobian

Checking path independence requires testing every path. A local condition can be checked with derivatives. If F=∇f\vb{F} = \grad f with f∈C2f \in C^2, then ∂jFi=∂j∂if=∂i∂jf=∂iFj\partial_j F_i = \partial_j\partial_i f = \partial_i\partial_j f = \partial_i F_j by Schwarz’s theorem: the Jacobian of F\vb{F} (the Hessian of ff) is symmetric. In R2\R^2 the condition is one equation, ∂xF2=∂yF1\partial_x F_2 = \partial_y F_1, and in R3\R^3 there are three, grouped into rot⁡F=0\operatorname{rot}\vb{F} = \vb{0} (defined next section).

Is it sufficient? It depends on the domain. When the domain is a ball, rectangle or all Rn\R^n, yes:

Proof

Write u=x−x0\vb{u} = \vb{x} - \vb{x}_0 and xt=x0+tu\vb{x}_t = \vb{x}_0 + t\vb{u}. Differentiating under the integral sign (Leibniz’s rule; everything is continuous on [0,1][0, 1]),

∂jf(x)=∫01[∑it ∂jFi(xt) ui+Fj(xt)] ⁣dt.\partial_j f(\vb{x}) = \int_0^1\Big[\sum_i t\,\partial_j F_i(\vb{x}_t)\,u_i + F_j(\vb{x}_t)\Big]\dd t .

By symmetry, ∂jFi=∂iFj\partial_j F_i = \partial_i F_j, and ∑i∂iFj(xt) ui= ⁣d ⁣dtFj(xt)\sum_i \partial_i F_j(\vb{x}_t)\,u_i = \frac{\dd}{\dd t}F_j(\vb{x}_t) by the chain rule. The bracket becomes t ⁣d ⁣dtFj(xt)+Fj(xt)= ⁣d ⁣dt[t Fj(xt)]t\frac{\dd}{\dd t}F_j(\vb{x}_t) + F_j(\vb{x}_t) = \frac{\dd}{\dd t}\big[t\,F_j(\vb{x}_t)\big], whose integral from 00 to 11 is Fj(x)F_j(\vb{x}).

∎

The theorem’s formula is also an algorithm: to construct a potential integrate F\vb{F} along a ray. By hand it is often faster to integrate component by component. With F=(2xy+z,  x2,  x)\vb{F} = (2xy + z,\; x^2,\; x), integrating F1F_1 with respect to xx gives f=x2y+xz+g(y,z)f = x^2y + xz + g(y, z); differentiating with respect to yy gives x2+gy=x2x^2 + g_y = x^2, hence gy=0g_y = 0; differentiating with respect to zz gives x+gz=xx + g_z = x, hence gz=0g_z = 0. The potential is f=x2y+xzf = x^2y + xz up to a constant, and work from (0,0,0)(0, 0, 0) to (1,2,3)(1, 2, 3) is f(1,2,3)=5f(1, 2, 3) = 5 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

F(x,y)=(−y,x)x2+y2,(x,y)≠(0,0).\vb{F}(x, y) = \frac{(-y, x)}{x^2 + y^2}, \qquad (x, y) \neq (0, 0).

Compute ∂yF1=y2−x2(x2+y2)2=∂xF2\partial_y F_1 = \dfrac{y^2 - x^2}{(x^2 + y^2)^2} = \partial_x F_2: the condition holds throughout the domain. But its circulation around the unit circle is ∫02π(sin⁡2t+cos⁡2t)  ⁣dt=2π≠0\int_0^{2\pi}(\sin^2 t + \cos^2 t)\,\dd t = 2\pi \neq 0. By the characterization theorem, it has no potential on the punctured plane. What fails? Locally it is a gradient: F=∇θ\vb{F} = \grad\theta with θ=atan2⁡(y,x)\theta = \operatorname{atan2}(y, x) the polar angle. But θ\theta is not a function on the punctured plane: after a circuit around the origin it increases by 2π2\pi. Work along a path is the change in angle, and two paths from AA to BB passing opposite sides of the origin differ by one full turn.

InteractiveDoes it depend on the path?
agujero
Work accumulated from A (horizontal axis: fraction of path traversed)
  • path 1: W1=∫P1F⋅ ⁣drW_1 = \int_{P_1} \vb{F}\cdot\dd\vb{r}
  • path 2: W2W_2
Work W1W_1 (path 1)−3.1416
Work W2W_2 (path 2)3.1416
W1−W2W_1 - W_2 (loop circulation)−6.2832
2π×2\pi \times turns around the origin−6.2832
The loop winds around the origin 1 time: W1−W2=2π⋅(−1)W_1 - W_2 = 2\pi \cdot (-1) although rot⁡F=0\operatorname{rot}F = 0 throughout the domain. The domain is not simply connected.
Two paths from AA to BB (cubic Bézier curves; drag endpoints and control points). W=∫F⋅ ⁣drW = \int \vb{F}\cdot\dd\vb{r} is computed by Gauss–Legendre quadrature and below is accumulated work along each path. With a gradient, the curves end at the same height, f(B)−f(A)f(B) - f(A), whatever you do. With rotation (−y,x)(-y, x), the difference is twice the area of the loop between paths (Green's theorem below). With the vortex, path 1 starts above the origin and 2 below: their loop (out along 1, back along 2) encircles the origin clockwise and W1−W2=−2πW_1 - W_2 = -2\pi. Then move the lower path to the same side as the other: the difference returns to 00. How can you obtain +2π+2\pi? And ±4π\pm 4\pi, with a path making one full turn around the origin?

What matters is not the hole’s size but that the loop formed by the two paths encircles it: the difference is 2π2\pi 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 Rn\R^n; 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 R3\R^3 minus a point, zero curl does suffice (the sphere is simply connected), but in R3\R^3 minus a line the vortex remains a counterexample.

What this has to do with generative models

A score ∇log⁡p\grad\log p is conservative by construction, with potential log⁡p\log p, so its Jacobian, the Hessian of log⁡p\log p, is symmetric. An arbitrary network sθ:Rd→Rd\vb{s}_\theta:\R^d\to\R^d, in contrast, has an arbitrary Jacobian and is not generally a gradient; it must be parametrized as sθ=∇Eθ\vb{s}_\theta = \grad E_\theta to be one. Similarly, a navigation field −∇U-\grad U has no loops: follow its flow lines downward and UU 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 J=S+K\mat{J} = \mat{S} + \mat{K} with S=12(J+J⊤)\mat{S} = \tfrac12(\mat{J} + \mat{J}\T) symmetric and K=12(J−J⊤)\mat{K} = \tfrac12(\mat{J} - \mat{J}\T) skew-symmetric. With linearization F(x+h)≈F(x)+Jh\vb{F}(\vb{x} + \vb{h}) \approx \vb{F}(\vb{x}) + \mat{J}\vb{h}, near x\vb{x} the neighborhood deforms as follows: S\mat{S} stretches and compresses it along its eigenvectors, and K\mat{K} 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. tr⁡J\tr\mat{J} is the sum of stretches along axes; curl components are the three independent entries of K\mat{K}, because (J−J⊤)w=(rot⁡F)×w(\mat{J} - \mat{J}\T)\vb{w} = (\operatorname{rot}\vb{F})\times\vb{w} for every w\vb{w} (check entry by entry). Field w↦Kw=12(rot⁡F)×w\vb{w}\mapsto\mat{K}\vb{w} = \tfrac12(\operatorname{rot}\vb{F})\times\vb{w} is infinitesimal rotation of angular velocity 12rot⁡F\tfrac12\operatorname{rot}\vb{F}: that is why the wheels in the earlier figure turn at half the curl.

Fielddiv⁡\operatorname{div}rot⁡\operatorname{rot}Behavior
(x,y)(x, y)2200uniform source
(−y,x)(-y, x)0022rigid-body rotation
(−y,x)/(x2+y2)(-y, x)/(x^2 + y^2)0000 (outside origin)vortex: circles without rotating locally
(x,y)/(x2+y2)(x, y)/(x^2 + y^2)00 (outside origin)00point source, flux 2π2\pi
−Σ−1(x−μ)-\mat{\Sigma}\inv(\vb{x} - \vb{\mu}) (score of N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}))−tr⁡Σ−1-\tr\mat{\Sigma}\inv00sink 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 R2\R^2, ∂xxr2=y2−x2r4\partial_x\frac{x}{r^2} = \frac{y^2 - x^2}{r^4} and ∂yyr2=x2−y2r4\partial_y\frac{y}{r^2} = \frac{x^2 - y^2}{r^4} sum to zero), yet flux 2π2\pi 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 Φt\vb{\Phi}_t be the flow of F\vb{F}: the map taking each point to its position after time tt. For small hh, Φh(x)≈x+hF(x)\vb{\Phi}_h(\vb{x}) \approx \vb{x} + h\vb{F}(\vb{x}), whose Jacobian is I+hJ\mat{I} + h\mat{J}, and expanding the determinant,

det⁡(I+hJ)=1+h tr⁡J+O(h2)=1+hdiv⁡F+O(h2).\det(\mat{I} + h\mat{J}) = 1 + h\,\tr\mat{J} + \bigO(h^2) = 1 + h\operatorname{div}\vb{F} + \bigO(h^2).

By the change-of-variables formula, the volume of the image of a region Ω\Omega changes at rate  ⁣d ⁣dtvol⁡Φt(Ω)∣t=0=∫Ωdiv⁡F  ⁣dx\frac{\dd}{\dd t}\operatorname{vol}\vb{\Phi}_t(\Omega)\big|_{t=0} = \int_\Omega\operatorname{div}\vb{F}\,\dd\vb{x}. Divergence is the density of expansion, confirmed by the magenta drop:  ⁣dln⁡A/ ⁣dt≈div⁡F\dd\ln A/\dd t \approx \operatorname{div}\vb{F} at its position. This reappears in continuous flows in generative AI: if a density is transported by x′=F(x)\vb{x}' = \vb{F}(\vb{x}), its logarithm along a trajectory evolves as  ⁣d ⁣dtlog⁡pt(xt)=−div⁡F\frac{\dd}{\dd t}\log p_t(\vb{x}_t) = -\operatorname{div}\vb{F} (see instantaneous change of variables and continuous normalizing flows).

Identities inherited from Schwarz

Proof

(1) The first component of rot⁡∇f\operatorname{rot}\grad f is ∂y∂zf−∂z∂yf=0\partial_y\partial_z f - \partial_z\partial_y f = 0, and the others cancel likewise, all by Schwarz’s theorem. (2) div⁡rot⁡F=∂x(∂yF3−∂zF2)+∂y(∂zF1−∂xF3)+∂z(∂xF2−∂yF1)\operatorname{div}\operatorname{rot}\vb{F} = \partial_x(\partial_yF_3 - \partial_zF_2) + \partial_y(\partial_zF_1 - \partial_xF_3) + \partial_z(\partial_xF_2 - \partial_yF_1) contains six terms canceling in pairs, ∂x∂yF3\partial_x\partial_yF_3 with ∂y∂xF3\partial_y\partial_xF_3, etc. (3) This is the definition. (4) Apply the product rule to each ∂i(fFi)\partial_i(fF_i).

∎

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, div⁡(∇log⁡p)=Δlog⁡p\operatorname{div}(\grad\log p) = \Delta\log p, 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 r:D⊂R2→R3\vb{r}: D \subset \R^2 \to \R^3 parametrizes surface SS, vectors ru\vb{r}_u and rv\vb{r}_v are tangent and the cross product ru×rv\vb{r}_u\times\vb{r}_v is normal to SS, with norm equal to the area of the parallelogram generated by ru  ⁣du\vb{r}_u\,\dd u and rv  ⁣dv\vb{r}_v\,\dd v: it is the area element,  ⁣dS=∥ru×rv∥ ⁣du  ⁣dv\dd S = \norm{\vb{r}_u\times\vb{r}_v}\dd u\,\dd v.

Changing parametrization with a diffeomorphism φ\vb{\varphi} multiplies the cross product by det⁡Jφ\det\mat{J}_{\vb{\varphi}}, and the change-of-variables formula compensates: flux is preserved if det⁡Jφ>0\det\mat{J}_{\vb{\varphi}} > 0 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 γ(t)=(x(t),y(t))\vb{\gamma}(t) = (x(t), y(t)) is traversed counterclockwise, the outward normal is n  ⁣ds=(y′,−x′)  ⁣dt\vb{n}\,\dd s = (y', -x')\,\dd t and flux is ∮F⋅n  ⁣ds=∮F1  ⁣dy−F2  ⁣dx\oint\vb{F}\cdot\vb{n}\,\dd s = \oint F_1\,\dd y - F_2\,\dd x. This form converts Green’s theorem into the planar divergence theorem, as we will see. (For a surface that is graph z=g(x,y)z = g(x, y), parametrized by r(x,y)=(x,y,g(x,y))\vb{r}(x, y) = (x, y, g(x, y)), the cross product is rx×ry=(−gx,−gy,1)\vb{r}_x\times\vb{r}_y = (-g_x, -g_y, 1), 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 D={(x,y):a≤x≤b,  g1(x)≤y≤g2(x)}D = \{(x, y): a \le x \le b,\; g_1(x) \le y \le g_2(x)\} with g1≤g2g_1 \le g_2 of class C1C^1 (a “type I” region). By Fubini’s theorem and the fundamental theorem of calculus,

∬D∂P∂y  ⁣dA=∫ab[P(x,g2(x))−P(x,g1(x))] ⁣dx.\iint_D\pd{P}{y}\,\dd A = \int_a^b\big[P(x, g_2(x)) - P(x, g_1(x))\big]\dd x.

Line integral ∮P  ⁣dx\oint P\,\dd x has four segments: lower curve y=g1(x)y = g_1(x) left to right, contributing ∫abP(x,g1(x))  ⁣dx\int_a^b P(x, g_1(x))\,\dd x; the right side, where  ⁣dx=0\dd x = 0; the upper curve traversed right to left, contributing −∫abP(x,g2(x))  ⁣dx-\int_a^b P(x, g_2(x))\,\dd x; and the left side, also with  ⁣dx=0\dd x = 0. Thus ∮∂DP  ⁣dx=−∬D∂yP  ⁣dA\oint_{\partial D}P\,\dd x = -\iint_D\partial_yP\,\dd A. If DD is also type II, {c≤y≤d,  h1(y)≤x≤h2(y)}\{c \le y \le d,\; h_1(y) \le x \le h_2(y)\}, the same argument with xx and yy interchanged gives ∮∂DQ  ⁣dy=+∬D∂xQ  ⁣dA\oint_{\partial D}Q\,\dd y = +\iint_D\partial_xQ\,\dd A (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 DD remains.

∎

Green’s planimeter

If you choose F=12(−y,x)\vb{F} = \tfrac12(-y, x), its curl is 11 everywhere and Green says

aˊrea⁡(D)=∬D1  ⁣dA=12∮∂D(x  ⁣dy−y  ⁣dx).\operatorname{área}(D) = \iint_D 1\,\dd A = \frac12\oint_{\partial D}(x\,\dd y - y\,\dd x).

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 ri=(xi,yi)\vb{r}_i = (x_i, y_i), each straight edge contributes exactly 12(xiyi+1−xi+1yi)\tfrac12(x_iy_{i+1} - x_{i+1}y_i), the signed area of its triangle with the origin: this is the shoelace formula you will implement below.

InteractiveGreen's planimeter
draw here
  • triangle (O,ri,ri+1)(O, \vb{r}_i, \vb{r}_{i+1}) with area >0> 0
  • with area <0< 0
  • arrow: traversal direction
View
100 %
A=12∮(x  ⁣dy−y  ⁣dx)A = \tfrac12\oint (x\,\dd y - y\,\dd x)5.3026
∮x  ⁣dy\oint x\,\dd y5.3026
−∮y  ⁣dx-\oint y\,\dd x5.3026
∬n  ⁣dA\iint n\,\dd A (cell count)5.400
Orientationcounterclockwise (positive)
Partial sweep sum5.303
Move OO: the signed triangles change completely, but their sum does not. This is the shoelace formula.
Draw a closed curve on the canvas with mouse or finger; you can also choose a preset. In ‘Sweep from OO’, each edge forms a triangle with point OO (drag it): blue for positive area, red for negative. Their signed sum is 12∮(x  ⁣dy−y  ⁣dx)\tfrac12\oint(x\,\dd y - y\,\dd x), and observe that it does not depend on where OO is placed. Use the traversal control to see accumulation. The clockwise circle gives negative area. In ‘Winding number’, color shows how often the curve surrounds each point: the line integral measures ∬n  ⁣dA\iint n\,\dd A, and a region inside the inner loop counts twice. Counting 0.1×0.10.1 \times 0.1 cells gives the same figure up to grid discretization error (a few tenths at most).

Three lessons from the figure. First, sign: reversing traversal changes the sign of every line integral and thus area. Second, independence of OO: graphically, F\vb{F} matters only through its curl. Adding any gradient to F\vb{F} does not change circulation around a closed curve; 12(−y,x)\tfrac12(-y, x), (0,x)(0, x) and (−y,0)(-y, 0) 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 (−Q,P)(-Q, P): its “curl” is ∂xP+∂yQ=div⁡F\partial_x P + \partial_y Q = \operatorname{div}\vb{F} and ∮(−Q)  ⁣dx+P  ⁣dy=∮F1  ⁣dy−F2  ⁣dx=∮F⋅n  ⁣ds\oint(-Q)\,\dd x + P\,\dd y = \oint F_1\,\dd y - F_2\,\dd x = \oint\vb{F}\cdot\vb{n}\,\dd s. 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 xnx_n direction”, {(x′,xn):x′∈D′,  g1(x′)≤xn≤g2(x′)}\{(\vb{x}', x_n): \vb{x}' \in D',\; g_1(\vb{x}') \le x_n \le g_2(\vb{x}')\}, Fubini and the fundamental theorem give ∫Ω∂nFn  ⁣dV=∫D′[Fn(x′,g2)−Fn(x′,g1)]  ⁣dx′\int_\Omega\partial_nF_n\,\dd V = \int_{D'}[F_n(\vb{x}', g_2) - F_n(\vb{x}', g_1)]\,\dd\vb{x}', the flux of component FnenF_n\vb{e}_n through the top and bottom caps (the side boundary contributes nothing because n⋅en=0\vb{n}\cdot\vb{e}_n = 0). 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.

InteractiveWhat leaves through the boundary
  • red arrow: outward (F⋅n>0\vb{F}\cdot\vb{n} > 0)
  • blue arrow: inward
  • background: div⁡F\operatorname{div}\vb{F}
Region
4 × 4
Flux ∮∂ΩF⋅n  ⁣ds\oint_{\partial\Omega} \vb{F}\cdot\vb{n}\,\dd s2.53280
∬Ωdiv⁡F  ⁣dA\iint_{\Omega} \operatorname{div}\vb{F}\,\dd A2.53280
Difference0.00000
Area of Ω\Omega4.320
Mean div⁡F\operatorname{div}\vb{F} (flux / area)0.586
The values agree: what exits through the boundary is exactly what is created inside.
Move the region (drag its center) and resize it (drag the blue corner). Arrows on the boundary are F⋅n\vb{F}\cdot\vb{n}: red outward (field exits), blue inward. At right, flux ∮F⋅n  ⁣ds\oint\vb{F}\cdot\vb{n}\,\dd s and the integral of divergence inside agree at every moment, for every region and field. Enable ‘Subdivide into cells’: each cell loses through its boundary what it creates inside, and outflows on interior edges cancel in pairs (what leaves a cell enters its neighbor), so the sum of cells is exactly the outer-boundary flux. With the point source there is a case where the theorem fails: which hypothesis fails?

A consequence gives divergence physical meaning without coordinates: apply the theorem to a small ball Bρ(x)B_\rho(\vb{x}) and divide by its volume,

div⁡F(x)=lim⁡ρ→01vol⁡Bρ∮∂Bρ(x)F⋅n  ⁣dS,\operatorname{div}\vb{F}(\vb{x}) = \lim_{\rho\to 0}\frac{1}{\operatorname{vol}B_\rho}\oint_{\partial B_\rho(\vb{x})}\vb{F}\cdot\vb{n}\,\dd S,

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 J\mat{J} be the Jacobian of F\vb{F} evaluated at r(u,v)\vb{r}(u, v). By the chain rule and symmetry ruv=rvu\vb{r}_{uv} = \vb{r}_{vu} (Schwarz),

∂u(F⋅rv)−∂v(F⋅ru)=(Jru)⋅rv−(Jrv)⋅ru=rv⋅(J−J⊤)ru=rv⋅((rot⁡F)×ru),\partial_u\big(\vb{F}\cdot\vb{r}_v\big) - \partial_v\big(\vb{F}\cdot\vb{r}_u\big) = (\mat{J}\vb{r}_u)\cdot\vb{r}_v - (\mat{J}\vb{r}_v)\cdot\vb{r}_u = \vb{r}_v\cdot(\mat{J} - \mat{J}\T)\vb{r}_u = \vb{r}_v\cdot\big((\operatorname{rot}\vb{F})\times\vb{r}_u\big),

which by the scalar triple product is (rot⁡F)⋅(ru×rv)(\operatorname{rot}\vb{F})\cdot(\vb{r}_u\times\vb{r}_v): the flux integrand. Then ∬S(rot⁡F)⋅n  ⁣dS=∬D[∂u(F⋅rv)−∂v(F⋅ru)]  ⁣du  ⁣dv\iint_S(\operatorname{rot}\vb{F})\cdot\vb{n}\,\dd S = \iint_D[\partial_u(\vb{F}\cdot\vb{r}_v) - \partial_v(\vb{F}\cdot\vb{r}_u)]\,\dd u\,\dd v, and by Green applied to (P,Q)=(F⋅ru,  F⋅rv)(P, Q) = (\vb{F}\cdot\vb{r}_u,\; \vb{F}\cdot\vb{r}_v) on DD this is ∮∂D(F⋅ru)  ⁣du+(F⋅rv)  ⁣dv=∮∂SF⋅ ⁣dr\oint_{\partial D}(\vb{F}\cdot\vb{r}_u)\,\dd u + (\vb{F}\cdot\vb{r}_v)\,\dd v = \oint_{\partial S}\vb{F}\cdot\dd\vb{r}.

∎

One principle

The four results in this lesson (the fundamental theorem for ∇f\grad f, 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.

DimensionRegionBoundaryStatement
1[a,b][a, b]{a,b}\{a, b\}∫abf′  ⁣dx=f(b)−f(a)\int_a^b f'\,\dd x = f(b) - f(a)
1, on a curvecurve CC from AA to BB{A,B}\{A, B\}∫C∇f⋅ ⁣dr=f(B)−f(A)\int_C\grad f\cdot\dd\vb{r} = f(B) - f(A)
2region DDcurve ∂D\partial D∬Drot⁡F  ⁣dA=∮∂DF⋅ ⁣dr\iint_D\operatorname{rot}\vb{F}\,\dd A = \oint_{\partial D}\vb{F}\cdot\dd\vb{r} (Green)
2, 3surface SScurve ∂S\partial S∬Srot⁡F⋅n  ⁣dS=∮∂SF⋅ ⁣dr\iint_S\operatorname{rot}\vb{F}\cdot\vb{n}\,\dd S = \oint_{\partial S}\vb{F}\cdot\dd\vb{r} (Stokes)
nnregion Ω\Omegahypersurface ∂Ω\partial\Omega∫Ωdiv⁡F  ⁣dV=∮∂ΩF⋅n  ⁣dS\int_\Omega\operatorname{div}\vb{F}\,\dd V = \oint_{\partial\Omega}\vb{F}\cdot\vb{n}\,\dd S (Gauss)

The language of differential forms unifies them as ∫Ω ⁣dω=∫∂Ωω\int_\Omega\dd\omega = \int_{\partial\Omega}\omega (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 CC with rot⁡F=0\operatorname{rot}\vb{F} = \vb{0} on a surface SS bounded by it inside the domain gives ∮CF⋅ ⁣dr=0\oint_C\vb{F}\cdot\dd\vb{r} = 0, 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 rot⁡F\operatorname{rot}\vb{F} concentrates its “2πδ2\pi\delta”, is in the way. The same holds for the point source with Gauss.

Integration by parts and score matching

From the product rule div⁡(fG)=∇f⋅G+fdiv⁡G\operatorname{div}(f\vb{G}) = \grad f\cdot\vb{G} + f\operatorname{div}\vb{G} and divergence theorem, if f∈C1(Ω‾)f \in C^1(\overline{\Omega}) and G∈C1(Ω‾;Rn)\vb{G} \in C^1(\overline{\Omega};\R^n),

∫Ω∇f⋅G  ⁣dV=∮∂Ωf G⋅n  ⁣dS−∫Ωfdiv⁡G  ⁣dV.\int_\Omega\grad f\cdot\vb{G}\,\dd V = \oint_{\partial\Omega}f\,\vb{G}\cdot\vb{n}\,\dd S - \int_\Omega f\operatorname{div}\vb{G}\,\dd V.

This is integration by parts in Rn\R^n and generalizes ∫abf′g=[fg]ab−∫abfg′\int_a^b f'g = [fg]_a^b - \int_a^b fg'. With G=∇v\vb{G} = \grad v we obtain Green’s identities, ∫Ω(∇u⋅∇v+u Δv)  ⁣dV=∮∂Ωu ∂nv  ⁣dS\int_\Omega(\grad u\cdot\grad v + u\,\Delta v)\,\dd V = \oint_{\partial\Omega}u\,\partial_{\vb{n}}v\,\dd S, used for instance to prove that the Dirichlet problem for Laplace’s equation has at most one solution. When fGf\vb{G} decays rapidly at infinity, the boundary term vanishes and ∫Rn∇f⋅G=−∫Rnfdiv⁡G\int_{\R^n}\grad f\cdot\vb{G} = -\int_{\R^n}f\operatorname{div}\vb{G} remains: −div⁡-\operatorname{div} is the adjoint of ∇\grad. In weak form this lets us differentiate a nondifferentiable function by transferring the derivative to the test function.

Hyvärinen’s identity

Let pp be an unknown density on Rd\R^d from which we have samples, and sθ:Rd→Rd\vb{s}_\theta:\R^d\to\R^d a model of its score s∗=∇log⁡p\vb{s}^* = \grad\log p. The natural objective is Fisher divergence,

JESM(θ)=12 Ep[∥sθ(x)−∇log⁡p(x)∥2],J_{\text{ESM}}(\theta) = \tfrac12\,\E_{p}\big[\norm{\vb{s}_\theta(\vb{x}) - \grad\log p(\vb{x})}^2\big],

but it contains ∇log⁡p\grad\log p, precisely what we want to learn. Integration by parts removes it.

Proof

Expand the square: JESM=12E∥sθ∥2−E[sθ⋅∇log⁡p]+CJ_{\text{ESM}} = \tfrac12\E\norm{\vb{s}_\theta}^2 - \E[\vb{s}_\theta\cdot\grad\log p] + C. Only the cross term needs attention. Since p ∇log⁡p=∇pp\,\grad\log p = \grad p,

E[sθ⋅∇log⁡p]=∫Rdsθ⋅∇p  ⁣dx=lim⁡R→∞∫BRsθ⋅∇p  ⁣dx.\E[\vb{s}_\theta\cdot\grad\log p] = \int_{\R^d}\vb{s}_\theta\cdot\grad p\,\dd\vb{x} = \lim_{R\to\infty}\int_{B_R}\vb{s}_\theta\cdot\grad p\,\dd\vb{x}.

On each ball BRB_R, integration by parts with f=pf = p and G=sθ\vb{G} = \vb{s}_\theta gives ∫BRsθ⋅∇p=∮∂BRp sθ⋅n  ⁣dS−∫BRpdiv⁡sθ\int_{B_R}\vb{s}_\theta\cdot\grad p = \oint_{\partial B_R}p\,\vb{s}_\theta\cdot\vb{n}\,\dd S - \int_{B_R}p\operatorname{div}\vb{s}_\theta. The first term tends to 00 by hypothesis, and the second converges to E[div⁡sθ]\E[\operatorname{div}\vb{s}_\theta] by dominated convergence, since E∣div⁡sθ∣<∞\E\lvert\operatorname{div}\vb{s}_\theta\rvert < \infty. Thus E[sθ⋅∇log⁡p]=−E[div⁡sθ]\E[\vb{s}_\theta\cdot\grad\log p] = -\E[\operatorname{div}\vb{s}_\theta].

∎

We call JESMJ_{\text{ESM}} the explicit objective (explicit score matching) and JISM(θ)=Ep[div⁡sθ+12∥sθ∥2]J_{\text{ISM}}(\theta) = \E_p[\operatorname{div}\vb{s}_\theta + \tfrac12\norm{\vb{s}_\theta}^2] the implicit objective (implicit score matching): the identity says JESM=JISM+CJ_{\text{ESM}} = J_{\text{ISM}} + C. The implicit one contains only the model and expectations under pp, approximated with samples: J^(θ)=1n∑i[tr⁡Jsθ(xi)+12∥sθ(xi)∥2]\hat J(\theta) = \frac1n\sum_i[\tr\mat{J}_{\vb{s}_\theta}(\vb{x}_i) + \tfrac12\norm{\vb{s}_\theta(\vb{x}_i)}^2]. It also does not depend on the normalization constant, because the score of p~=Z p\tilde p = Z\,p is the same. Three comments.

  • Cost. div⁡sθ=tr⁡Jsθ\operatorname{div}\vb{s}_\theta = \tr\mat{J}_{\vb{s}_\theta} requires the dd diagonal derivatives of the Jacobian, i.e. dd 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 JESMJ_{\text{ESM}} is the true score, a gradient. But the objective can be evaluated for any field sθ\vb{s}_\theta, conservative or otherwise.
  • The boundary hypothesis is real. If pp has support with a boundary, integration by parts leaves a nonzero term −∮p sθ⋅n  ⁣dS-\oint p\,\vb{s}_\theta\cdot\vb{n}\,\dd S, and the computable objective is no longer the true one. This is the lesson’s final interactive.
InteractiveThe boundary that does not vanish
p(x)
  • density p(x)p(x)
  • true score s∗=(log⁡p)′s^* = (\log p)'
  • model sθ(x)=θ1+θ2xs_\theta(x) = \theta_1 + \theta_2 x
  • below: contours of JESMJ_{\text{ESM}} (thick gray) and JISM+CJ_{\text{ISM}} + C (thin orange) in (θ1,θ2)(\theta_1, \theta_2); circles: minima
JESM=12E[(sθ−s∗)2]J_{\text{ESM}} = \tfrac12\E[(s_\theta - s^*)^2]2.4978
JISM+C=E[sθ′+12sθ2]+CJ_{\text{ISM}} + C = \E[s_\theta' + \tfrac12 s_\theta^2] + C2.4978
Boundary [p sθ][p\,s_\theta]0.0000
JISM+C−[p sθ]J_{\text{ISM}} + C - [p\,s_\theta]2.4978
Explicit θ⋆\theta^\star(0.074, −0.530)
Implicit θ⋆\theta^\star(0.074, −0.530)
In the tails p sθ→0p\,s_\theta \to 0: the boundary term vanishes for all θ\theta. The objectives differ by the constant CC, have the same contours and the same minimum.
Linear model sθ(x)=θ1+θ2xs_\theta(x) = \theta_1 + \theta_2 x in one dimension. Above: density (blue), true score (dashed gray) and model (orange). Below: parameter plane, with level curves of explicit objective JESMJ_{\text{ESM}} (thick gray) and implicit JISM+CJ_{\text{ISM}} + C (thin orange), and their minima as hollow circles. Drag blue point θ\theta. With the Gaussian mixture (support R\R), both curves coincide to the last level: the identity is exact. Switch to the exponential on [0,∞)[0, \infty): density equals p(0)=1p(0) = 1 at the boundary, leaving term −p(0) sθ(0)-p(0)\,s_\theta(0), and the implicit minimum moves away. In which direction? How far? Check the readouts that JISM+C−[p sθ]J_{\text{ISM}} + C - [p\,s_\theta] does reproduce JESMJ_{\text{ESM}}.

The exponential case can be solved by hand. With p=e−xp = e^{-x} on [0,∞)[0, \infty) the score is −1-1, and the exact model is sθ=−1s_\theta = -1, that is, θ=(−1,0)\theta = (-1, 0). The implicit objective with sθ=θ1+θ2xs_\theta = \theta_1 + \theta_2x is θ2+12E[(θ1+θ2x)2]\theta_2 + \tfrac12\E[(\theta_1 + \theta_2 x)^2], with Ex=1\E x = 1 and Ex2=2\E x^2 = 2, and setting its gradient to zero yields θ=(1,−1)\theta = (1, -1): a score rising when it should fall. The difference between the objectives is exactly the boundary term −p(0)sθ(0)=−θ1-p(0)s_\theta(0) = -\theta_1: linear in θ\theta, 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.

[ ]Line integrals, Green and the shoelace formulaBrowser
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 2π2\pi to the last displayed digit, unchanged by reparametrizing with t↦t2t\mapsto t^2 and changing sign when traversal is reversed, as the theorem says. The gradient gives 22 (the potential difference) along all four paths, including one oscillating and moving backward vertically, and rotation gives 00 and −2-2 along the first two. A random polygon’s area agrees by shoelace and circulation of 12(−y,x)\tfrac12(-y, x), and matches Monte Carlo point counting within statistical error (with 400,000 points, the estimator’s standard deviation is about 7⋅10−37\cdot 10^{-3}).

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.

[ ]Divergence, curl and flux on a gridBrowser
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 O(h2)\bigO(h^2) (with h=0.01h = 0.01, on the order of 10−410^{-4} in divergence and 10−510^{-5} 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 10−310^{-3}, is region discretization error. The point source gives 2π2\pi through the circle and zero through a region not containing it (residual of order 10−610^{-6} 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 2.22.2 for the grid field, whose curl is y2y^2. 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 x\vb{x} through the sphere is 4π4\pi and changes sign on swapping parameters, because that reverses ru×rv\vb{r}_u\times\vb{r}_v.

Finally, one-dimensional score matching. Parametrize the score as a linear combination of basis functions sθ(x)=∑kθkφk(x)\vb{s}_\theta(x) = \sum_k\theta_k\varphi_k(x). Then JISM(θ)=12θ⊤Aθ+b⊤θJ_{\text{ISM}}(\theta) = \tfrac12\theta\T\mat{A}\theta + \vb{b}\T\theta with A=E[φφ⊤]\mat{A} = \E[\vb{\varphi}\vb{\varphi}\T] and b=E[φ′]\vb{b} = \E[\vb{\varphi}'], minimized by solving Aθ=−b\mat{A}\theta = -\vb{b}: a linear system with samples. The explicit objective, which in the lab we can calculate because we know pp, gives Aθ=E[φ s∗]\mat{A}\theta = \E[\vb{\varphi}\,s^*].

[ ]Score matching in one dimensionBrowser
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 b=E[φ′]\vb{b} = \E[\vb{\varphi}'] 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 (1,−1)(1, -1), not (−1,0)(-1, 0): 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 f,P,Q,Rf, P, Q, R functions.

[ ]Checking with np.gradient, scipy.integrate and sympyBrowser
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 rot⁡∇f=0\operatorname{rot}\grad f = \vb{0} and div⁡rot⁡F=0\operatorname{div}\operatorname{rot}\vb{F} = 0 are zero symbolically for arbitrary functions, exactly what Schwarz’s theorem said.

Common mistakes

Exercises

NumericCirculation of rotation
Calculate the circulation of F(x,y)=(−y,x)\vb{F}(x, y) = (-y, x) along the unit circle traversed counterclockwise.
NumericFlux through the sphere
Calculate outward flux of F(x,y,z)=(x,y,z)\vb{F}(x, y, z) = (x, y, z) through the unit sphere.
QuizWhich fields are conservative?
Which fields are conservative on their domain?

More than one answer may be correct.

NumericWork using a potential
Field F(x,y,z)=(2xy+z,  x2,  x)\vb{F}(x, y, z) = (2xy + z,\; x^2,\; x) is conservative. Calculate its work along any curve from (0,0,0)(0, 0, 0) to (1,2,3)(1, 2, 3).
NumericArea of the astroid by Green
Calculate the area enclosed by astroid x=cos⁡3tx = \cos^3 t, y=sin⁡3ty = \sin^3 t, t∈[0,2π]t \in [0, 2\pi], using formula 12∮(x  ⁣dy−y  ⁣dx)\tfrac12\oint(x\,\dd y - y\,\dd x).
NumericFlux through a circle
Calculate outward flux of field F(x,y)=(x3,y3)\vb{F}(x, y) = (x^3, y^3) through the unit circle.
QuizSign of a circulation
Calculate ∮x  ⁣dy\oint x\,\dd y along the boundary of square [0,1]2[0, 1]^2 traversed clockwise.
QuizPoint source and the divergence theorem
Let F(x,y)=(x,y)/(x2+y2)\vb{F}(x, y) = (x, y)/(x^2 + y^2) and Ω\Omega be the unit disk. We have div⁡F=0\operatorname{div}\vb{F} = 0 in Ω∖{0}\Omega\setminus\{\vb{0}\}. What is true?
NumericA Gaussian score
A Gaussian in R3\R^3 has covariance Σ=diag⁡(1,2,4)\mat{\Sigma} = \diag(1, 2, 4). Calculate the divergence of its score ∇log⁡p(x)=−Σ−1(x−μ)\grad\log p(\vb{x}) = -\mat{\Sigma}\inv(\vb{x} - \vb{\mu}).
NumericScore matching with one parameter
Data are X∼N(0,4)X \sim \Normal(0, 4) and the model is sθ(x)=−θxs_\theta(x) = -\theta x. Minimize Hyvärinen objective J(θ)=E[sθ′(X)+12sθ(X)2]J(\theta) = \E[s_\theta'(X) + \tfrac12 s_\theta(X)^2] and give optimal θ\theta.
ProofThe curl of a gradient vanishes
Prove: If f∈C2(U)f \in C^2(U) with U⊆R3U \subseteq \R^3 open, then rot⁡(∇f)=0\operatorname{rot}(\grad f) = \vb{0} in UU.
0
Write F=∇f=(∂xf,∂yf,∂zf)\vb{F} = \grad f = (\partial_xf, \partial_yf, \partial_zf) and calculate the three components of rot⁡F\operatorname{rot}\vb{F}.

Step 1 of 3. What is the first component of rot⁡F\operatorname{rot}\vb{F} for F=∇f\vb{F} = \grad f?

ProofHyvärinen's identity in one dimension
Prove: Let pp be a C1C^1 positive density on R\R, and sθ∈C1s_\theta \in C^1 with Ep[sθ2]<∞\E_p[s_\theta^2] < \infty, Ep[((log⁡p)′)2]<∞\E_p[((\log p)')^2] < \infty and Ep∣sθ′∣<∞\E_p\lvert s_\theta'\rvert < \infty. If p(x)sθ(x)→0p(x)s_\theta(x) \to 0 as x→±∞x \to \pm\infty, then Ep[(sθ−(log⁡p)′)2]=Ep[sθ2+2sθ′]+C\E_p[(s_\theta - (\log p)')^2] = \E_p[s_\theta^2 + 2s_\theta'] + C, with CC independent of θ\theta.
0
Expand the square and focus on cross term Ep[sθ (log⁡p)′]\E_p[s_\theta\,(\log p)'].

Step 1 of 4. How do you rewrite Ep[sθ (log⁡p)′]\E_p[s_\theta\,(\log p)'] to get an integral without log⁡p\log p?

CodeShoelace and line integral
Implement two functions. 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.0
Shift+Enter to run
JESM(θ)=12∫p ∥sθ−∇log⁡p∥2  ⁣dxJ_{\text{ESM}}(\theta) = \tfrac12\int p\,\norm{\vb{s}_\theta - \grad\log p}^2\,\dd\vb{x}
Fisher divergence: the quantity to minimize, but it contains the true score.
1/6

Summary

Key idea
A vector field is an arrow at each point, and its Jacobian splits into what expands (trace, divergence) and what rotates (skew-symmetric part, curl). Green, Gauss and Stokes say the same thing: integrating that derivative over a region equals integrating the field over its boundary, because interior contributions cancel in pairs.
  • Line integral ∫CF⋅ ⁣dr\int_C\vb{F}\cdot\dd\vb{r} 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 2π2\pi: the domain matters.
  • Divergence is the Jacobian trace and relative volume-change rate of the flow; curl is twice the local angular velocity. Identities rot⁡∇f=0\operatorname{rot}\grad f = \vb{0} and div⁡rot⁡F=0\operatorname{div}\operatorname{rot}\vb{F} = 0 are Schwarz’s theorem.
  • Green’s, divergence and Stokes’ theorems are proved using Fubini and the fundamental theorem of calculus, and require hypotheses (field C1C^1 throughout the region, positive orientation). With interior singularities, flux concentrated there is invisible in the divergence.
  • Integration by parts in Rn\R^n is the divergence theorem applied to fGf\vb{G}. Hence Hyvärinen’s identity: 12E∥sθ−∇log⁡p∥2=E[div⁡sθ+12∥sθ∥2]+C\tfrac12\E\norm{\vb{s}_\theta - \grad\log p}^2 = \E[\operatorname{div}\vb{s}_\theta + \tfrac12\norm{\vb{s}_\theta}^2] + C, allowing a score to be trained without knowing it, provided p sθp\,\vb{s}_\theta vanishes at infinity.