arxiv:2005.10060v2 [physics.comp-ph] 2 jun 2020python package named bfieldtools. in this work, we...

15
Magnetic-field modeling with surface currents: Physical and computational principles of bfieldtools Antti J Mäkinen, 1, a) Rasmus Zetter, 1 Joonas Iivanainen, 1 Koos C J Zevenhoven, 1 Lauri Parkkonen, 1 and Risto J Ilmoniemi 1 Department of Neuroscience and Biomedical Engineering, Aalto University School of Science, FI-00076 Aalto, Finland (Dated: 3 June 2020) Surface currents provide a general way to model magnetic fields in source-free volumes. To facilitate the use of surface currents in magneto-quasistatic problems, we have implemented a set of computational tools in a Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to work with surface currents of arbitrary shape, we discretize the currents on triangle meshes using piecewise-linear stream functions. We apply analytical discretizations of integral equations to obtain the magnetic field and potentials associated with the discrete stream function. In addition, we describe the computation of the spherical multipole expansion and a novel surface-harmonic expansion for surface currents, both of which are useful for representing the magnetic field in source-free volumes with a small number of parameters. Last, we share examples related to magnetic shielding and surface-coil design using the presented tools. I. INTRODUCTION Modeling magnetic phenomena with surface currents has various applications in physics and engineering. One large field of applications is surface-coil design, where continuous surface currents are used to design coil wind- ing patterns. Such designs are made in plasma physics 1–3 magnetic resonance imaging (MRI), 4–9 transcranial mag- netic stimulation (TMS), 10,11 magnetic particle imaging (MPI), 12 and in zero-field magnetometry. 13 Further ap- plications of surface-coil design include, .e.g., field control in physics experiments 14,15 and pickup coils of magnetic sensors. 16,17 The methods used in coil design are also involved in modeling eddy current patterns induced in thin conduc- tive sheets 5,18,19 and field fluctuations due to thermal noise currents. 20,21 In addition, surface currents could be applied as equivalent models in magnetic shielding with high-permeability materials. 22,23 Modeling the magnetic field in free space using equivalent current densities on the volume boundary could also have various other appli- cations. This method can be used directly for modeling the field of uniformly magnetized bodies, 24 or the Meiss- ner effect in superconductors, but it could also be used as an equivalent model when interpolating magnetic-field data in e.g., in geomagnetism 25 and biomagnetism. 26,27 Additionally, such a field model could be applied, for ex- ample, when modeling magnetic fields for interference rejection. 28 Although surface currents are useful in modeling mag- netic problems, their application has been limited be- cause of a lack of general computational tools. Most studies have also been restricted to simple geometries. To facilitate surface-current-based methods, we introduce a a) Electronic mail: antti.makinen@aalto.fi novel Python software package bfieldtools (available at https://bfieldtools.github.io). This package pro- vides tools for representing currents on arbitrarily-shaped surfaces, and calculating the associated magnetic field and potentials. Further, tools for designing current pat- terns that generate desired magnetic fields are included. The whole software package is described in two papers. In this paper, we present physical and computational principles of the software and applications that showcase the capability of the presented tools. The accompany- ing paper 29 describes the Python-based implementation in detail and provides examples of its use in different ap- plications from the user perspective. As in many preceding works, 3–7,11,18 in bfieldtools, we model divergence-free surface currents with scalar stream functions. We discretize these functions on a tri- angle mesh using piecewise-linear basis functions equiva- lent to piecewise-constant surface-current density. Com- pared to analytical methods 30–32 that require certain symmetries for the current distributions, discretizing the stream function on a freely shaped triangle mesh allows studying currents and magnetic fields in a wide range of geometries. In this work, we first review the physics of the stream function. As an additional feature to previous works, we relate the stream function to harmonic potential theory. By introducing the magnetic scalar potential to the com- putational framework, analogies to other fields utilizing potential theory can be exploited, facilitating the formu- lation and solution of magneto-quasistatic problems. The main objective of this work is to describe the field calculations and their discretization as they are imple- mented in bfieldtools. Based on previous studies that utilize the linear discretization of the field source, 4,33–35 we obtain a consistent analytical discretization of the in- tegral equations involved in the field calculations. The same principles can also be used to obtain discrete dif- ferential operators on a surface 36,37 , which we utilize in arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020

Upload: others

Post on 17-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

Magnetic-field modeling with surface currents:Physical and computational principles of bfieldtools

Antti J Mäkinen,1, a) Rasmus Zetter,1 Joonas Iivanainen,1 Koos C J Zevenhoven,1 Lauri Parkkonen,1 and Risto JIlmoniemi1Department of Neuroscience and Biomedical Engineering, Aalto University School of Science, FI-00076 Aalto,Finland

(Dated: 3 June 2020)

Surface currents provide a general way to model magnetic fields in source-free volumes. To facilitate the useof surface currents in magneto-quasistatic problems, we have implemented a set of computational tools in aPython package named bfieldtools. In this work, we describe the physical and computational principlesof this toolset. To be able to work with surface currents of arbitrary shape, we discretize the currentson triangle meshes using piecewise-linear stream functions. We apply analytical discretizations of integralequations to obtain the magnetic field and potentials associated with the discrete stream function. In addition,we describe the computation of the spherical multipole expansion and a novel surface-harmonic expansion forsurface currents, both of which are useful for representing the magnetic field in source-free volumes with asmall number of parameters. Last, we share examples related to magnetic shielding and surface-coil designusing the presented tools.

I. INTRODUCTION

Modeling magnetic phenomena with surface currents hasvarious applications in physics and engineering. Onelarge field of applications is surface-coil design, wherecontinuous surface currents are used to design coil wind-ing patterns. Such designs are made in plasma physics1–3magnetic resonance imaging (MRI),4–9 transcranial mag-netic stimulation (TMS),10,11 magnetic particle imaging(MPI),12 and in zero-field magnetometry.13 Further ap-plications of surface-coil design include, .e.g., field controlin physics experiments14,15 and pickup coils of magneticsensors.16,17

The methods used in coil design are also involved inmodeling eddy current patterns induced in thin conduc-tive sheets5,18,19 and field fluctuations due to thermalnoise currents.20,21 In addition, surface currents could beapplied as equivalent models in magnetic shielding withhigh-permeability materials.22,23 Modeling the magneticfield in free space using equivalent current densities onthe volume boundary could also have various other appli-cations. This method can be used directly for modelingthe field of uniformly magnetized bodies,24 or the Meiss-ner effect in superconductors, but it could also be usedas an equivalent model when interpolating magnetic-fielddata in e.g., in geomagnetism25 and biomagnetism.26,27Additionally, such a field model could be applied, for ex-ample, when modeling magnetic fields for interferencerejection.28

Although surface currents are useful in modeling mag-netic problems, their application has been limited be-cause of a lack of general computational tools. Moststudies have also been restricted to simple geometries. Tofacilitate surface-current-based methods, we introduce a

a)Electronic mail: [email protected]

