diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 578984e8..f5fad964 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -94,6 +94,44 @@ Z = FiniteElementMethod.z_parameters(model, S) The port couples all its edge dofs to each other, which widens the sparsity pattern, so keep the sheet a few elements across. +## Far field, radiated power and directivity + +[`far_field`](@ref) transforms the solution on a closed facet set inside the mesh, the Huygens surface, into +the far field: Love's equivalent currents `J = n × H` and `M = -n × E` on its outward normal radiate into +vacuum, and with `exp(+iωt)` the result is the pair `E_θ, E_φ` of `r e^{ikr} E` as `r → ∞`. The surface must +enclose every source, port and conductor, lie in vacuum, touch no PEC facet and be star-shaped about its +`center` (default: its centroid), which decides the outward side; a sphere or box between the antenna and an +absorbing boundary is the usual choice, and Gmsh physical groups name it. `H = (i/ωμ0) ∇ × E` is averaged +over the cells on both sides of each facet. [`radiated_power`](@ref) integrates the Poynting flux through the +surface (`method = :flux`) or the radiation intensity over the sphere (`method = :far_field`), and +[`directivity`](@ref) is `4πU/P` with the far-field power, so it does not depend on the overall amplitude. + +The far field contains only the outgoing wave, while the flux and the port impedance also feel the wave the +first-order absorbing sphere reflects back, about `1/(kR)²` in amplitude for a dipole field at radius `R` +(5 % at `R = 0.75λ`): directivity and pattern are accurate on coarse meshes, the impedance needs the boundary +a wavelength or more away. + +```julia +using FiniteElementMethod, Ferrite +# `grid` from Gmsh (FerriteGmsh.togrid) with facet sets "outer", "huygens", "strip" and "gap" (in metres). +model = MaxwellModel(grid; pec = ["strip"], absorbing = ["outer"], ports = [LumpedPort("gap"; direction = (0, 0, 1))]) +sweep = solve_sweep(model, [2π * 3.0e8]; fields = true) +Zin = only(FiniteElementMethod.z_parameters(model, sweep.S[:, :, 1])) +sol = MaxwellSolution(model, 2π * 3.0e8, sweep.fields[1][:, 1]) +θs = range(0, π; length = 91) +ff = far_field(sol, "huygens", [Vec(sin(θ), 0.0, cos(θ)) for θ in θs]) # E-plane cut +D = directivity(sol, "huygens", [Vec(1.0, 0.0, 0.0)]) +``` + +`examples/dipole` builds this model for a strip dipole (Gmsh OCC: an absorbing sphere, a Huygens sphere and a +zero-thickness strip with a centre gap, graded towards the strip) and finds its resonance, impedance, +directivity and beamwidth; `test/Maxwell/dipole.jl` runs a coarse version, and the full-size one with +`FEM_MAXWELL_DIPOLE=1`. On the full mesh (1.4e5 edge dofs, a strip of equivalent radius 0.005λ, the absorbing +sphere at 1λ) the dipole resonates at a length of 0.456λ with `R = 69.6 Ω`; at resonance `D = 1.636` +(2.14 dBi, against 1.641 for the thin half-wave dipole), the half-power beamwidth is 78.5° (78.1°) and the +E-plane pattern is within 0.06 dB of `cos(π/2 cos θ)/sin θ` over 30°–150°. The resonant length is still +rising with refinement near the strip (0.437λ, 0.451λ, 0.456λ as the element size there halves). + ```@docs MaxwellModel MaxwellMaterial @@ -118,6 +156,9 @@ MaxwellSweep FiniteElementMethod.umfpack_solver FiniteElementMethod.tangential_mass FiniteElementMethod.port_excitations +far_field +radiated_power +directivity FiniteElementMethod.s_parameters FiniteElementMethod.propagation_constant FiniteElementMethod.cutoff_frequency diff --git a/examples/dipole/dipole.jl b/examples/dipole/dipole.jl new file mode 100644 index 00000000..744ee952 --- /dev/null +++ b/examples/dipole/dipole.jl @@ -0,0 +1,122 @@ +# A strip dipole fed by a lumped port, radiating inside a first-order absorbing sphere: input impedance against +# frequency, the resonance, and the far field (pattern, directivity, half-power beamwidth) at resonance. +# +# julia --project= examples/dipole/dipole.jl +# +# Mesh units are metres and the reference frequency is f0 = c / (1 m), so lengths are in wavelengths at f0. The +# dipole is a zero-thickness PEC strip along z in the plane y = 0, of width w = 4a (the equivalent radius of a +# flat strip is a quarter of its width), with a gap of length `gap` at its centre carrying a 50 Ω LumpedPort. +using FiniteElementMethod, Ferrite, LinearAlgebra +include(joinpath(@__DIR__, "mesh.jl")) + +const DIPOLE_F0 = FiniteElementMethod.C0 # Hz: λ = 1 m + +""" + dipole_model(; length, radius, gap, outer_radius, huygens_radius, h, h_wire = 2radius, growth = 0.3, + max_dofs = 3.0e5) + +The [`MaxwellModel`](@ref) of a strip dipole of `length` and equivalent `radius` (width `4radius`) with a +centre `gap`, in a ball of radius `outer_radius` with the absorbing condition on `"outer"`, a Huygens sphere +`"huygens"` of radius `huygens_radius`, and element size `h_wire` on the strip growing to `h`. A mesh above +`max_dofs` edge dofs is refused before anything is assembled on it. +""" +function dipole_model(; + length, radius, gap, outer_radius, huygens_radius, h, h_wire = 2radius, growth = 0.3, max_dofs = 3.0e5 + ) + grid = antenna_grid(; + outer_radius, huygens_radius, h, h_fine = h_wire, growth, strip = (; length, width = 4radius, gap) + ) + dh = DofHandler(grid) + add!(dh, :E, Nedelec{RefTetrahedron, 1}()) + close!(dh) + ndofs(dh) <= max_dofs || error("the dipole mesh has $(ndofs(dh)) edge dofs, above max_dofs = $max_dofs") + return MaxwellModel( + grid; pec = ["strip"], absorbing = ["outer"], ports = [LumpedPort("gap"; direction = (0, 0, 1), Z0 = 50.0)] + ) +end + +# The sinusoidal-current pattern of a thin dipole of electrical half-length kl/2, |E_θ| up to a constant. +thin_dipole_pattern(θ, half_kl) = abs((cos(half_kl * cos(θ)) - cos(half_kl)) / sin(θ)) + +# The half-power beamwidth (degrees) of a power pattern `D` sampled at increasing `θs` (rad) on (0, π/2] +# ending at broadside, by linear interpolation of the half-power crossing. +function half_power_beamwidth(θs, D) + i = findfirst(>=(D[end] / 2), D) + (i === nothing || i == 1) && error("the pattern does not cross half power on the sampled range") + t = (D[end] / 2 - D[i - 1]) / (D[i] - D[i - 1]) + return rad2deg(π - 2 * (θs[i - 1] + t * (θs[i] - θs[i - 1]))) +end + +""" + dipole_analysis(model; frequencies, length) + +Input impedance `Z(f)` of the dipole `model` of `length` (mesh units) at `frequencies` (Hz), the resonance (where `Im Z` changes sign, +linearly interpolated and then solved again there), and at resonance: `Z`, the input and radiated powers, the +directivity at broadside, the half-power beamwidth and the E-plane pattern (dB, normalised at broadside) on +`θ = 30°:5°:150°` against `cos(π/2 cos θ)/sin θ` (the half-wave target) and against the sinusoidal-current +pattern of the dipole's actual electrical length. +""" +function dipole_analysis(model; frequencies, length) + sweep = solve_sweep(model, 2π .* frequencies) + Z = [only(FiniteElementMethod.z_parameters(model, sweep.S[:, :, k])) for k in eachindex(frequencies)] + k = findfirst(i -> sign(imag(Z[i])) != sign(imag(Z[i + 1])), 1:(Base.length(Z) - 1)) + k === nothing && error("no resonance in the sweep: Im Z = $(imag.(Z))") + t = imag(Z[k]) / (imag(Z[k]) - imag(Z[k + 1])) + f_res = frequencies[k] + t * (frequencies[k + 1] - frequencies[k]) + + at_res = solve_sweep(model, [2π * f_res]; fields = true) + Z_res = only(FiniteElementMethod.z_parameters(model, at_res.S[:, :, 1])) + sol = MaxwellSolution(model, 2π * f_res, at_res.fields[1][:, 1]) + V = FiniteElementMethod.port_voltage(model, 1, sol.u) + I_in = FiniteElementMethod.port_current(model, 1, sol.u; source = 1) + P_in = real(V * conj(I_in)) / 2 + P_flux = radiated_power(sol, "huygens") + P_far = radiated_power(sol, "huygens"; method = :far_field) + + E_plane(θ) = Vec(sin(θ), 0.0, cos(θ)) + D_broadside = directivity(sol, "huygens", [Vec(1.0, 0.0, 0.0), Vec(0.0, 1.0, 0.0)]) + θs = deg2rad.(30:5:150) + pattern = directivity(sol, "huygens", E_plane.(θs)) + pattern_dB = 10 .* log10.(pattern ./ directivity(sol, "huygens", [E_plane(π / 2)])) + half_wave_dB = 20 .* log10.(thin_dipole_pattern.(θs, π / 2)) + half_kl = π * length * f_res / DIPOLE_F0 + sinusoidal_dB = 20 .* log10.(thin_dipole_pattern.(θs, half_kl) ./ thin_dipole_pattern(π / 2, half_kl)) + θ_fine = deg2rad.(1:0.25:90) + hpbw = half_power_beamwidth(θ_fine, directivity(sol, "huygens", E_plane.(θ_fine))) + return (; + frequencies, Z, f_res, resonant_length = length * f_res / DIPOLE_F0, Z_res, P_in, P_flux, P_far, + D_broadside, hpbw, θ_deg = rad2deg.(θs), pattern_dB, + pattern_err_half_wave = maximum(abs, pattern_dB - half_wave_dB), + pattern_err_sinusoidal = maximum(abs, pattern_dB - sinusoidal_dB), ndofs = ndofs(model.dh), + ) +end + +"Strip dipole meshes (lengths in λ at f0): `coarse` (~2e4 dofs, for the Maxwell test group) and `full` (~1.4e5, 8 GB peak)." +const DIPOLE_CASES = ( + coarse = (; + length = 0.48, radius = 5.0e-3, gap = 0.02, outer_radius = 0.6, huygens_radius = 0.4, h = 1 / 7, + h_wire = 0.0075, frequencies = DIPOLE_F0 .* (0.85:0.05:1.0), + ), + full = (; + length = 0.48, radius = 5.0e-3, gap = 0.01, outer_radius = 1.0, huygens_radius = 0.5, h = 1 / 12, + h_wire = 0.00125, growth = 0.4, frequencies = DIPOLE_F0 .* (0.91:0.015:0.97), + ), +) + +""" + run_dipole(case; max_dofs = 3.0e5) + +Build and analyse one of [`DIPOLE_CASES`](@ref) (`:coarse` or `:full`), with the build and analysis times. +""" +function run_dipole(case::Symbol; max_dofs = 3.0e5) + frequencies = DIPOLE_CASES[case].frequencies + mesh = Base.structdiff(DIPOLE_CASES[case], (; frequencies)) + build = @elapsed model = dipole_model(; mesh..., max_dofs) + analysis = @elapsed result = dipole_analysis(model; frequencies, mesh.length) + return (; result..., build, analysis) +end + +if abspath(PROGRAM_FILE) == @__FILE__ + result = run_dipole(Symbol(get(ARGS, 1, "full"))) + @info "strip dipole" result... +end diff --git a/examples/dipole/mesh.jl b/examples/dipole/mesh.jl new file mode 100644 index 00000000..ae0dbdf5 --- /dev/null +++ b/examples/dipole/mesh.jl @@ -0,0 +1,146 @@ +using Ferrite: Ferrite +using FerriteGmsh: FerriteGmsh +using Gmsh: Gmsh, gmsh + +""" + antenna_grid(; outer_radius, huygens_radius, h, h_fine = h, strip = nothing, source_radius = nothing, + growth = 0.3) + +Graded tetrahedral mesh of the ball of radius `outer_radius` about the origin, built with the Gmsh OCC API. +Physical groups, which become the facet and cell sets of the grid: + + - `"outer"`: the outer sphere (for the absorbing boundary); + - `"huygens"`: the closed interior sphere of radius `huygens_radius`; + - with `strip = (; length, width, gap)`: a zero-thickness strip dipole in the plane `y = 0`, along `z`, + `|x| ≤ width/2`, `|z| ≤ length/2`, as the interior facet sets `"strip"` (the two arms, for `pec`) and + `"gap"` (the rectangle `|z| ≤ gap/2` between them, for a `LumpedPort`); + - with `source_radius = a`: the cell set `"source"`, the ball of radius `a`. + +The element size is `h_fine` on the strip and in the source ball, grows by `growth` per unit distance from +them (a size `h_fine + growth d` at distance `d`) and is `h` elsewhere. +""" +function antenna_grid(; + outer_radius, huygens_radius, h, h_fine = h, strip = nothing, source_radius = nothing, growth = 0.3 + ) + Gmsh.initialize() + try + gmsh.option.setNumber("General.Terminal", 0) + gmsh.option.setNumber("General.NumThreads", 1) + gmsh.model.add("antenna") + occ = gmsh.model.occ + tools = [(3, occ.addSphere(0, 0, 0, huygens_radius))] + source_radius === nothing || push!(tools, (3, occ.addSphere(0, 0, 0, source_radius))) + if strip !== nothing + (; length, width, gap) = strip + arm = (length - gap) / 2 + # Rectangles in the plane z = 0, turned into y = 0 by a quarter turn about x: (x, y, 0) -> (x, 0, y). + rects = [ + occ.addRectangle(-width / 2, gap / 2, 0, width, arm), + occ.addRectangle(-width / 2, -length / 2, 0, width, arm), + occ.addRectangle(-width / 2, -gap / 2, 0, width, gap), + ] + occ.rotate([(2, r) for r in rects], 0, 0, 0, 1, 0, 0, π / 2) + append!(tools, [(2, r) for r in rects]) + end + occ.fragment([(3, occ.addSphere(0, 0, 0, outer_radius))], tools) + occ.synchronize() + + # Classify the surfaces by their bounding boxes rather than by OCC's tag numbering. + surfaces = [tag for (_, tag) in gmsh.model.getEntities(2)] + box(tag) = gmsh.model.getBoundingBox(2, tag) + extent(tag) = maximum(abs, box(tag)) + tol = 1.0e-4 * outer_radius + sphere(r) = filter(t -> abs(extent(t) - r) < 1.0e-2 * r && abs(box(t)[2]) > tol, surfaces) + gmsh.model.addPhysicalGroup(2, sphere(outer_radius), -1, "outer") + gmsh.model.addPhysicalGroup(2, sphere(huygens_radius), -1, "huygens") + fine_curves = Int[] + if strip !== nothing + flat = filter(t -> abs(box(t)[2]) < tol && abs(box(t)[5]) < tol, surfaces) + gap_surface = filter(t -> box(t)[6] < strip.gap / 2 + tol && box(t)[3] > -strip.gap / 2 - tol, flat) + gmsh.model.addPhysicalGroup(2, setdiff(flat, gap_surface), -1, "strip") + gmsh.model.addPhysicalGroup(2, gap_surface, -1, "gap") + for t in flat + append!(fine_curves, abs.(last.(gmsh.model.getBoundary([(2, t)], false, false)))) + end + end + if source_radius !== nothing + volumes = [tag for (_, tag) in gmsh.model.getEntities(3)] + ball = filter(t -> maximum(abs, gmsh.model.getBoundingBox(3, t)) < 1.1 * source_radius, volumes) + gmsh.model.addPhysicalGroup(3, ball, -1, "source") + end + gmsh.model.addPhysicalGroup(3, [tag for (_, tag) in gmsh.model.getEntities(3)], -1, "domain") + + fields = Int[] + # Size h_fine within `near` of the field `distance`, growing linearly to h. + function refine(distance, near) + threshold = gmsh.model.mesh.field.add("Threshold") + gmsh.model.mesh.field.setNumber(threshold, "InField", distance) + gmsh.model.mesh.field.setNumber(threshold, "SizeMin", h_fine) + gmsh.model.mesh.field.setNumber(threshold, "SizeMax", h) + gmsh.model.mesh.field.setNumber(threshold, "DistMin", near) + gmsh.model.mesh.field.setNumber(threshold, "DistMax", near + (h - h_fine) / growth) + return push!(fields, threshold) + end + if !isempty(fine_curves) + distance = gmsh.model.mesh.field.add("Distance") + gmsh.model.mesh.field.setNumbers(distance, "CurvesList", unique(fine_curves)) + gmsh.model.mesh.field.setNumber(distance, "Sampling", 400) + refine(distance, 0.0) + end + if source_radius !== nothing + radius = gmsh.model.mesh.field.add("MathEval") + gmsh.model.mesh.field.setString(radius, "F", "Sqrt(x^2 + y^2 + z^2)") + refine(radius, source_radius) + end + if isempty(fields) + constant = gmsh.model.mesh.field.add("MathEval") + gmsh.model.mesh.field.setString(constant, "F", string(h)) + push!(fields, constant) + end + background = gmsh.model.mesh.field.add("Min") + gmsh.model.mesh.field.setNumbers(background, "FieldsList", fields) + gmsh.model.mesh.field.setAsBackgroundMesh(background) + gmsh.option.setNumber("Mesh.MeshSizeExtendFromBoundary", 0) + gmsh.option.setNumber("Mesh.MeshSizeFromPoints", 0) + gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 0) + gmsh.model.mesh.generate(3) + return gmsh_grid() + finally + Gmsh.finalize() + end +end + +# The local node indices of the four facets of a tetrahedron, in Ferrite's facet order (Ferrite.facets is not public). +const TET_FACETS = ((1, 3, 2), (1, 2, 4), (2, 3, 4), (1, 4, 3)) + +""" + gmsh_grid() + +The `Ferrite.Grid` of the current Gmsh model, as `FerriteGmsh.togrid()` makes it (facet sets from the physical +groups of dimension 2, listing every cell next to each facet; cell sets from those of dimension 3), but finding +the facets through a hash of their nodes, in time linear in the mesh size: `togrid` compares every facet with +every cell (about 17 s at 1.8 × 10⁵ cells, against 0.2 s here). +""" +function gmsh_grid() + gmsh.model.mesh.renumberNodes() + gmsh.model.mesh.renumberElements() + # getNodes lists the nodes by entity, not by tag. + tags, coordinates = gmsh.model.mesh.getNodes() + nodes = Vector{Ferrite.Node{3, Float64}}(undef, length(tags)) + for (i, tag) in pairs(tags) + nodes[tag] = Ferrite.Node(Ferrite.Vec{3}(Tuple(coordinates[(3i - 2):(3i)]))) + end + cells, element_tags = FerriteGmsh.toelements(3) + FerriteGmsh.reorient!(cells, nodes) + cellsets = FerriteGmsh.tocellsets(3, element_tags) + facets_of = Dict{Vector{Int}, Vector{Ferrite.FacetIndex}}() + for (i, cell) in pairs(cells), (k, local_nodes) in pairs(TET_FACETS) + facet = map(j -> cell.nodes[j], local_nodes) + push!(get!(facets_of, sort!(collect(facet)), Ferrite.FacetIndex[]), Ferrite.FacetIndex(i, k)) + end + facetsets = Dict{String, Set{Ferrite.FacetIndex}}() + for (name, triangles) in FerriteGmsh.toboundary(2) + facetsets[name] = Set(f for t in triangles for f in facets_of[sort!(collect(t))]) + end + return Ferrite.Grid(cells, nodes; facetsets, cellsets) +end diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 93456ad6..b86dfd24 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -59,9 +59,11 @@ include("maxwell/model.jl") include("maxwell/driven.jl") include("maxwell/sweep.jl") include("maxwell/adjoint.jl") +include("maxwell/farfield.jl") export MaxwellMaterial, MaxwellModel, MaxwellTerm, maxwell_operator, maxwell_operator! export MaxwellSolution, driven_problem, solve_driven, field_values export WavePort, LumpedPort, MaxwellSweep, solve_sweep +export far_field, radiated_power, directivity export MaxwellSensitivities, s_parameter_sensitivities, adjoint_gradient include("precompile.jl") diff --git a/src/maxwell/farfield.jl b/src/maxwell/farfield.jl new file mode 100644 index 00000000..01bdd693 --- /dev/null +++ b/src/maxwell/farfield.jl @@ -0,0 +1,233 @@ +# Near-to-far-field transform of a MaxwellSolution: equivalent currents on a closed facet surface (the +# Huygens surface) radiating into vacuum. + +# E and H (SI units) at the facet quadrature points of a Huygens surface, with the outward normal and the +# area weights; positions in metres. +struct _HuygensSurface + x::Vector{Ferrite.Vec{3, Float64}} + normal::Vector{Ferrite.Vec{3, Float64}} + E::Vector{Ferrite.Vec{3, ComplexF64}} + H::Vector{Ferrite.Vec{3, ComplexF64}} + dS::Vector{Float64} +end + +_facet_nodes(grid, cell, local_facet) = + sort!([Ferrite.getcells(grid, cell).nodes[i] for i in _TET_FACET_NODES[local_facet]]) + +_centroid(grid, nodes) = sum(Ferrite.get_node_coordinate(grid, n) for n in nodes) / length(nodes) + +function _area(grid, (a, b, c)) + xa, xb, xc = (Ferrite.get_node_coordinate(grid, n) for n in (a, b, c)) + return norm(cross(xb - xa, xc - xa)) / 2 +end + +# Every cell next to each geometric facet of the set, whichever of them the set lists. +function _facet_cells(grid, name) + _check_facetset(grid, name) + triangles = Dict{Vector{Int}, Vector{Ferrite.FacetIndex}}() + for (cell, local_facet) in Ferrite.getfacetset(grid, name) + triangles[_facet_nodes(grid, cell, local_facet)] = Ferrite.FacetIndex[] + end + isempty(triangles) && throw(ArgumentError("facet set $(repr(name)) is empty")) + for cell in 1:Ferrite.getncells(grid), local_facet in 1:4 + cells = get(triangles, _facet_nodes(grid, cell, local_facet), nothing) + cells === nothing || push!(cells, Ferrite.FacetIndex(cell, local_facet)) + end + return triangles +end + +# A closed triangulated surface uses every edge an even number of times (twice when it is a manifold). +function _check_closed(triangles, name) + edges = Dict{Tuple{Int, Int}, Int}() + for (a, b, c) in keys(triangles), edge in ((a, b), (a, c), (b, c)) + edges[edge] = get(edges, edge, 0) + 1 + end + open_edges = count(isodd, values(edges)) + open_edges == 0 || + throw(ArgumentError("facet set $(repr(name)) is not a closed surface: $open_edges of its edges bound an odd number of its facets")) + return nothing +end + +# The normals chosen facet by facet are one consistent outward orientation when each edge is traversed once in +# each direction by the triangles oriented by them, and the enclosed volume ∮ x⋅n dS / 3 is positive. +function _check_orientation(grid, oriented, name, center) + edges = Dict{Tuple{Int, Int}, Int}() + volume = 0.0 + for (a, b, c) in oriented + for (i, j) in ((a, b), (b, c), (c, a)) + edges[(i, j)] = get(edges, (i, j), 0) + 1 + edges[(j, i)] = get(edges, (j, i), 0) - 1 + end + xa, xb, xc = (Ferrite.get_node_coordinate(grid, n) for n in (a, b, c)) + volume += dot(xa, cross(xb - xa, xc - xa)) / 6 + end + (all(iszero, values(edges)) && volume > 0) || + throw(ArgumentError("the normals of the Huygens surface $(repr(name)) pointing away from the centre $center are not one outward orientation: the surface must be star-shaped about the centre")) + return nothing +end + +function _huygens_surface(sol::MaxwellSolution, name::AbstractString, center) + (; model, omega, u) = sol + grid, dh, L = model.grid, model.dh, model.length_scale + name = String(name) + triangles = _facet_cells(grid, name) + _check_closed(triangles, name) + if center === nothing + areas = Dict(nodes => _area(grid, nodes) for nodes in keys(triangles)) + center = sum(_centroid(grid, nodes) * a for (nodes, a) in areas) / sum(values(areas)) + end + center = Ferrite.Vec{3, Float64}(Tuple(center)) + fv = _facet_values() + local_dofs = _TET_FACET_EDGE_DOFS + prescribed = Set(model.ch.prescribed_dofs) + surface = _HuygensSurface(Ferrite.Vec{3, Float64}[], Ferrite.Vec{3, Float64}[], Ferrite.Vec{3, ComplexF64}[], Ferrite.Vec{3, ComplexF64}[], Float64[]) + oriented = NTuple{3, Int}[] + for (nodes, facets) in triangles + xf = _centroid(grid, nodes) + inner = nothing + curl_sum = zero(Ferrite.Vec{3, ComplexF64}) + for facet in facets + cell, local_facet = facet[1], facet[2] + model.materials[cell] == MaxwellMaterial() || + throw(ArgumentError("the Huygens surface $(repr(name)) must lie in vacuum; cell $cell next to it is not vacuum")) + dofs = Ferrite.celldofs(dh, cell) + any(i -> dofs[i] in prescribed, local_dofs[local_facet]) && + throw(ArgumentError("the Huygens surface $(repr(name)) touches a PEC facet; it must enclose every conductor")) + Ferrite.reinit!(fv, Ferrite.getcells(grid, cell), Ferrite.getcoordinates(grid, cell), local_facet) + # The curl of a lowest-order Nédélec field is constant in each tetrahedron. + curl_sum += Ferrite.function_curl(fv, 1, u[dofs]) + dot(Ferrite.getnormal(fv, 1), xf - center) > 0 && (inner = facet) + end + inner === nothing && + throw(ArgumentError("facet $nodes of the Huygens surface $(repr(name)) has no cell on the side of the centre $center: the surface must be star-shaped about it")) + # H = (i / ωμ0) ∇ × E, averaged over the cells on both sides, which halves the O(h) bias of one side. + H = im / (omega * model.mu0 * L) * curl_sum / length(facets) + cell, local_facet = inner[1], inner[2] + x = Ferrite.getcoordinates(grid, cell) + Ferrite.reinit!(fv, Ferrite.getcells(grid, cell), x, local_facet) + u_cell = u[Ferrite.celldofs(dh, cell)] + a, b, c = nodes + xa, xb, xc = (Ferrite.get_node_coordinate(grid, n) for n in nodes) + push!(oriented, dot(cross(xb - xa, xc - xa), Ferrite.getnormal(fv, 1)) > 0 ? (a, b, c) : (a, c, b)) + for q in 1:Ferrite.getnquadpoints(fv) + push!(surface.x, Ferrite.spatial_coordinate(fv, q, x) * L) + push!(surface.normal, Ferrite.getnormal(fv, q)) + push!(surface.E, Ferrite.function_value(fv, q, u_cell)) + push!(surface.H, H) + push!(surface.dS, Ferrite.getdetJdV(fv, q) * L^2) + end + end + _check_orientation(grid, oriented, name, center) + return surface +end + +function _unit_direction(d) + r = Ferrite.Vec{3, Float64}(Tuple(d)) + nr = norm(r) + nr > 0 || throw(ArgumentError("a far-field direction must be a nonzero vector")) + return r / nr +end + +# θ̂ and φ̂ at the unit vector r̂; φ = 0 on the z axis. +function _spherical_basis(r̂) + θ, φ = acos(clamp(r̂[3], -1.0, 1.0)), atan(r̂[2], r̂[1]) + θ̂ = Ferrite.Vec{3, Float64}((cos(θ) * cos(φ), cos(θ) * sin(φ), -sin(θ))) + φ̂ = Ferrite.Vec{3, Float64}((-sin(φ), cos(φ), 0.0)) + return θ̂, φ̂ +end + +function _far_field(surface::_HuygensSurface, model, omega, directions) + k = omega * sqrt(model.mu0 * model.eps0) + η = sqrt(model.mu0 / model.eps0) + # Love's equivalent currents on the outward normal n: J = n × H, M = -n × E. + J = cross.(surface.normal, surface.H) .* surface.dS + M = cross.(surface.E, surface.normal) .* surface.dS + E_theta, E_phi = ComplexF64[], ComplexF64[] + for d in directions + r̂ = _unit_direction(d) + N, Lm = zero(Ferrite.Vec{3, ComplexF64}), zero(Ferrite.Vec{3, ComplexF64}) + for (i, x) in pairs(surface.x) + phase = cis(k * dot(r̂, x)) + N += J[i] * phase + Lm += M[i] * phase + end + θ̂, φ̂ = _spherical_basis(r̂) + push!(E_theta, -im * k / 4π * (dot(Lm, φ̂) + η * dot(N, θ̂))) + push!(E_phi, im * k / 4π * (dot(Lm, θ̂) - η * dot(N, φ̂))) + end + return (; E_theta, E_phi) +end + +""" + far_field(sol::MaxwellSolution, surface, directions; center = nothing) + +The far field of `sol` in the unit `directions` (3-vectors, normalised here) as `(; E_theta, E_phi)`, vectors +of the spherical components of `r e^{ikr} E(r r̂)` in volt as `r → ∞` (with `exp(+iωt)` the field is +`E ≈ F e^{-ikr}/r`; `k = ω sqrt(μ0 ε0)`). + +`surface` names a closed facet set (the Huygens surface) inside the mesh, in vacuum, that encloses every +source, port and conductor and touches no PEC facet; outside it the fields must be outgoing (an absorbing +boundary or PML further out). Its equivalent currents `J = n × H` and `M = -n × E` on the outward normal +`n` radiate into vacuum. The set may list each facet from either cell or from both. The outward side is the +one away from `center` (default: the area-weighted centroid of the surface), so the surface must be +star-shaped about `center`, such as a sphere or a box. `E` is taken from the inner cell, and +`H = (i/ωμ0) ∇ × E`, constant in each tetrahedron, is the average of the cells on both sides. At the poles +`θ̂` and `φ̂` are those of `φ = 0`. +""" +function far_field(sol::MaxwellSolution, surface::AbstractString, directions; center = nothing) + return _far_field(_huygens_surface(sol, surface, center), sol.model, sol.omega, directions) +end + +# Directions at the midpoints of an ntheta × nphi grid in (θ, φ) and their solid angles; the midpoint rule in θ +# converges at second order (the relative solid-angle error is 3e-4 at 36 points and 8e-5 at 72), the periodic +# rule in φ can be spectrally accurate. +function _sphere_grid(ntheta, nphi) + θs = (0.5:ntheta) .* (π / ntheta) + φs = (0:(nphi - 1)) .* (2π / nphi) + directions = [Ferrite.Vec{3, Float64}((sin(θ) * cos(φ), sin(θ) * sin(φ), cos(θ))) for φ in φs for θ in θs] + weights = [sin(θ) * (π / ntheta) * (2π / nphi) for φ in φs for θ in θs] + return directions, weights +end + +_intensity(model, ff) = (abs2.(ff.E_theta) .+ abs2.(ff.E_phi)) ./ (2 * sqrt(model.mu0 / model.eps0)) + +function _far_field_power(surface, model, omega, ntheta, nphi) + directions, weights = _sphere_grid(ntheta, nphi) + return dot(weights, _intensity(model, _far_field(surface, model, omega, directions))) +end + +""" + radiated_power(sol::MaxwellSolution, surface; center = nothing, method = :flux, ntheta = 36, nphi = 72) + +The time-averaged power (watt) radiated through the Huygens surface `surface` (see [`far_field`](@ref)). +`method = :flux` integrates the Poynting vector `½ Re(E × H̄)⋅n` over the surface; `method = :far_field` +integrates the radiation intensity `U = (|E_θ|² + |E_φ|²)/2η0` of [`far_field`](@ref) over the sphere on an +`ntheta × nphi` midpoint grid. The far-field integral counts only the outgoing field, the flux the net power, +so they differ by the power the outer boundary reflects back in, besides discretisation error. +""" +function radiated_power( + sol::MaxwellSolution, surface::AbstractString; center = nothing, method::Symbol = :flux, + ntheta::Integer = 36, nphi::Integer = 72 + ) + hs = _huygens_surface(sol, surface, center) + method === :far_field && return _far_field_power(hs, sol.model, sol.omega, ntheta, nphi) + method === :flux || throw(ArgumentError("method must be :flux or :far_field, got $(repr(method))")) + return sum(real(dot(cross(E, conj(H)), n)) * dS for (E, H, n, dS) in zip(hs.E, hs.H, hs.normal, hs.dS)) / 2 +end + +""" + directivity(sol::MaxwellSolution, surface, directions; center = nothing, ntheta = 36, nphi = 72) + +The directivity `D = 4π U / P` (linear, not dB) in the unit `directions`, with `U` the radiation intensity of +[`far_field`](@ref) and `P` its integral over the sphere (`radiated_power(...; method = :far_field)`), so that +`D` averages to 1 over the sphere whatever the error of the overall amplitude. +""" +function directivity( + sol::MaxwellSolution, surface::AbstractString, directions; center = nothing, + ntheta::Integer = 36, nphi::Integer = 72 + ) + hs = _huygens_surface(sol, surface, center) + P = _far_field_power(hs, sol.model, sol.omega, ntheta, nphi) + P > 0 || throw(ArgumentError("the solution radiates no power through $(repr(surface))")) + return 4π .* _intensity(sol.model, _far_field(hs, sol.model, sol.omega, directions)) ./ P +end diff --git a/test/Maxwell/dipole.jl b/test/Maxwell/dipole.jl new file mode 100644 index 00000000..42fe16fa --- /dev/null +++ b/test/Maxwell/dipole.jl @@ -0,0 +1,39 @@ +# A strip dipole near half a wavelength, on a coarse graded Gmsh mesh with named physical groups: the lumped-port +# impedance against frequency, the resonance and the far field at resonance, with loose bands. The full-size run +# (1.4e5 dofs, 8 GB peak, under a minute) is gated by FEM_MAXWELL_DIPOLE=1. +using FiniteElementMethod, Ferrite, LinearAlgebra, Test +include(joinpath(@__DIR__, "..", "..", "examples", "dipole", "dipole.jl")) + +# Thin half-wave dipole targets (sinusoidal current, η0 = 376.73 Ω): D = 4 / Cin(2π) and its beamwidth. +const D_HALF_WAVE = 1.6409 +const HPBW_HALF_WAVE = 78.08 + +function report(name, r) + @info name r.ndofs r.build r.analysis r.resonant_length r.Z_res r.P_in r.P_flux r.P_far D = Tuple(r.D_broadside) r.hpbw r.pattern_err_half_wave r.pattern_err_sinusoidal + @info "$name: Z(f)" collect(zip(r.frequencies ./ DIPOLE_F0, r.Z)) + return r +end + +@testset "coarse strip dipole" begin + r = report("coarse dipole", run_dipole(:coarse; max_dofs = 3.0e4)) + @test 0.42 < r.resonant_length < 0.48 + @test 45 < real(r.Z_res) < 90 + @test abs(imag(r.Z_res)) < 5 + # Lossless: the port's input power leaves through the Huygens surface. + @test r.P_flux ≈ r.P_in rtol = 0.05 + # The absorbing sphere at 0.6λ reflects about 1/(kR)² = 7% of the field back onto the dipole, which the + # flux and the impedance see and the outgoing far field does not. + @test r.P_far ≈ r.P_flux rtol = 0.15 + @test r.D_broadside ≈ [D_HALF_WAVE, D_HALF_WAVE] rtol = 0.05 + @test r.hpbw ≈ HPBW_HALF_WAVE atol = 4 + @test r.pattern_err_half_wave < 0.5 +end + +if get(ENV, "FEM_MAXWELL_DIPOLE", "0") == "1" + @testset "full strip dipole" begin + r = report("full dipole", run_dipole(:full)) + @test r.P_flux ≈ r.P_in rtol = 0.02 + @test r.D_broadside ≈ [D_HALF_WAVE, D_HALF_WAVE] rtol = 0.023 # ±0.1 dB + @test r.pattern_err_half_wave < 0.2 + end +end diff --git a/test/Maxwell/farfield.jl b/test/Maxwell/farfield.jl new file mode 100644 index 00000000..4ee46826 --- /dev/null +++ b/test/Maxwell/farfield.jl @@ -0,0 +1,91 @@ +# Near-to-far-field transform against the exact radiation of a small z-directed current ball (a Hertzian +# dipole): λ = 1 m, an absorbing sphere of radius 0.75λ and a Huygens sphere of radius 0.3λ. +using FiniteElementMethod, Ferrite, LinearAlgebra, Test +include(joinpath(@__DIR__, "..", "..", "examples", "dipole", "mesh.jl")) + +const OMEGA = 2π * FiniteElementMethod.C0 # λ = 1 m +const K0 = 2π +const ETA = sqrt(FiniteElementMethod.MU0 / FiniteElementMethod.EPS0) + +grid = antenna_grid(; outer_radius = 0.75, huygens_radius = 0.3, h = 1 / 12, h_fine = 0.025, source_radius = 0.05) +model = MaxwellModel(grid; absorbing = ["outer"]) +sol = solve_driven(model, OMEGA, Dict("source" => (0.0, 0.0, 1.0))) # J = ẑ A/m² +@info "Hertzian dipole mesh" getncells(grid) ndofs(model.dh) + +# The exact far field of the discrete source, F_θ = (ikη/4π) sin θ ∫ J_z exp(ik r̂⋅x) dV, by the cells' quadrature. +# The input power of the source is -½ Re ∫ E⋅J̄ dV. +cv = CellValues(QuadratureRule{RefTetrahedron}(4), Nedelec{RefTetrahedron, 1}()) +source_points = Tuple{Vec{3, Float64}, Float64}[] +P_in = 0.0 +for cc in CellIterator(model.dh, collect(getcellset(grid, "source"))) + reinit!(cv, cc) + u_cell = sol.u[celldofs(cc)] + for q in 1:getnquadpoints(cv) + push!(source_points, (spatial_coordinate(cv, q, getcoordinates(cc)), getdetJdV(cv, q))) + global P_in -= real(function_value(cv, q, u_cell)[3]) * getdetJdV(cv, q) / 2 + end +end +exact_E_theta(r̂) = im * K0 * ETA / 4π * sqrt(1 - r̂[3]^2) * sum(dV * cis(K0 * dot(r̂, x)) for (x, dV) in source_points) + +@testset "Hertzian dipole far field" begin + θs = deg2rad.(10:10:170) + directions = [Vec(sin(θ) * cos(φ), sin(θ) * sin(φ), cos(θ)) for φ in (0.0, π / 3, π) for θ in θs] + ff = far_field(sol, "huygens", directions) + exact = exact_E_theta.(directions) + err = maximum(abs, ff.E_theta - exact) / maximum(abs, exact) + @info "Hertzian far field" err maximum(abs, ff.E_phi) / maximum(abs, exact) + @test err < 0.05 + @test maximum(abs, ff.E_phi) < 0.02 * maximum(abs, exact) + + D = directivity(sol, "huygens", [Vec(1.0, 0.0, 0.0), Vec(0.0, -1.0, 0.0)]) + P_flux = radiated_power(sol, "huygens") + P_far = radiated_power(sol, "huygens"; method = :far_field) + P_exact = sum(abs2(exact_E_theta(Vec(sin(θ), 0.0, cos(θ)))) / (2 * ETA) * 2π * sin(θ) * (π / 200) for θ in (0.5:200) .* (π / 200)) + @info "Hertzian power and directivity" D P_in P_flux P_far P_exact + @test D ≈ [1.5, 1.5] rtol = 0.01 + @test P_far ≈ P_exact rtol = 0.03 + # The flux counts the net power, which the wave the absorbing sphere reflects back onto the source changes + # by about 2|Γ| ≈ 1/(kR)² (5% at R = 0.75λ, 10% at λ/2); the far field sees only the outgoing wave. + @test P_flux ≈ P_in rtol = 0.02 + @test P_flux ≈ P_far rtol = 0.08 + # The pole is regular: θ̂ = x̂ there and the z-dipole radiates nothing along its axis. + pole = far_field(sol, "huygens", [Vec(0.0, 0.0, 2.0), Vec(0.0, 0.0, -1.0)]) + @test all(isfinite, pole.E_theta) && maximum(abs, pole.E_theta) < 0.02 * maximum(abs, exact) +end + +@testset "Huygens surface orientation and degenerate inputs" begin + # The set lists each facet from both cells; listing it from either one alone gives the same far field. + directions = [Vec(1.0, 0.0, 0.0), Vec(0.6, 0.0, 0.8)] + reference = far_field(sol, "huygens", directions) + # A cell is outside the sphere when it lies on the far side of the facet plane from the origin. + function outside(facet) + x = getcoordinates(grid, facet[1]) + a, b, c = (x[i] for i in FiniteElementMethod._TET_FACET_NODES[facet[2]]) + n = cross(b - a, c - a) + return sign(dot(sum(x) / 4 - a, n)) == sign(dot(a, n)) + end + for side in (true, false) + one_side = Set(f for f in getfacetset(grid, "huygens") if outside(f) == side) + grid.facetsets["one side"] = one_side + @test length(one_side) < length(getfacetset(grid, "huygens")) + ff = far_field(sol, "one side", directions) + @test ff.E_theta ≈ reference.E_theta && ff.E_phi ≈ reference.E_phi + end + @test far_field(sol, "huygens", directions; center = (0.01, 0.0, 0.0)).E_theta ≈ reference.E_theta + + grid.facetsets["cap"] = Set(f for f in getfacetset(grid, "huygens") if getcoordinates(grid, f[1])[1][3] > 0) + @test_throws "is not a closed surface" far_field(sol, "cap", directions) + @test_throws "star-shaped" far_field(sol, "huygens", directions; center = (1.0, 0.0, 0.0)) + @test_throws "nonzero vector" far_field(sol, "huygens", [Vec(0.0, 0.0, 0.0)]) + @test_throws "method must be" radiated_power(sol, "huygens"; method = :poynting) + @test_throws "no facet set" far_field(sol, "nowhere", directions) + + silent = MaxwellSolution(model, OMEGA, zeros(ComplexF64, ndofs(model.dh))) + @test radiated_power(silent, "huygens") == 0 + @test_throws "radiates no power" directivity(silent, "huygens", directions) + + shielded = MaxwellModel(grid; absorbing = ["outer"], pec = ["huygens"]) + @test_throws "touches a PEC facet" far_field(MaxwellSolution(shielded, OMEGA, sol.u), "huygens", directions) + dielectric = MaxwellModel(grid; absorbing = ["outer"], materials = Dict("domain" => MaxwellMaterial(; eps_r = 2.0))) + @test_throws "must lie in vacuum" far_field(MaxwellSolution(dielectric, OMEGA, sol.u), "huygens", directions) +end