-
Notifications
You must be signed in to change notification settings - Fork 493
Expand file tree
/
Copy pathexample_magnetostatics.py
More file actions
281 lines (224 loc) · 9.71 KB
/
example_magnetostatics.py
File metadata and controls
281 lines (224 loc) · 9.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
###########################################################################
# Example Magnetostatics
#
# This example demonstrates solving a 3d magnetostatics problem
# (a copper coil with radial current around a cylindrical iron core)
# using a curl-curl formulation and H(curl)-conforming function space
#
# 1/mu Curl B + j = 0
# Div. B = 0
#
# solved over field A such that B = Curl A,
# and Dirichlet homogeneous essential boundary conditions
#
# This example also illustrates using an ImplicitField to warp a grid mesh
# to a cylindrical domain
###########################################################################
from typing import Any
import numpy as np
import warp as wp
import warp.examples.fem.utils as fem_example_utils
import warp.fem as fem
# Physics constants
MU_0 = wp.constant(np.pi * 4.0e-7) # Vacuum magnetic permeability
MU_c = wp.constant(1.25e-6) # Copper magnetic permeability
MU_i = wp.constant(6.0e-3) # Iron magnetic permeability
@wp.func
def cube_to_cylinder(x: wp.vec3):
# mapping from unit square to unit disk
pos_xz = wp.vec3(x[0], 0.0, x[2])
return wp.max(wp.abs(pos_xz)) * wp.normalize(pos_xz) + wp.vec3(0.0, x[1], 0.0)
@wp.func
def cube_to_cylinder(x: wp.vec3d):
z = wp.float64(0.0)
pos_xz = wp.vec3d(x[0], z, x[2])
return wp.max(wp.abs(pos_xz)) * wp.normalize(pos_xz) + wp.vec3d(z, x[1], z)
@wp.func
def cube_to_cylinder_grad(x: wp.vec3):
# gradient of mapping from unit square to unit disk
pos_xz = wp.vec3(x[0], 0.0, x[2])
if pos_xz == wp.vec3(0.0):
grad = wp.mat33(0.0)
else:
dir_xz = wp.normalize(pos_xz)
dir_grad = (wp.identity(n=3, dtype=float) - wp.outer(dir_xz, dir_xz)) / wp.length(pos_xz)
abs_xz = wp.abs(pos_xz)
xinf_grad = wp.where(
abs_xz[0] > abs_xz[2], wp.vec3(wp.sign(pos_xz[0]), 0.0, 0.0), wp.vec3(0.0, 0.0, wp.sign(pos_xz[2]))
)
grad = dir_grad * wp.max(abs_xz) + wp.outer(dir_xz, xinf_grad)
grad[1, 1] = 1.0
return grad
@wp.func
def cube_to_cylinder_grad(x: wp.vec3d):
z = wp.float64(0.0)
pos_xz = wp.vec3d(x[0], z, x[2])
if pos_xz == wp.vec3d(z):
grad = wp.mat33d(z)
else:
dir_xz = wp.normalize(pos_xz)
dir_grad = (wp.identity(n=3, dtype=wp.float64) - wp.outer(dir_xz, dir_xz)) / wp.length(pos_xz)
abs_xz = wp.abs(pos_xz)
xinf_grad = wp.where(
abs_xz[0] > abs_xz[2], wp.vec3d(wp.sign(pos_xz[0]), z, z), wp.vec3d(z, z, wp.sign(pos_xz[2]))
)
grad = dir_grad * wp.max(abs_xz) + wp.outer(dir_xz, xinf_grad)
grad[1, 1] = wp.float64(1.0)
return grad
@wp.func
def permeability_field(
pos: Any,
core_radius: float,
core_height: float,
coil_internal_radius: float,
coil_external_radius: float,
coil_height: float,
):
x = wp.abs(pos[0])
y = wp.abs(pos[1])
z = wp.abs(pos[2])
r = wp.sqrt(x * x + z * z)
mu_i = type(x)(MU_i)
mu_c = type(x)(MU_c)
mu_0 = type(x)(MU_0)
if r <= core_radius:
return wp.where(y < core_height, mu_i, mu_0)
if r >= coil_internal_radius and r <= coil_external_radius:
return wp.where(y < coil_height, mu_c, mu_0)
return type(x)(MU_0)
@wp.func
def current_field(
pos: Any,
current: float,
coil_internal_radius: float,
coil_external_radius: float,
coil_height: float,
):
x = pos[0]
y = wp.abs(pos[1])
z = pos[2]
r = wp.sqrt(x * x + z * z)
ch = type(x)(coil_height)
ir = type(x)(coil_internal_radius)
er = type(x)(coil_external_radius)
j = type(x)(current)
return wp.where(
y < ch and r >= ir and r <= er,
type(pos)(z, pos.dtype(0.0), -x) * j / r,
type(pos)(pos.dtype(0.0)),
)
@fem.integrand
def curl_curl_form(s: fem.Sample, domain: fem.Domain, u: fem.Field, v: fem.Field, mu: fem.Field):
return wp.dot(fem.curl(u, s), fem.curl(v, s)) / mu(s)
@fem.integrand
def mass_form(s: fem.Sample, domain: fem.Domain, v: fem.Field, u: fem.Field):
return wp.dot(u(s), v(s))
@fem.integrand
def curl_expr(s: fem.Sample, u: fem.Field):
return fem.curl(u, s)
class Example:
def __init__(self, quiet=False, mesh: str = "grid", resolution=32, domain_radius=2.0, current=1.0e6, fp64=False):
# We mesh the unit disk by first meshing the unit square, then building a deformed geometry
# from an implicit mapping field
r = domain_radius
if mesh == "hex":
positions, hex_vidx = fem_example_utils.gen_hexmesh(
bounds_lo=wp.vec3(-r, -r, -r),
bounds_hi=wp.vec3(r, r, r),
res=wp.vec3i(resolution, resolution, resolution),
)
if fp64:
positions = wp.array(positions.numpy(), dtype=wp.types.vector(3, wp.float64))
cube_geo = fem.Hexmesh(hex_vertex_indices=hex_vidx, positions=positions)
elif mesh == "tet":
positions, tet_vidx = fem_example_utils.gen_tetmesh(
bounds_lo=wp.vec3(-r, -r, -r),
bounds_hi=wp.vec3(r, r, r),
res=wp.vec3i(resolution, resolution, resolution),
)
if fp64:
positions = wp.array(positions.numpy(), dtype=wp.types.vector(3, wp.float64))
cube_geo = fem.Tetmesh(tet_vertex_indices=tet_vidx, positions=positions)
elif mesh == "nano":
vol = fem_example_utils.gen_volume(
bounds_lo=wp.vec3(-r, -r, -r),
bounds_hi=wp.vec3(r, r, r),
res=wp.vec3i(resolution, resolution, resolution),
)
cube_geo = fem.Nanogrid(grid=vol, scalar_type=wp.float64 if fp64 else wp.float32)
else:
cube_geo = fem.Grid3D(
bounds_lo=wp.vec3(-r, -r, -r),
bounds_hi=wp.vec3(r, r, r),
res=wp.vec3i(resolution, resolution, resolution),
scalar_type=wp.float64 if fp64 else wp.float32,
)
def_field = fem.ImplicitField(
domain=fem.Cells(cube_geo), func=cube_to_cylinder, grad_func=cube_to_cylinder_grad
)
sim_geo = def_field.make_deformed_geometry(relative=False)
coil_config = {"coil_height": 0.25, "coil_internal_radius": 0.3, "coil_external_radius": 0.4}
core_config = {"core_height": 1.0, "core_radius": 0.2}
domain = fem.Cells(sim_geo)
self._permeability_field = fem.ImplicitField(
domain, func=permeability_field, values=dict(**coil_config, **core_config)
)
self._current_field = fem.ImplicitField(domain, func=current_field, values=dict(current=current, **coil_config))
vec3_type = wp.vec3d if fp64 else wp.vec3
A_space = fem.make_polynomial_space(
sim_geo, degree=1, element_basis=fem.ElementBasis.NEDELEC_FIRST_KIND, dtype=vec3_type
)
self.A_field = A_space.make_field()
B_space = fem.make_polynomial_space(sim_geo, degree=1, element_basis=fem.ElementBasis.LAGRANGE, dtype=vec3_type)
self.B_field = B_space.make_field()
self.renderer = fem_example_utils.Plot()
def step(self):
A_space = self.A_field.space
sim_geo = A_space.geometry
u = fem.make_trial(space=A_space)
v = fem.make_test(space=A_space)
scalar_type = sim_geo.scalar_type
lhs = fem.integrate(
curl_curl_form, fields={"u": u, "v": v, "mu": self._permeability_field}, output_dtype=scalar_type
)
rhs = fem.integrate(mass_form, fields={"v": v, "u": self._current_field}, output_dtype=scalar_type)
# Dirichlet BC
boundary = fem.BoundarySides(sim_geo)
u_bd = fem.make_trial(space=A_space, domain=boundary)
v_bd = fem.make_test(space=A_space, domain=boundary)
dirichlet_bd_proj = fem.integrate(
mass_form, fields={"u": u_bd, "v": v_bd}, assembly="nodal", output_dtype=scalar_type
)
fem.project_linear_system(lhs, rhs, dirichlet_bd_proj)
# solve using Conjugate Residual (numerically rhs may not be in image of lhs)
fem_example_utils.bsr_cg(lhs, b=rhs, x=self.A_field.dof_values, method="cr", max_iters=250, quiet=False)
# compute B as curl(/proxy?url=https%3A%2F%2Fgithub.com%2FA)
fem.interpolate(curl_expr, dest=self.B_field, fields={"u": self.A_field})
def render(self):
self.renderer.add_field("B", self.B_field)
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=32, help="Grid resolution.")
parser.add_argument("--mesh", type=str, default="grid", choices=["tet", "hex", "grid", "nano"], help="Mesh type.")
parser.add_argument("--radius", type=float, default=2.0, help="Radius of simulation domain.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true", help="Suppresses the printing out of iteration residuals.")
parser.add_argument("--fp64", action="store_true", default=False, help="Use double precision (fp64) throughout.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
quiet=args.quiet, mesh=args.mesh, resolution=args.resolution, domain_radius=args.radius, fp64=args.fp64
)
example.step()
example.render()
if not args.headless:
example.renderer.plot({"B": {"streamlines": {"density": 1.0}}})