novel Python software package bfieldtools (available athttps://bfieldtools.github.io). This package pro-vides tools for representing currents on arbitrarily-shapedsurfaces, and calculating the associated magnetic fieldand potentials. Further, tools for designing current pat-terns that generate desired magnetic fields are included.The whole software package is described in two papers.In this paper, we present physical and computationalprinciples of the software and applications that showcasethe capability of the presented tools. The accompany-ing paper29 describes the Python-based implementationin detail and provides examples of its use in different ap-plications from the user perspective.

As in many preceding works,3–7,11,18 in bfieldtools,we model divergence-free surface currents with scalarstream functions. We discretize these functions on a tri-angle mesh using piecewise-linear basis functions equiva-lent to piecewise-constant surface-current density. Com-pared to analytical methods30–32 that require certainsymmetries for the current distributions, discretizing thestream function on a freely shaped triangle mesh allowsstudying currents and magnetic fields in a wide range ofgeometries.

In this work, we first review the physics of the streamfunction. As an additional feature to previous works, werelate the stream function to harmonic potential theory.By introducing the magnetic scalar potential to the com-putational framework, analogies to other fields utilizingpotential theory can be exploited, facilitating the formu-lation and solution of magneto-quasistatic problems.

The main objective of this work is to describe the fieldcalculations and their discretization as they are imple-mented in bfieldtools. Based on previous studies thatutilize the linear discretization of the field source,4,33–35we obtain a consistent analytical discretization of the in-tegral equations involved in the field calculations. Thesame principles can also be used to obtain discrete dif-ferential operators on a surface36,37, which we utilize in

arX

iv:2

005.

1006

0v2

[ph

ysic

s.co

mp-

ph]

2 J

un 2

020

Page 2: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

2

the integral formulas.We have also implemented computations for series rep-

resentations of the magnetic field in a source-free vol-ume. First, we review the multipole expansion in termsof spherical harmonics, which is the conventional way ofdescribing such a field. We adapt the multipole expan-sion of 3D current densities28,38,39 to obtain the expan-sion for the field from a surface current on a mesh. Inaddition, we introduce a novel field representation basedon expanding the stream function with the eigenfunc-tions of the surface-Laplacian,40,41 which can be seen asa generalization of the multipole expansion.

Finally, we share a few examples demonstrating the ca-pability of these tools in coil design and magnetic shield-ing. More applications are described in the accompany-ing paper,29 including references to the software imple-mentation.

II. STREAM FUNCTION IN QUASISTATIC MAGNETISM

A. Divergence-free surface currents

A divergence-free current density ~j(~r) on an arbitrarysurface can be expressed with a scalar stream function ψon the surface5,18

~j(~r) = ∇‖ψ(~r)× n(~r) , (1)

where ~r is the position on the surface, n is the unit sur-face normal, and ∇‖ the tangential gradient operator,42i.e., the 3D gradient projected to a tangent plane on thesurface: ∇‖ = ∇− n(n · ∇). As ∇‖ψ(~r) × n(~r) is per-pendicular to ∇‖ψ(~r), the streamlines of the current cor-respond exactly to the isocontours of ψ(~r). For conve-nience, we define the operator ∇‖(·) × n as the rotatedgradient.

By taking a line integral of ψ from ~r0 to ~r on the sur-face, we find that the difference in the stream functionbetween the two ends of the path equals the flux of sur-face current ~j(~r) passing the curve5

ψ(~r)− ψ(~r0) =

∫ ~r

~r0

~j(~r ′) · (d~l′ × n′) , (2)

where d~l′ × n′ is a path differential perpendicular to thedirection of the path. In consequence, a line integralfrom a reference point ~r0 determines the stream functionuniquely on the surface.

From another point of view, the stream function canbe interpreted as a surface density of magnetic dipolesnormal to the surface43,44 (see also Appendix A):

~m(~r) = ψ(~r)n(~r) . (3)

This interpretation of the stream function enables analo-gies to dipole layers involved in, e.g., volume conductorproblems and the calculation of magnetic scalar poten-tials for divergence-free surface currents.

As the surface current density is assumed divergence-free everywhere, the flux of current through any bound-ary on the surface must be zero. Applying Eq. (2) on aboundary, we can deduce that this condition is equiva-lent to ψ(~r) being constant on the boundary. With onlyone boundary, the constant can be set to zero since anadditional constant in ψ(~r) does not affect ~j(~r). Whenthe surface contains holes, the hole boundaries can havetheir own constants. These matters are further discussedin Sec. III when discretizing the stream function.

B. Stream functions and the magnetic scalar potential

The magnetic field ~B originating from sources outside thevolume of interest can be expressed as the gradient of ascalar potential U : ~B = −µ0∇U . As the magnetic fieldis divergence-free, the magnetic scalar potential U is har-monic, i.e., it satisfies Laplace’s equation∇2U = 0. Fromthe theory of harmonic potentials45, we know that U canbe determined uniquely in the volume (up to a constant)when either the potential or the normal derivative of thepotential is specified on the boundary enclosing the vol-ume. Thus, any external source distribution whose po-tential reproduces the boundary conditions of a given U ,can be used to generate U in the volume.

In particular, the boundary condition can be satisfiedby the potential of a dipole density ψ(~r)n on the samesurface.46,47 In potential theory, this source distributionis known as a double layer, equivalent to two parallellayers of opposite charge. In magnetostatic calculations,as discussed above, such a layer of magnetic dipoles cor-responds to a surface-current density ∇‖ψ(~r) × n. Anymagnetic field within a source-free volume can thus beexpressed with a stream function on the boundary of thevolume.

As the discussion above applies only to a closed surface,a stream function on a surface with openings cannot gen-erally represent all possible field patterns in the volume.This must be taken into account in coil designs where thecurrent may only be placed in restricted regions as wellas in field-interpolation tasks with equivalent surface cur-rents. However, the dipole-layer analogy still applies toa stream function on an open surface: the stream func-tion always corresponds to a discontinuity in the scalarpotential18 similar to a dipole layer.46

C. Integral equations

In the following, we layout the integral equations for cal-culating the quasistatic magnetic field and magnetic po-tentials from a stream function. The integrations arediscretized in Sec. III.

In source-free volumes, the magnetic field can be ex-pressed with either a vector or scalar potential45

~B(~r) = ∇× ~A(~r) = −µ0∇U(~r) . (4)

Page 3: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

3

The vector potential of a surface current density canbe written as an integral over the surface S, where thestream function is defined:

~A(~r) =µ0

∫S

~j(~r ′)

|~r − ~r ′|dS′ =

µ0

∫ ∇′‖ψ(~r ′)× n′

|~r − ~r ′|dS′ .

(5)The vector potential can be equivalently written in termsof a magnetic dipole layer ~m = ψn (see Appendix A),which is the more convenient form to express the mag-netic scalar potential

U(~r) =1

∫ψ(~r ′)n′ · ∇′ 1

|~r − ~r ′|dS′ . (6)

Similar dipole-layer potentials are used for the electricfield in volume conductor problems48. Finally, the Biot–Savart formula for the magnetic field is obtained as thecurl of the vector potential

~B(~r) =µ0

∫(∇‖ψ(~r ′)× n′)× ~r − ~r ′

|~r − ~r ′|3dS′ . (7)

In computations, it is useful to expand the stream func-tion with a set of basis functions ψk(~r) as

ψ(~r) =∑k

skψk(~r) . (8)

The coefficients sk parametrize the stream function, en-abling linear-algebraic techniques for processing it. Fur-thermore, the basis functions ψk(~r) can be made to sat-isfy possible boundary conditions so that any combi-nation of them satisfies the same conditions. In somegeometries, ψk(~r) can be chosen as, e.g., sinusoids orspherical harmonics.15,18,43 The rotated gradients of thebasis functions provides a basis set of vector functions~jk(~r) = ∇‖ψk(~r)× n(~r) that expand the current density.

The basis function coefficients sk, forming a columnvector s, can be used to write the inductive energy and re-sistive dissipation power of a surface current as quadraticforms of s12,18,43. The inductive energy, i.e., the energystored in the magnetic field, can be written as s>Ms/2,where the matrix M consists of the mutual inductancesof the current patterns, which can be calculated as45

Mk,l =

∫S

~jk(~r) · ~Al(~r)dS =

∫S

ψk(~r)n · ~Bl(~r)dS, (9)

where ~Al and ~Bl are the magnetic vector potential andthe magnetic field generated by the current pattern ~jl(~r),respectively.

The power dissipation due to resistive heating can bewritten as s>Rs, where

Rk,l =

∫S

~ek(~r) ·~jl(~r)dS =

∫S

1

σs(~r)~jk(~r) ·~jl(~r)dS (10)

is the mutual resistance associated with the two currentpatterns. Here, ~ek is the electric field associated with ~jk

and σs(~r) = σ(~r)d(~r) is the surface conductivity definedby material conductivity σ and surface thickness d. Fur-ther, assuming constant surface conductivity and usingstream functions to describe ~jk and ~jl, we get

Rk,l =1

σs

∫S

[∇‖ψk(~r)× n] · [∇‖ψl(~r)× n]dS

=1

σs

∫S

∇‖ψk(~r) · ∇‖ψl(~r)dS

= − 1

σs

∫S

ψk(~r)∇2‖ψl(~r)dS .

(11)

Partial integration (Gauss theorem) was used to get thelast identity, where ∇2

‖ = ∇‖ · ∇‖ is the surface Lapla-cian or the Laplace–Beltrami operator.40,41 The possibleboundary terms vanish similar to derivation in AppendixA. The relationship between the mutual resistance andthe Laplacian is utilized further in the next section.

III. DISCRETIZATION

A. Piecewise-linear stream function

In bfieldtools, surface-current densities are repre-sented by stream functions on triangle meshes. A tri-angle mesh consists of an ordered collection of vertices~r1, ..., ~rV , forming a point cloud in a 3D space, and ofa set of triangular faces ∆f , each defined by a triplet(i, j, k) of vertex indices.

We discretize the integral and differential equationsdescribed in the previous section by approximating thestream function as linear on each face of the trianglemesh. Such piecewise-linear functions can be conve-niently expressed as in Eq. (8) by choosing the basis func-tions ψk(~r) to be so-called hat functions hi(~r), where theindex i corresponds to the ith vertex of the mesh. Thehat function hi(~r) has the value one at vertex i and zeroat all other vertices. Within triangles, the value is inter-polated linearly (see Fig. 1A). As in Eq. (8), the streamfunction can be written as a sum of the basis functions

ψ(~r) =∑i

sihi(~r) , (12)

where si, the weight for the vertex i, is equal to thecurrent circulating around the vertex on the neighbour-ing triangles. We obtain current-density basis func-tions by taking the rotated gradient of the hat function~ji(~r) = ∇‖hi(~r)× n , which corresponds to an eddy cur-rent circulating around vertex i as illustrated using blackarrows in Fig. 1A.

In each neighbouring triangle, the gradient and rotatedgradient of a hat function are constant and can be ex-

Page 4: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

4

FIG. 1. A: In the lower left corner of the triangle mesh, theblue color indicates a hat function with an increasing functionvalue towards the center vertex. The red arrows represent thegradient of the function. The black arrows correspond to therotated gradient constituting an eddy current around the ver-tex. The green color around the hole indicates a basis functionfor the hole, constructed to satisfy the constant boundary con-dition along the hole boundary. B: Euclidean vectors used inthe differential operators and integral formulas. C: Geometryfor the signed distance functions xi = ~Gf,i · ~dj and df = nf · ~djused in the analytical integral formulas.

pressed using the local geometry36,37 as

∇‖hi(~r) = nf ×~ei

2Af, (13)

∇‖hi(~r)× nf =~ei

2Af. (14)

where Af is the area of the neighbouring triangle f , nfthe triangle normal and ~ei the edge opposing the vertexi in the triangle.

The constant condition on the outer mesh boundarycan be implemented by setting the boundary-vertex val-ues to zero. However, each hole boundary can float at anarbitrary value. To satisfy the constant boundary con-dition on the hole boundaries, we construct a combined

basis function for each hole boundary Ck as

hCk(~r) =

∑i∈Ck

hi(~r) . (15)

These functions are constant along the hole boundariesand can be conceptualized as a current flowing around thehole within the triangles neighbouring the hole vertices(Fig. 1A). The stream function can now be expressed as

ψ(~r) =∑i

sihi(~r) +∑k

skhCk(~r) , (16)

where the first part sums over the inner vertices of themesh and the latter sums over the holes of the mesh.

With this vertex-wise discretization of the stream func-tion, we can represent physical quantities using opera-tors acting on the vertex values si. Stacking the weightssi into a column vector s, linear operators (e.g. thesurface-Laplacian) acting on ψ discretize to matricesthat can be used in linear mappings s 7→ As or inquadratic forms s 7→ s>As. Additionally, fields origi-nating from the discretized current can be expressed as~B(~r) =

∑n~Bn(~r) sn = ~B(~r)>s, where ~B(~r) is a column

vector of the magnetic field contributions at ~r from eachvertex in the mesh.

B. Differential operators

With the hat-function discretization, the gradient of anyscalar function can be calculated on the faces of the meshfrom the neighbouring vertex values.36,37 As this calcula-tion is linear with respect to the vertex values, we definea discrete gradient operator ~G as a map from scalar val-ues at the vertices (i) to Euclidean vectors at the faces(f). Since there are only three non-zero hat functions oneach triangle, the result of this operation can expressedas

( ~Gs)f =∑l

~Gf,lsl = ~Gf,isi + ~Gf,jsj + ~Gf,ksk , (17)

where i, j, and k are the vertices of ∆f . One element ofthe operator is obtained directly from the gradient of thebasis function Eq. (13) as

~Gf,i =

nf × ~ei

2Af, i ∈ ∆f

0, i /∈ ∆f .(18)

The elements of the rotated-gradient operator are definedas

~G⊥f,i = ~Gf,i × nf . (19)

Using the hat functions to discretize the surface-Laplacian operator leads to the so-called cotan formuladerived and applied in the context of partial differ-ential equations as well as in geometry and graphics

Page 5: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

5

FIG. 2. Geometric quantities in the discretization of induc-tance, resistance and Laplacian operators. Laplacian and re-sistance matrices are sparse: only the vertices whose neigh-bouring triangles overlap contribute to to the matrix ele-ments. The inductance matrix is dense with elements describ-ing the coupling between the currents circulating the vertices.

processing.49–52 As second derivatives are ill-defined forhat functions (zero on the faces, infinite on vertices andedges), the discrete Laplacian operator L is understoodas the weak (integrated) form of the surface Laplacian:

Li,j = −∫∇‖hi(~r) · ∇‖hj(~r)dS

= −∑f

(~Gf,i · ~Gf,j)Af ,(20)

Using Eq. (18), the non-zero off-diagonal elements of Lcan be expressed as

Li,j = −1

2

(~e1i · ~e1

j

2A1+~e 2i · ~e 2

j

2A2

)

= −1

2[cot(αij) + cot(βij)]

(21)

where i and j correspond to two neighbouring vertices,angles αij and βij are the angles opposing the edge con-necting the vertices, and indices 1 and 2 correspond tothe two triangles that share the edge, as illustrated inFig. 2. Since constant functions belong to the null spaceof the Laplacian, the diagonal elements can be obtainedas

Li,i = −∑j 6=i

Li,j . (22)

When the surface has boundaries (outer edges orholes), the Laplacian has to be modified. Elements thatcorrespond to the zero-valued boundary can be left out ofthe matrix. Using Eqs. (15) and (16), it can be deducedthat the elements that correspond to the basis functionof a hole boundary can be obtained by summing the rowsand columns associated with the vertices on the bound-ary.

C. Analytical integrals

The analytical integral formulas introduced in this sec-tion are the basic building blocks of bfieldtools mesh

FIG. 3. A: Building blocks of the field operators visualizedas source configurations and their respective potentials. Theintegral Ω is the potential of a uniform dipole density (whitearrows) on a triangle, γ is the potential of a line charge, φ isthe potential of a uniform charge density on a triangle, andΩ is the potential of a linearly varying dipole density on atriangle. B: The magnetic field ~Bi, scalar potential Ui andvector potential ~Ai calculated for a single stream-function el-ement. The stream function (a hat function) is representedby the gray color on the six triangles. The magnetic field(black lines) ~Bi and the scalar potential Ui (red-blue colors)are visualized on the same vertical plane and the vector po-tential (blue arrows) is shown on a horizontal plane above thestream function element. Due to the analytical formulas, thecomputed fields are well-behaving in the vicinity of the mesh.

operators for the magnetic field and magnetic potentials(Sec. II C). As the integrals needed to compute the meshoperators involve singular quantities, the analytical for-mulas behave more smoothly in the proximity of thesource mesh compared to numerical quadratures. Theseformulas have been derived in the literature related toboundary-element methods in bioelectromagnetism33–35

and in antenna modeling53–55. To introduce conceptsand to unify notation, we review the analytical formulas,which can also be seen as potentials of simple charge ordipole configurations visualized in Fig. 3A.

The first building block, used in all the field calcula-tions, is the solid angle subtended at ~r by triangle ∆f

consisting of vertices i, j, and k:33

Ωf (~r) = −∫

∆f

~r − ~r ′

|~r − ~r ′|3· d~S ′ = −2 atan2(N,D) , (23)

where N = ~di × ~dj · ~dk is the numerator and D =

|~di||~dj ||~dk| +∑l=(i,j,k) |~dl|(~dl+1 · ~dl−1) the denominator

for the two-argument inverse tangent function atan2 de-fined as in most standard programming languages. Here,~di = ~r − ~ri is a vector pointing from the vertex i to theevaluation point ~r (see Fig. 1B). The magnetic scalar po-tential of unit (magnetic) dipole density on a triangle canbe computed using the solid angle as −Ωf/(4π).

Page 6: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

6

The second building block is the potential of a linecharge. The potential of a unit line charge on edge ~ei(Fig. 1B) can be obtained as34

γi(~r) =1

|~ei|

∫ ~rk

~rj

1

|~r − ~r ′|dl′ =

−1

|~ei|ln|~dj ||~ei|+ ~dj · ~ei|~dk||~ei|+ ~dk · ~ei

,

(24)where ~rj and ~rk are the two ends of the edge ~ei.

With the two integrals above, we can express the po-tential of a unit charge density on a triangle ∆f :35

φf (~r) =

∫∆f

1

|~r − ~r ′|dS ′

=df (~r)Ωf (~r) +∑l=i,j,k

2Afxl(~r)γl(~r) .(25)

Here, df = nf · ~dl+1 is the signed distance from the trian-gle plane along the plane normal and xl = ~Gf,l·~dl+1 is thenormalized signed distance from the line extended fromthe edge ~el along ~Gf,l such that xl(~rl) = 1. The geometryrelated to these distances can be found in Fig. 1C.

Finally, we present the potential of a linearly varyingdipolar density hi(~r) on a triangle ∆f :34

Ωf,i(~r) =

∫∆f

hi(~r′)~r − ~r ′

|~r − ~r ′|3· d~S ′

=− xi(~r)Ωf (~r) +∑l=i,j,k

ci,ldf (~r)γl(~r) ,(26)

where ci,l = ~ei · ~el/(2Af ). As the notation in Eqs. (25)and (26) differ from the literature, we provide alternative,concise derivations of the formulas in Appendix B usingthe notation of this work.

D. Magnetic field and magnetic potentials

We express the magnetic field and potentials using meshoperators such that, e.g., the magnetic field at ~r is~B(~r) =

∑i~Bi(~r) si = ~B(~r)>s, where the sum is taken

over the vertices of the mesh and ~Bi(~r) is the magneticfield corresponding to hat function hi(~r). When a set offield evaluation points ~rj is given, the operators canbe expressed as coupling matrices, whose elements equalthe coupling between the hat-function currents and thefield components at the evaluation points.

The magnetic field ~Bi(~r) of a constant current den-sity in a triangle is derived in B and, using that result,the magnetic field due to a single hat-function currentbecomes

~Bi(~r) =µ0

∑f∈Ni

∫∆f

~G⊥f,i ×~r − ~r ′

|~r − ~r ′|3dS′

=µ0

∑f∈Ni

Ωf (~r)~Gf,i −∑l=i,j,k

ci,lγl(~r)nf

,

(27)

where Ni denotes the set of triangles neighbouring vertexi as shown in Fig. 2. A corresponding formula expressedin local coordinates of a triangle has been derived byPissanetzky.4

The vector and scalar potentials for the current of ahat stream function hi can be obtained in a straightfor-ward manner using the integrals in Sec. III C. The vec-tor potential [Eq. (5)] can be expressed using the dis-crete rotated-gradient [Eq. (19)] and the integral φf (~r):[Eq. (25)]4,10

~Ai(~r) =µ0

∑f∈Ni

∫∆f

~G⊥f,i|~r − ~r ′|

dS′ =µ0

∑f∈Ni

~G⊥f,iφf (~r) .

(28)

The scalar potential [Eq. (6)] of hi involves only thepotentials of linearly varying dipole densities Ωf,i(~r)[Eq. (26)]

Ui(~r) =1

∑f∈Ni

∫∆f

hi(~r′)n · ~r − ~r ′

|~r − ~r ′|3dS′

=1

∑f∈Ni

Ωf,i(~r) .

(29)

The magnetic field and potentials due to a single hat-function current are illustrated in Fig. 3B.

E. Mutual inductance and resistance

The mutual inductance between two hat-function cur-rents (Fig. 2) can be calculated using Eq. (9) as

Mi,j =µ0

∑f∈Ni

∑f ′∈Nj

∫∆f

∫∆f′

~G⊥f,i · ~G⊥f ′,j

|~r − ~r ′|dSdS′

=µ0

∑f∈Ni

∑f ′∈Nj

~G⊥f,i · ~G⊥f ′,j

∑q

wqφf (~rq) ,

(30)

where the second integral is calculated using quadraturepoints ~rq with weights wq as calculated by Koponen10.We have implemented this approach in bfieldtools, asit naturally handles the singularity in the double integralwhen ∆f = ∆f ′ . Alternatively, the singularity can behandled with an analytical formula for the self element.56

In this basis, the mutual inductance operator M canalso be interpreted as a mapping from the discretizedstream function s to the magnetic flux (integrated normalcomponent) at the mesh vertices. This can be seen fromthe second identity in Eq. (9): by replacing ~mk with thedipole density nhk, the matrix element Mk,l correspondsto the normal magnetic field of current l integrated overthe hat function of vertex k.

For mutual resistance we also have to model the sur-face conductivity σs. Assuming piecewise-constant sur-face conductivity on the triangles, and using Eq. (10), we

Page 7: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

7

obtain the mutual resistance operator as

Ri,j =

∫1

σ(~r)d∇‖hi(~r) · ∇‖hj(~r)dS

=∑f

~Gf,i · ~Gf,jσfd

Af =1

2d

(~e1i · ~e1

j

2A1σ1+~e 2i · ~e 2

j

2A2σ2

),

(31)

where σ1 and σ2 are the conductivities in triangles 1 and2 neighbouring the edge from vertex i to vertex j (seeFig. 2). When σ is constant over the surface, the re-sistance operator is proportional to the discrete surfaceLaplacian Ri,j = − 1

σsLi,j . Several studies6,7,44 use mu-

tual resistance in this form although the relation to thediscrete Laplacian has not been noted.

IV. MAGNETIC FIELD REPRESENTATIONS WITHSOURCE EXPANSIONS

The magnetic field in free space can be expanded as aseries of components, each of which can be interpreted tocorrespond to a certain type of a source-current pattern.A common series used for the static magnetic field is thespherical multipole expansion. This expansion can rep-resent a spatially smoothly varying magnetic field with afew parameters, which can be helpful, e.g., when design-ing coils that generate these types of fields.15,39,57

A disadvantage of the multipole expansion is, however,that the series can diverge in regions where the actualfield is well-behaving. For more general purposes, we in-troduce a representation of magnetic fields based on astream function, which can be viewed as an equivalentsource of the field. We expand the stream function on asurface as a series of functions that we call surface har-monics. The magnetic field patterns of the surface har-monics then yield a representation of the field similar tothe multipole expansion.

A. Multipole expansion with spherical harmonics

The general solution of Laplace’s equation in sphericalcoordinates (~r, θ, ϕ) is45

U(r, θ, ϕ) =

∞∑l=0

l∑m=−l

(αlmr−l−1 +βlmr

l)Ylm(θ, ϕ) , (32)

where αlm and βlm are the multipole coefficients,Ylm(θ, ϕ) are spherical harmonic functions with degreel and order m (|m| ≤ l). The αlm terms involve powersof the inverse distance, representing sources close to ori-gin, whereas the βlm terms represent far-away sources.In bfieldtools, we use the real spherical harmonics,58which are orthonormal with respect to integration overthe full solid angle, i.e,

∫ΩYlmYl′m′dΩ = δll′δmm′ .

FIG. 4. A: Convergence regions of the spherical-harmonicmultipole expansion (SPH) and the surface harmonic expan-sion (SUH) shown in gray. Blue regions depict the volumesof magnetic sources and red regions the volumes where theexpansions do not converge. B: The magnetic scalar poten-tial corresponding to different components of the sphericalharmonic (SPH) and surface harmonic (SUH) inner-sourceexpansions. The scalar potential is depicted by the red–blue colors on the vertical plane and the field source is il-lustrated by the green–brown color. In both expansion, thefirst, fifth, 11th, and 16th component of the series are shown.The bunny surface mesh was decimated from the origi-nal (http://graphics.stanford.edu/data/3Dscanrep/#bunny)and repaired for holes.

We obtain the expansion for the magnetic field by tak-ing the gradient of the scalar potential:

~B(~r) = −µ0∇U(~r)

= −µ0

∞∑l=0

l∑m=−l

[αlm∇(r−l−1Ylm(θ, ϕ))

+ βlm∇(rlYlm(θ, ϕ))]

= −µ0

∞∑l=0

l∑m=−l

[αlmr−l−2

√(l + 1)(2l + 1)~Vlm(θ, ϕ)

+ βlmrl−1√l(2l + 1) ~Wlm(θ, ϕ)] ,

(33)

where ~Vlm = (−(l + 1)Ylmr + ∇1Ylm)/√

(l + 1)(2l + 1)

and ~Wlm = (lYlmr+∇1Ylm)/√l(2l + 1) are vector spher-

ical harmonics.28,59 Here, ∇1 is the angular part of thegradient on a unit sphere.58 Both the set of vector spher-ical harmonics ~Vlm, ~Wlm, and the set of tangential vec-tor spherical harmonics ~Xlm = −r × ∇1Ylm/

√l(l + 1)

are also orthonormal with respect to an inner product∫Ω~flm · ~gl′m′dΩ .

Page 8: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

8

Because the multipole expansion of ~B is linear withrespect to the coefficients, we can express it using linearoperators ~Bα and ~Bβ as

~B(~r) = ~Bα(~r)>α+ ~Bβ(~r)>β , (34)

where the expansions coefficients, truncated at a certaindegree l, are stacked in the column vectors α and β.When the magnetic field is evaluated at a specific setof evaluation points, the linear operators above can beexpressed as coupling matrices that map the given mul-tipole coefficients to field values at the evaluation points.

The coefficients αlm and βlm can be calculated directlyfrom any surface-current distribution ~j(~r) with help ofthe tangential vector spherical harmonics ~Xlm as38,39

αlm =

√l(l + 1)

(l + 1)(2l + 1)

∫(r′)l ~Xlm(~r ′) ·~j(~r′)dS′ (35)

βlm = −√l(l + 1)

l(2l + 1)

∫(r ′)−l−1 ~Xlm(~r ′) ·~j(~r ′)dS′ . (36)

Using these equations together with the stream functionin Eq. (1) and its discretization in Eq. (12), we definemesh operators (matrices) Cα and Cβ that map thestream-function values to the spherical harmonic coef-ficients

α = Cαs (37)β = Cβs . (38)

The convergence of the multipole series may be ana-lyzed by inserting, for example, the inner multipole co-efficients of Eq. (35) into Eq. (32) which yields terms in-volving factors (r′/r)(l−1). If there are any sources withradius r′ greater than the radius of the field point r, thefactors (r′/r)(l−1) approach infinity with growing l andthe series fails to converge. A similar analysis can bemade for the outer sources. These analyses result in con-vergence regions for the expansions shown in Fig. 4A. Asthe figures show, the choice of the origin is crucial forthe convergence, but it cannot be chosen in such a waythat the series would converge everywhere in the volumewhere the scalar potential is defined.

B. Surface-harmonic expansion

With the tools presented in this work, we can generatea field expansion that converges at all points where themagnetic scalar potential is defined [Fig. 4]. The expan-sion is based on the fact that any potential satisfying theLaplace equation can be written in terms of an equiv-alent stream function on a boundary of the domain asdescribed in Sec. II B. Expanding the stream function asa linear combination of basis functions with increasing or-der of spatial detail yields a field representation similarto the spherical multipole expansion.

FIG. 5. Surface-harmonic basis functions, i.e. eigenfunctionsof the surface Laplacian, for three surfaces and their eigen-value spectra normalized with the square root of the surfacearea (

√A). Shown are the first six basis functions for each

surface obtained by numerically solving Eq. (40).

We base the expansion on the eigenfunctions of the(negative) surface Laplacian. These eigenfunctions gen-eralize a sinusoidal function basis, such as the sphericalharmonics basis, to an arbitrary surface (see Fig. 5).Generally, these functions are characterized by the eigen-value equation40,41

−∇2‖vn(~r) = k2

nvn(~r) , (39)

where the eigenvalue k2n corresponds to the squared spa-

tial frequency of the nth eigenfunction vn. The higher theorder n is, the higher the spatial frequency and the morezero crossings vn(~r) has (Fig. 5). In relation to spheri-cal harmonics, we call these functions surface harmonics(SUHs). In geometry processing, they are also known asmanifold harmonics.60

For practical computations, we discretize the functionsas vn(~r) =

∑i Vi,nhi(~r), which leads to a discrete (gen-

eralized) eigenvalue equation41

−Lvn = k2nNvn , (40)

where L is the Laplace operator in Eq. (21) and N is amass matrix taking into account the overlap of hat func-tions, and vn correspond to columns of the matrix V. Asboth L and N are sparse matrices, the vertex coefficientvectors vn can be solved efficiently with sparse solvers.The resulting eigenfunctions vn(~r) are orthonormal withrespect to integration over the surface, which can be ex-pressed in the discrete form as v>nNvm = δn,m.

Page 9: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

9

Substituting the surface-harmonics representation of astream function ψ(~r) =

∑n anvn(~r) to Eq. (6), we can

write the magnetic scalar potential as

U(~r) =1

∫ψ(~r ′)n′ · ∇′ 1

|~r − ~r ′|dS′

=∑i

ai1

∫vn(~r ′)n′ · ∇′ 1

|~r − ~r ′|dS′

=∑i,n

aiVi,n1

∫hi(~r

′)n′ · ∇′ 1

|~r − ~r ′|dS′

=∑i,n

aiVi,nUi(~r) = U(~r)>V a .

(41)

Similarly, the SUH coefficients a can be mapped to themagnetic field as

~B(~r) = ~B(~r)>V a . (42)

Examples of the scalar potentials of the basis functionsvn (SUH) are displayed in Fig. 4B with a comparison tothe multipole expansion (SPH). Compared to the mul-tipole potentials, in the SUH expansion, the potentialsare distributed more uniformly around the correspond-ing surface.

The SUH expansion is not restricted to closed surfaces,but can be applied for stream functions on surfaces withboundaries and any number of holes. Such bases can beused for surface-coil design to decrease the degrees of free-dom when optimizing surface currents, as demonstratedin the accompanying paper.29

Instead of orthogonal stream functions, one may desireorthogonality in their magnetic fields. In that case, thebasis functions can be solved from an discrete eigenvalueequation similar to Eq. (40) by replacing the mass matrixN with the inductance matrix M . To enable physicalinterpretations, L can be replaced by R = L/σs to getthe following eigenvalue equation

Rsn =1

τnMsn. (43)

This equation is related to the independent modes ofeddy currents on the conducting surface; τn is the timeconstant of the nth mode. These modes can be used, forexample, to calculate the time dynamics of eddy-currentinduced fields18 or uncoupled current patterns for ther-mal noise calculations.20,61 It should be noted, however,that M is now a dense matrix, whereas N was verysparse, disabling the use of sparse eigensolvers and in-creasing computation time when building the matrix.

V. COIL DESIGN AND SHIELDING

In this section, we give examples that utilize the de-veloped tools. As the design of surface coils using dis-tributed currents is probably the most prominent appli-cation of these tools, we start by giving a brief overview

FIG. 6. Two examples of surface currents on two surfaces,generating a desired magnetic field confined in a closed vol-ume. Top: Stream functions of two surface-current configu-rations with a primary current on the sphere and a shieldingcurrent on the rounded cube. The currents are designed sothat together they create a homogeneous field (left) and afirst-order gradient field (right). Bottom: the magnetic fieldlines (black) and the corresponding magnetic scalar potentialare plotted on the horizontal plane shown in the 3D plots ontop.

of the coil-design method. In surface-coil design usingtriangle meshes,6,7,11 the coil current is expressed with adiscretized stream function s on the mesh similarly as inour tools. The stream-function s is optimized by min-imizing a cost function while taking into account givenconstraints for, e.g., the field shape. Finally, the coilwires are placed on the isocontours of the stream func-tion to approximate the continuous current density.

Typically, a quadratic form of s such as the magneticenergy s>Ms or the dissipated power s>Rs is used asa cost function. Constraints for the field pattern can beformulated using the mesh operator ~B(~r) and they can beincorporated in quadratic programming as demonstratedin the accompanying paper.29

Here, in the next examples, we take a more theoreticalapproach to surface-coil design and, in particular, to thedesign of self-shielded coils. We also share an exampleof a calculation related to magnetic shielding using thetools described in this work.

A. Perfect shielding by surface currents on a closed surface

When designing coils for target magnetic fields, it is oftenalso desired to control the field outside the volume ofinterest, e.g., to shield the external environment fromthe field of the primary current. For such a situation,a shielding current outside the primary surface can be

Page 10: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

10

FIG. 7. Shielded magnetic fields designed for bi-planar current-domains obtained by minimizing the quadratic objective inEq. (47). Top left: Homogeneous field with minimum inductance weighting (small λ). Top right: Homogeneous field withminimum multipole residual weighting (large λ). Bottom left: Gradient field with minimum inductance weighting. Bottomright: Gradient field with minimum multipole residual weighting. In each case, the magnetic field is visualized using the streamlines and a contour plot of the scalar potential on the horizontal plane shown in the middle. The associated stream functionson the primary and shielding surfaces are shown left from the field plots.

designed.Let us consider a closed surface, inside which a desired

field pattern is to be designed and a second (outer) sur-face, the exterior of which is to be shielded from the field.To derive a set of equations with a unique solution, weagain discretize the surfaces using triangle meshes. Theshielded field pattern can be obtained by designing suit-able stream functions s1 and s2 on the two surfaces sothat their combined field satisfies desired boundary con-ditions. Based on the discussion in Sec. III E, we canwrite the boundary conditions for the normal compo-nent of the field at the surfaces using stacked mutual-inductance matrices M ij as

Ms =

[M11 M12

M21 M22

] [s1

s2

]=

[bn

0

], (44)

where the first row corresponds to the desired magneticfield bn at the inner surface and the second row corre-sponds to the zero condition for the outer surface. Be-cause s>Ms is the total magnetic-field energy of the sys-tem, M is a positive semi-definite matrix. As the onlyzero eigenvalue is the one corresponding to a constantstream function (zero current), the system can be solvedby inverting M deflated for the constant vector.

Two examples demonstrating the perfect shielding ob-tained by solving Eq. (44) are shown Fig. 6. The shieldingby the outer surface corresponds to the situation wherethe exterior volume would be a superconductor that ex-pels all fields so that no magnetic field crosses the outer

surface. This is also analogous to an electrical volume-conductor problem where the exterior volume is insulat-ing, confining the 3D current density.

When the outer current surface contains current-freeregions in it, perfect cancellation of the primary field isgenerally not possible due to a lack of degrees of freedomin the current-pattern design. Next, we demonstrate amethod to optimize the primary and shielding currentsapplicable also to an open surface geometry.

B. Self-shielded currents with an open geometry

We now apply the tools presented in this work forthe design of self-shielded coils in a more realistic bi-planar geometry. Consider a primary coil with streamfunction s1 and a shielding coil with stream functions2. Demonstrated by Harris and coworkers8, a well-performing shielding coil can be designed by minimizingthe magnetic-field energy with respect to s2. Using s1

and s2, the field energy can then be expressed as

EM =1

2

[s>1 s>2

] [M11 M12

M21 M22

] [s1

s2

]=

1

2s>1 M11s1 + s>1 M21s2 +

1

2s>2 M22s2 .

(45)

The minimum (for given s1) can be found by equating thegradient of EM with respect to s2 to zero, which yields a

Page 11: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

11

set of linear equations:

M21s1 +M22s2 = 0 . (46)

Based on Eq. (44), we can now explain why this methodworks: the equation can be interpreted as a conditionthat the normal self-field of the shielding currentM22s2

exactly cancels the normal field component generated bythe primary current M21s1 at the shielding surface. Bysolving Eq. (46) for s2, we can rewrite the field energy asEM = 1

2s>1 (M11 −M12M

−122 M21)s1 = 1

2s>1 M11s1.

We will now optimize the primary current s1 for min-imal energy with an additional constraint. Instead of ahard equality constraint for the desired field, we mod-ify the cost function with a term that penalizes for theresidual in desired multipole moments β:

E(s1) =1

2s>1 M11s1 + λ‖β −Cβs1‖2, (47)

where λ is a trade-off parameter between a perfect multi-pole fit and a minimal field energy. The coupling matrixCβ = Cβ,1 + Cβ,2M

−122 M21 is obtained using the con-

straint in Eq. (46); Cβ,i are matrices that map si to themultipole moments. The solution for s1 that minimizesthe cost function can again be found by equating thegradient ∇s1E(s1) to zero:

s1 = (C>βCβ + M11/λ)−1Cββ . (48)

Examples of shielded configurations generated usingthe method above are shown in Fig. 7. Compared tothe fields in Fig. 6, which are solved for a closed geome-try, these fields leak in the directions where the shieldingsurface is missing. Thus, the placement of the shieldingsurfaces is crucial for the self-shielding performance.

C. Modeling a high-permeability magnetic shield

Magnetic measurements are usually shielded from thelow-frequency fluctuations of the outside magnetic en-vironment with soft ferromagnetic materials such as µ-metal. The purpose of these materials is to guide theexternal magnetic field to create a magnetic void insidethe shield. A downside is that the shield also distortsthe fields generated inside the shield. When the relativepermeability of the shield is very large, the effect of theshield can be approximated by a shield with infinite rel-ative permeability. This leads to a boundary conditionstating that the magnetic field must be normal to theinner surface of the shield or, equivalently, the inner sur-face has to be at equipotential in terms of the magneticscalar potential.45

Let us consider a primary potential Up(~r)>sp gener-ated by a surface current with (discretized) stream func-tion sp inside the magnetic shield. We can satisfy theequipotential condition on the shield by placing a suitableequivalent surface current seq on the shield surface. In

other words, we require that U>p (~r)sp +U eq(~r)>seq = 0holds on the shield. To solve for seq, we apply the con-dition at collocation points on the shield mesh. BecauseU eq(~r)seq is discontinuous across the shield, we apply thecondition at collocation points slightly inwards from theshield surface as ~rj − εnj , where ~rj are the vertex posi-tions of the shield mesh, ε is a small number compared tothe mesh resolution and ~nj are the vertex normal vectors.After solving the resulting set of linear equations for seq,we can estimate the effect of the shield by U eq(~r)>seq atall points inside the shield.

Figure 8 shows an example of a magnetically shieldedconfiguration with a surface-current pattern on a bi-planar surface inside a perfect cylindrical magneticshield. The current patterns on the planes are designedsuch that the field in the target volume, indicated bythe dashed circle, is as homogeneous as possible. Thesecondary field due to the shield amplifies the magneticfield (the gradient of the potential) in the vicinity of theshield outside the target volume. The contribution fromthe cylinder cap also produces minor inhomogeneity inthe magnetic field inside the target volume.

VI. DISCUSSION AND OUTLOOK

We have introduced a set of tools for static and qua-sistatic modeling of divergence-free surface currents andtheir fields. The tools can be used for a variety of tasksfrom surface-coil design and equivalent-source modelingto eddy-current and thermal-noise calculations. Thiswork has covered the central computations implementedin the software, the structure of which is described in theaccompanying paper.29

The computational and theoretical framework lever-ages the interpretation of stream functions as magneticdipole densities normal to the surface. This analogy hasbeen recognized previously43,44, but has not been fullyexploited. In this work, we exploit this interpretation fur-ther for the calculation of the magnetic scalar potential ofa stream function, which we use, e.g., for visualizing themagnetic field. The scalar potential also enables the ap-plication of harmonic potential theory commonly appliedin volume-conductor problems in the form of boundary-element methods (BEM).62,63 The discretizations imple-mented in bfieldtools are directly applicable for BEMcomputations. Namely, the potential of a linearly vary-ing dipole density can be used to calculate the double-layer operator D for linear (hat) basis functions, andthe potential of a constant charge density can be usedfor the single-layer operator S with constant basis func-tions. Additionally, the mutual inductance operatorM isequivalent to yet another operator called N , which mapsa dipole density to the normal field component.46,62

In the future, it can be fruitful to exploit the anal-ogy between quasistatic magnetic problems and electricvolume conductor problems even further. The source ofthe field in the former can be interpreted as magnetic

Page 12: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

12

FIG. 8. A current distribution (coil) on a bi-planar surface(A) inside a perfect cylindrical µ-metal magnetic shield, anequivalent surface current on the shield surface (B), and as-sociated magnetic scalar potentials (C,D,E) plotted on thehorizontal plane shown in A and B. A: The stream functionof the primary current distribution on the bi-planar surfacesinside the shield. B: The equivalent surface-current distri-bution (stream function and surface-current density) repre-senting the induced field source on the µ-metal shield. C:The primary magnetic scalar potential generated by the pri-mary source in A. D: The magnetic scalar potential generatedby the equivalent current in B inside the shield surface. E:The combined potential that satisfies the constant-potentialboundary condition. The dashed circle represents the volumeof interest.

dipoles, whereas in the latter, the sources are currentdipoles. The magnetic scalar potential is analogous tothe electric potential (both satisfy Laplace’s equation),and if we interpret the permeability µ as the counter-part of electrical conductivity σ in a volume conductor,the magnetic field is perfectly analogous to the volumecurrent density. The vector potential in the magneticproblem further corresponds to the magnetic field in avolume conductor problem. This means that the toolspresented in this work could be applied to solve the elec-tric potential in a volume conductor, e.g., for modelingtranscranial magnetic stimulation10,64 or for solving the

bioelectromagnetic forward problem.63The multipole and surface-harmonic expansions im-

plemented in bfieldtools are also suitable for ap-plications in a more general context, e.g., in bio-magnetic experiments or geomagnetism. The multi-pole expansion has been applied to source modelingin bioelectromagnetism.48,65–67 In magnetoencephalogra-phy, it has also been applied in signal space separation(SSS),28 which can be used to design software spatial fil-ters to reject external interference fields. In principle, thesurface-harmonic expansion could be used for the samepurpose with more general convergence properties.

ACKNOWLEDGMENTS

This work has received funding from the Vilho, Yrjöand Kalle Väisälä Foundation (author AM), EuropeanUnion’s Horizon 2020 research and innovation pro-gramme under grant agreement No. 820393 (macQsi-mal), the European Research Council under ERC GrantAgreement no. 678578 (HRMEG), and the Swedish Cul-tural Foundation under grant no. 140635 (author RZ).

DATA AVAILABILITY

Data sharing is not applicable to this article as no newdata were created or analyzed in this study.

REFERENCES

1P. Merkel, Nuclear Fusion 27, 867 (1987).2M. Drevlak, Fusion Technology 33, 106 (1998).3M. Abe, T. Nakayama, S. Okamura, and K. Matsuoka, Physicsof Plasmas 10, 1022 (2003).

4S. Pissanetzky, Measurement Science and Technology 3, 667(1992).

5G. N. Peeren, Journal of Computational Physics 191, 305 (2003).6R. A. Lemdiasov and R. Ludwig, Concepts in Magnetic Reso-nance Part B: Magnetic Resonance Engineering: An EducationalJournal 26, 67 (2005).

7M. S. Poole, Improved equipment and techniques for dynamicshimming in high field MRI, Ph.D. thesis, University of Notting-ham (2007).

8C. T. Harris, D. W. Haw, W. B. Handler, and B. A. Chronik,Journal of Magnetic Resonance 234, 95 (2013).

9S. Hidalgo-Tobon, Concepts in Magnetic Resonance Part A 36,223 (2010).

10L. M. Koponen, J. O. Nieminen, T. P. Mutanen, M. Stenroos,and R. J. Ilmoniemi, Brain stimulation 10, 795 (2017).

11C. Cobos Sánchez, F. J. Garcia-Pacheco, J. M. G. Rodriguez,and J. R. Hill, Engineering Analysis with Boundary Elements88, 156 (2018).

12G. Bringout and T. M. Buzug, IEEE Transactions on Magnetics51, 1 (2014).

13N. Holmes, J. Leggett, E. Boto, G. Roberts, R. M. Hill, T. M.Tierney, V. Shah, G. R. Barnes, M. J. Brookes, and R. Bowtell,NeuroImage 181, 760 (2018).

14S. Afach, G. Bison, K. Bodek, F. Burri, Z. Chowdhuri, M. Daum,M. Fertl, B. Franke, Z. Grujic, V. Hélaine, et al., Journal ofApplied Physics 116, 084510 (2014).

Page 13: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

13

15G. Wyszyński, K. Bodek, S. Afach, G. Bison, Z. Chowdhuri,M. Daum, B. Franke, S. Komposch, B. Lauss, D. Ries, et al.,AIP Advances 7, 035216 (2017).

16B. J. Roth and J. P. Wikswo Jr, Review of Scientific Instruments61, 2439 (1990).

17B. Suits and A. Garroway, Journal of Applied Physics 94, 4170(2003).

18K. C. J. Zevenhoven, S. Busch, M. Hatridge, F. Öisjöen, R. J.Ilmoniemi, and J. Clarke, Journal of Applied Physics 115, 1(2014).

19K. C. J. Zevenhoven, H. Dong, R. J. Ilmoniemi, and J. Clarke,Applied Physics Letters 106, 034101 (2015).

20B. J. Roth, Journal of Applied Physics 83, 635 (1998).21S. Uhlemann, H. Müller, J. Zach, and M. Haider, Ultrami-croscopy 151, 199 (2015), special Issue: 80th Birthday of HaraldRose; PICO 2015 – Third Conference on Frontiers of AberrationCorrected Electron Microscopy.

22P. T. Vesanen, J. O. Nieminen, K. C. Zevenhoven, J. Dabek,J. Simola, J. Sarvas, and R. J. Ilmoniemi, IEEE Transactionson Magnetics 48, 53 (2011).

23T. J. Sumner, J. M. Pendlebury, and K. F. Smith, Journal ofPhysics D: Applied Physics 20, 1095 (1987).

24R. J. Blakely, Potential theory in gravity and magnetic applica-tions (Cambridge University Press, 1996).

25C. A. Mendonca and J. B. Silva, Geophysics 59, 722 (1994).26J. Numminen, S. Ahlfors, R. Ilmoniemi, J. Montonen, andJ. Nenonen, IEEE Transactions on Biomedical Engineering 42,72 (1995).

27H. Hänninen, P. Takala, M. Mäkijärvi, J. Montonen, P. Korho-nen, L. Oikarinen, K. Simelius, J. Nenonen, T. Katila, andL. Toivonen, Basic research in cardiology 96, 405 (2001).

28S. Taulu and M. Kajola, Journal of Applied Physics 97 (2005),10.1063/1.1935742.

29R. Zetter, A. J. Mäkinen, J. Iivanainen, K. C. J. Zevenhoven,R. J. Ilmoniemi, and L. Parkkonen, (2020), arXiv:2005.10056[physics.comp-ph].

30R. Turner, Journal of Physics D: Applied Physics 19, L147(1986).

31S. Crozier, S. Dodd, K. Luescher, J. Field, and D. M. Doddrell,Magma: Magnetic Resonance Materials in Physics, Biology, andMedicine 3, 49 (1995).

32M. A. Brideson, L. K. Forbes, and S. Crozier, Concepts in Mag-netic Resonance: an Educational Journal 14, 9 (2002).

33A. Van Oosterom and J. Strackee, IEEE transactions on Biomed-ical Engineering , 125 (1983).

34J. De Munck, IEEE Transactions on Biomedical Engineering 39,986 (1992).

35A. Ferguson, X. Zhang, and G. Stroink, IEEE Transactions onBiomedical Engineering 41, 455 (1994).

36F. de Goes, M. Desbrun, and Y. Tong, in ACM SIGGRAPH2016 Courses, SIGGRAPH ’16 (ACM, New York, NY, USA,2016) pp. 27:1–27:49.

37M. Botsch, L. Kobbelt, M. Pauly, P. Alliez, and B. Lévy, Polygonmesh processing (CRC press, 2010).

38C. G. Gray, American Journal of Physics 46, 582 (1978).39J. O. Nieminen, P. T. Vesanen, K. C. J. Zevenhoven, J. Dabek,J. Hassel, J. Luomahaara, J. S. Penttilä, and R. J. Ilmoniemi,Journal of Magnetic Resonance 212, 154 (2011).

40B. Levy, in IEEE International Conference on Shape Modelingand Applications 2006 (SMI’06) (2006) pp. 13–13.

41M. Reuter, S. Biasotti, D. Giorgi, G. Patanè, and M. Spagnuolo,Computers & Graphics 33, 381 (2009).

42A. Reusken, IMA Journal of Numerical Analysis 40, 109 (2020).43G. Peeren, Stream function approach for determining optimalsurface currents, Ph.D. thesis, Philips Research (2003).

44H. S. Lopez, F. Liu, M. Poole, and S. Crozier, IEEE Transactionson Magnetics 45, 767 (2009).

45J. D. Jackson, Classical electrodynamics; 3rd ed. (John Wiley &Sons, Inc, New York, NY, 1999).

46J.-C. Nédélec, Acoustic and electromagnetic equations: integralrepresentations for harmonic problems (Springer-Verlag, 2001).

47W. Hackbusch, “Integral equations: Theory and numerical treat-ment,” (1995).

48D. B. Geselowitz, Biophysical journal 7, 1 (1967).49R. H. MacNeal, The solution of partial differential equations bymeans of electrical networks, Ph.D. thesis, California Institute ofTechnology (1949).

50U. Pinkall and K. Polthier, Experimental mathematics 2, 15(1993).

51A. Jacobson, Algorithms and interfaces for real-time deforma-tion of 2d and 3d shapes, Ph.D. thesis, ETH Zurich (2013).

52K. Crane, C. Weischedel, and M. Wardetzky, ACM Transactionson Graphics (TOG) 32, 1 (2013).

53S. Rao, A. Glisson, D. Wilton, and B. Vidula, IEEE Transactionson Antennas and Propagation 27, 604 (1979).

54D. Wilton, S. Rao, A. Glisson, D. Schaubert, O. Al-Bundak, andC. Butler, IEEE Transactions on Antennas and Propagation 32,276 (1984).

55R. D. Graglia, IEEE Transactions on Antennas and Propagation41, 1448 (1993).

56T. F. Eibert and V. Hansen, IEEE transactions on Antennas andPropagation 43, 1499 (1995).

57T. Xia, Z. Miao, S. Chen, H. Wang, and Y. Yao, PLOS ONE12, 1 (2017).

58A. Plattner and F. J. Simons, Applied and Computational Har-monic Analysis 36, 1 (2014).

59E. L. Hill, American Journal of Physics 22, 211 (1954).60B. Vallet and B. Lévy, in Computer Graphics Forum, Vol. 27(Wiley Online Library, 2008) pp. 251–260.

61J. Iivanainen, A. J. Mäkinen, R. Zetter, K. C. J. Zevenhoven,R. J. Ilmoniemi, and L. Parkkonen, in preparation (2020).

62J. Kybic, M. Clerc, T. Abboud, O. Faugeras, R. Keriven, andT. Papadopoulo, IEEE transactions on Medical Imaging 24, 12(2005).

63M. Stenroos, V. Mäntynen, and J. Nenonen, Computer Methodsand Programs in Biomedicine 88, 256 (2007).

64C. C. Sánchez, J. M. G. Rodriguez, Á. Q. Olozábal, andD. Blanco-Navarro, Physics in Medicine & Biology 62, 73 (2016).

65J. P. Wikswo and K. R. Swinney, Journal of Applied Physics 57,4301 (1985).

66G. Nolte and G. Curio, Biophysical journal 73, 1253 (1997).67K. Jerbi, J. C. Mosher, S. Baillet, and R. M. Leahy, Physics inMedicine & Biology 47, 523 (2002).

Appendix A: Stream function as magnetic dipole density

In this appendix, we demonstrate the equivalence of thecurrent-density and dipole-density interpretations of thestream function ψ based on the magnetic vector poten-tial. Let us start from the vector potential of a surface-current density:

~A(~r) =µ0

∫S

~j(~r ′)

RdS′ =

µ0

∫S

∇′‖ψ(~r ′)× n′

RdS′ .

(A1)where ~R = ~r−~r ′ and R = |~R| to simplify the expression.Using the product rule ∇‖ ′(ψ(~r ′)/R) = ∇′‖ψ(~r ′)/R +

ψ(~r ′)∇′‖(1/R) on the tangent plane, we get

~A(~r) =µ0

(∫S

∇′‖ψ(~r ′)

R× n′dS′

+

∫S

ψ(~r ′)n′ ×∇′‖1

RdS′).

(A2)

Page 14: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

14

With Stokes’s theorem on the surface, the first integralcan be converted to a line integral of ψ(~r ′)/R over theboundary of S. As discussed in Sec. II B, the streamfunction must be constant on the boundary. On a singleboundary this constant can be set to zero and the lineintegral vanishes. When the surface contains holes, weget rid of the line integrals, by extending the constantvalues over the holes. This redefinition does not affect ~j,but enables us to express the vector potential as

~A(~r) =µ0

∫S

ψ(~r ′)n′ ×∇′ 1RdS′ , (A3)

where we have applied n × ∇′‖ = n × ∇′. This is thevector potential of a magnetic dipole density ~m(~r ′) =ψ(~r ′)n(~r ′).

The two forms of the mutual inductanceMk,l in Eq. (9)can be obtained using the equivalence of Eqs. (A1) and(A3). We start from

Mk,l =

∫Sk

~jk(~r) · ~Al(~r)dS , (A4)

where ~jk is one surface-current density and ~Al the vectorpotential of surface-current density ~jl. By substitutingthe vector potential in the dipole-density form Eq. (A3),we get a double integral, the integrand of which can bemanipulated as

~jk(~r) ·(µ0

4π~ml(~r

′)×∇′ 1R

)= ~ml(~r

′) ·(µ0

4π~jk(~r)×∇ 1

R

).

(A5)

Identifying the expression in the parenthesis on the rightas the integrand of the Biot–Savart law for ~jk gives

Mk,l = Ml,k =

∫Sk

~mk(~r) · ~Bl(~r)dS . (A6)

Appendix B: Integral formulas for triangles

Here, we present simplified derivations of the integralformulas that involve the solid angle Ωf [Eq. (23)] andline-charge potentials γi [Eq. (24)]. The derivations sharesome common aspects, which we would like to point out.The integrands are first manipulated so that a term thatcontains the solid angle can be separated. The rest of theintegrand can be expressed as surface divergence on thetriangle, for which Gauss’s theorem can be applied, yield-ing expressions containing the line-charge potentials. Fi-nally, the coefficients multiplying the analytical integralsare determined using the geometry of the problem.a. Magnetic field of a constant current on a triangle

Using a basic vector identity for the vector triple product,we can write the integrand in the Biot–Savart formula inEq. (7) for ∇′‖ψ(~r ′)× nf = ~Gf,i × nf = ~G⊥f,i as

~G⊥f,i ×~R

R3=

(~Gf,i ·

~R

R3

)nf −

(nf ·

~R

R3

)~Gf,i , (B1)

where ~R = ~r−~r ′ and R = |~R|. We can further write thescalar part of the first term on the right-hand side as

~Gf,i ·~R

R3= ~Gf,i · ∇′

1

R= ∇′‖ ·

(~Gf,iR

). (B2)

Now, we can integrate the expression over the triangle∆f . Using Gauss’s theorem for the first term, and thedefinition of the solid angle for the second, we get∫

∆f

~G⊥f,i ×∇′1

RdS′

= nf

∫∂∆f

~Gf,iR·(−nf × d~l ′

)+ ~Gf,iΩf (~r) ,

(B3)

where −nf × d~l ′ is a line differential on the triangleboundary ∂∆f perpendicular to d~l ′ pointing out of thetriangle in the triangle plane. Rearranging the scalartriple product inside the first integral, we get∫

∆f

(~Gf,i × nf )×∇′ 1RdS′

= nf (−~Gf,i × nf ) ·∫∂∆f

1

Rd~l ′ − ~Gf,iΩf (~r) ,

= Ωf (~r)~Gf,i −∑l=i,j,k

ci,lγl(~r)nf ,

(B4)

where ci,l = ~G⊥f,i · ~el = (~ei · ~el)/(2Af ).b. Potential of a uniform charge density on a triangle

We decompose the displacement vector as ~R = ~p+df nf ,where ~p is the component along the plane of the triangleand df = nf · ~R is the signed distance from the triangleplane. This leads to the following identity

1

R= −∇′‖ ·

~p

R−d2f

R3. (B5)

Integrating the expression over ∆f , we get

∫∆f

1

RdS = −

∫∂∆f

~p · (−n′f × d~l ′)R

+ df Ω(~r) , (B6)

where the first term has been obtained by Gauss’s theo-rem and the second by applying the definition of the solidangle. Integrating each triangle edge in ∂∆f separatelyand noting that the numerators of these integrals do notdepend on the integration variable, we can express theline integral using the line-charge potentials:∫

∆f

1

RdS = df (~r)Ωf (~r) +

∑l=i,j,k

2Afxl(~r)γl(~r) , (B7)

where xl = ~Gf,l · ~dl+1 is the normalized signed distancemeasured in the triangle plane from the line defined byedge ~el towards node l so that xl(~ri) = 1.

Page 15: arXiv:2005.10060v2 [physics.comp-ph] 2 Jun 2020Python package named bfieldtools. In this work, we describe the physical and computational principles of this toolset. To be able to

15

c. Potential of a linear dipole density With identi-ties df = nf · ~R and hi(~r ′) = ~Gf,i·(~r′−~rj) = ~Gf,i·(~dj− ~R),we can write the potential of a linearly varying dipoledensity as

∫∆f

hi(~r′)~R

R3· d~S ′ = df

∫∆f

~Gf,i · (~dj − ~R)

R3dS ′ . (B8)

Again, let us separate a term containing the solid angle:∫∆f

hi(~r′)~R

R3· d~S ′

= −xi(~r)Ωf (~r)− df∫

∆f

~Gf,i ·~R

R3dS ′.

(B9)

For the latter integral, we can utilize the identity inEq. (B2):∫

∆f

hi(~r′)~R

R3· d~S ′

= −xi(~r)Ωf (~r) +∑l=i,j,k

ci,ldf (~r)γl(~r) .(B10)