harmolab.cma — characteristic modes#
High-level entry points first, then the solver, the post-processing and the diagnostics. Theory: Characteristic modes.
Entry points#
- harmolab.cma.cma_algorithm.cma_algorithm(path, frequency: float = None, n_modes: int = 10, regularization_epsilon: float = 1e-10, sort_by: str = 'magnitude', cma_solver: str = 'regularized', rank_tol: float = 1e-06, show: bool = True, save_image: bool = False, show_current_arrows: bool = True, write_report: bool = True, use_gpu: bool = None) ModalData[source]#
High-level CMA pipeline — mirror of radiation_algorithm(), but self- sufficient: the mesh and the impedance matrix are always (re)computed from path.msh at `frequency`, never loaded from a possibly-stale save left by a previous radiation_algorithm() run (see CharacteristicModeSolver's docstring, "Freshness"). Pre-conditions -------------- path.msh must exist. `frequency` is required UNLESS path.mat_impedance already exists from a previous run, in which case its stored frequency is reused as the analysis point (everything else is still recomputed fresh from the current mesh). Parameters ---------- path : SimpleNamespace from setup_save_file_paths() frequency : float, Hz -- analysis frequency. Optional if path.mat_impedance already exists (see above). n_modes : number of characteristic modes to extract regularization_epsilon : relative perturbation applied to R (default 1e-10); only used by cma_solver='regularized' cma_solver : 'regularized' (default) solves on the full space after shifting R by eps*I, so every basis function yields a mode -- including the many that radiate nothing, whose eigenvalue then reflects eps rather than the structure. 'rank_truncated' first projects onto the subspace R spans, returning at most rank(R) modes, all of which radiate. See CMAParameters for the full argument. rank_tol : eigenvalues of R below rank_tol * max count as null space for 'rank_truncated' (default 1e-6) sort_by : 'magnitude' → modes nearest resonance first (|λ| ascending) 'value' → algebraic sort (most negative first) show : display Plotly figures for each mode save_image : also write each mode's current plot to data/fig_image/ as cma_mode<n>_current_<name>.pdf show_current_arrows : overlay black arrows along the modal current direction on each mode plot (default True) write_report : also write a human-readable Markdown report next to the .mat (per-mode significance, characteristic angle, a plain-language reading and the numerical health checks) -- see harmolab.cma.cma_report use_gpu : bool or None, passed to calculate_z_matrice (None = auto-detect, see harmolab.utils.impedance.compute_backend) Returns ------- ModalData with eigenvalues, eigenvectors, frequency, n_modes Example ------- >>> from harmolab.utils.file_path import setup_save_file_paths >>> from harmolab.cma.cma_algorithm import cma_algorithm >>> path = setup_save_file_paths("dipole") >>> modal_data = cma_algorithm(path, frequency=1e9, n_modes=5, show=True)
- class harmolab.cma.cma_frequency_sweep.CMASweepData(frequencies: ndarray, eigenvalues: ndarray, eigenvectors: ndarray, n_modes: int, tracking: object = None)[source]#
Bases:
objectContainer for CMA results across a frequency sweep.
eigenvalues / eigenvectors are always stored in the eigensolver’s own per-frequency ordering (sorted by |lambda| at each point independently), whether or not tracking ran. tracking, when present, is the permutation that turns those labels into mode identities that hold across the sweep; tracked() applies it. Keeping the raw arrays as the stored form means a saved sweep reads the same as it always did, and the untracked view stays available for comparison.
- frequencies: ndarray#
- eigenvalues: ndarray#
- eigenvectors: ndarray#
- n_modes: int#
- tracking: object = None#
- tracked() CMASweepData[source]#
The same sweep with the modes re-indexed so that column k is one physical mode from end to end.
Returns a NEW container; this one is left in raw solver order. Every plotter and report takes a CMASweepData, so the tracked view is used by passing sweep_data.tracked() wherever sweep_data went before. Idempotent: the returned object carries a consumed permutation, so calling tracked() on it again changes nothing.
- Raises:
RuntimeError if the sweep was computed with track=False, since there is –
then no permutation to apply. –
- class harmolab.cma.cma_frequency_sweep.DataManager_cma_sweep[source]#
Bases:
objectSave and load CMA frequency-sweep results, following the DataManager_* pattern.
- static save_data(path, sweep_data: CMASweepData) None[source]#
- static load_data(filename: str) CMASweepData[source]#
- harmolab.cma.cma_frequency_sweep.cma_frequency_sweep(path, freq_start, freq_stop, n_points=41, n_modes=6, regularization_epsilon=1e-10, sort_by='magnitude', cma_solver='regularized', rank_tol=1e-06, use_gpu=None, write_report=True, track=True, tracking_params=None)[source]#
Compute characteristic mode eigenvalues AND eigenvectors across a frequency sweep, reusing calculate_z_matrice_sweep's batched Z(f) assembly -- exactly like frequency_sweep() does for physical antennas -- instead of re-assembling Z from scratch at every frequency. Storing eigenvectors for the whole sweep (not just eigenvalues) is cheap for the mode counts CMA actually uses (a few to a few dozen), and means the "surface current for a given frequency and eigenvalue" step never needs a second solve: just index eigenvectors[freq_idx, :, mode_idx]. Mode ordering and tracking -------------------------- At each frequency, modes are selected/sorted independently by |lambda_n| (see GeneralizedEigenSolver.solve), so "mode index n" in the returned arrays is a per-frequency label, not a mode identity: where two eigenvalue curves cross, the label follows whichever mode happens to be n-th closest to resonance there, and swaps. With track=True (the default) the sweep is additionally correlated across adjacent frequencies (harmolab.cma.mode_tracking) and the permutation that restores mode identity is attached to the result as `sweep_data.tracking`. The stored eigenvalues/eigenvectors stay in raw solver order -- applying the permutation is `sweep_data.tracked()`, which returns a second CMASweepData that every plotter and the report accept unchanged: sweep = cma_frequency_sweep(path, f1, f2) ModalVisualizer.plot_eigenvalues_vs_frequency(sweep.tracked()) print(sweep.tracking.summary()) Tracking reports what it cannot decide rather than hiding it: quasi- degenerate pairs, avoided crossings and steps where the correlation is weak come back as `sweep.tracking.events`. See the mode_tracking module docstring. Mesh freshness -------------- Unlike cma_algorithm()/CharacteristicModeSolver (which load the already -saved path.mat_mesh2 and rely on radiation_algorithm() having been run on the current geometry), this function does NOT trust a possibly-stale path.mat_mesh2: it re-derives points/triangles/edges/vecteurs_rho from path.msh itself, exactly like frequency_sweep() does for physical antennas. Reason: this function assembles its own Z(f) from scratch and never reads path.mat_impedance, so there is no other check (like CharacteristicModeSolver.solve()'s verify_mesh_fingerprint) that would catch an updated .msh whose mesh1/mesh2 hadn't been regenerated to match -- silently sweeping the WRONG geometry otherwise. Pre-conditions -------------- path.msh OR path.mat must exist. When path.msh is present the mesh is always re-derived from it, so path.mat/path.mat_mesh2 need not be up to date beforehand; when it is absent (mesh not produced by gmsh, e.g. a structured pixel grid exported from MATLAB) path.mat is used as the source of truth and left untouched. See cma_mesh.prepare_cma_mesh. Parameters ---------- path : SimpleNamespace from setup_save_file_paths() freq_start, freq_stop : float, sweep bounds in Hz n_points : int, number of frequency points (>=2, both ends included) n_modes : int, number of characteristic modes to track per frequency regularization_epsilon : float, relative perturbation applied to R before eigh sort_by : 'magnitude' | 'value', see GeneralizedEigenSolver cma_solver : 'regularized' (default) or 'rank_truncated' -- see CMAParameters. Truncation returns only rank(R) modes, and rank(R) varies across the sweep, so n_modes must stay below the rank at the LOWEST frequency; the loop raises with that number if it does not. rank_tol : null-space threshold for 'rank_truncated' (default 1e-6) use_gpu : bool or None, passed to calculate_z_matrice_sweep write_report : also write a human-readable Markdown report next to the .mat (resonances, modal Q, bandwidths, health checks) -- see harmolab.cma.cma_report track : correlate the modes across adjacent frequencies and attach the resulting permutation as sweep_data.tracking (default True). Costs one (n_modes x n_modes) correlation per step -- negligible next to the Z(f) assembly -- and does not alter the stored arrays; see "Mode ordering and tracking" above. tracking_params : TrackingParameters, if the defaults need changing (correlation metric, degeneracy tolerance, the TECA -style correction hook) -- see harmolab.cma.mode_tracking Returns ------- CMASweepData
- class harmolab.cma.cma_parameters.CMAParameters(n_modes: int = 10, regularization_epsilon: float = 1e-10, normalize: bool = True, sort_by: str = 'magnitude', solver: str = 'regularized', rank_tol: float = 1e-06)[source]#
Bases:
objectConfiguration for the Characteristic Mode Analysis solver.
- n_modes: int = 10#
- regularization_epsilon: float = 1e-10#
- normalize: bool = True#
- sort_by: str = 'magnitude'#
- solver: str = 'regularized'#
- rank_tol: float = 1e-06#
Solver#
- class harmolab.cma.cma_solver.CharacteristicModeSolver(path, params: CMAParameters, frequency: float = None, use_gpu: bool = None, write_report: bool = True)[source]#
Bases:
objectOrchestrates the full CMA pipeline:
- path.msh → mesh → Z(frequency) → R, X → eigenvalue problem
→ ModalData → surface currents → Plotly figures
Self-sufficient, like cma_frequency_sweep(): both the mesh AND the impedance matrix are always (re)computed here at the requested frequency, never loaded from a possibly-stale save left by a previous radiation_algorithm() run. See “Freshness” below for why.
Pre-conditions#
path.msh OR path.mat exists. When path.msh is present the mesh is re-derived from it; when it is absent (mesh not produced by gmsh, e.g. a structured pixel grid exported from MATLAB) path.mat is used as the source of truth. See cma_mesh.prepare_cma_mesh.
Either frequency is passed explicitly, or path.mat_impedance already exists from a previous run (its stored frequency is then reused as the analysis point – everything else in that file is still recomputed fresh, see below).
Freshness#
_load_mesh() re-derives points/triangles/edges/vecteurs_rho from path.msh every time it can, and solve() then always recomputes Z at frequency from that fresh mesh via calculate_z_matrice() – neither is loaded from disk and trusted as-is. This closes the staleness gap a fingerprint check can only detect after the fact: previously, if path.mat_mesh2 and path.mat_impedance were BOTH left stale together (neither regenerated after a .msh edit), their fingerprints matched each other and a consistency check would pass silently even though neither matched the CURRENT .msh. Always recomputing both from path.msh makes that mismatch structurally impossible instead of merely detected.
- solve() ModalData[source]#
Run the CMA analysis and save results to path.mat_cma.
- Returns:
ModalData
- reconstruct_modal_currents(modal_data: ModalData)[source]#
Reconstruct the surface current on each triangle for every mode.
- Returns:
surface_currents (list of float64 (N_triangles,) — |J| per mode)
current_vectors (list of complex (3, N_triangles) — J per mode, before) – taking the norm, for the current-direction arrows
- visualize(modal_data: ModalData, show: bool = True, save_image: bool = False, show_current_arrows: bool = True) list[source]#
Plot each characteristic mode current on the mesh.
- Parameters:
modal_data (ModalData from solve())
show (display each figure)
save_image (also write each mode to data/fig_image/ as PDF)
show_current_arrows (overlay black arrows along the modal current) – direction (see rwg5.visualize_surface_current)
- Returns:
list of plotly.graph_objects.Figure
- class harmolab.cma.eigen_solver.GeneralizedEigenSolver[source]#
Bases:
objectSolve the CMA generalized eigenvalue problem X·J = λ·R·J
R = Re(Z) radiation-resistance matrix (symmetric, PSD for lossless PEC) X = Im(Z) reactance matrix (symmetric for reciprocal structures)
- static solve(R: ndarray, X: ndarray, params: CMAParameters)[source]#
- Parameters:
R (float64 (N, N) Re(Z), must be positive semi-definite)
X (float64 (N, N) Im(Z), symmetric)
params (CMAParameters)
- Returns:
eigenvalues (float64 (K,) λ_n sorted according to params.sort_by)
eigenvectors (float64 (N, K) J_n as columns, R-orthonormal)
sort_order (int (K,) indices into the full spectrum before selection)
- harmolab.cma.cma_mesh.prepare_cma_mesh(path, verbose=True)[source]#
Build the RWG mesh objects a CMA run needs, preferring a freshly re-derived mesh but tolerating meshes that never came from gmsh.
Two situations have to coexist:
The geometry was built with gmsh, so path.msh exists and is the source of truth. Re-deriving path.mat (and mesh1/mesh2) from it on every run is what keeps an edited .msh from being silently ignored – CMA assembles its own Z, so nothing else downstream would notice a stale cached mesh.
The mesh came from somewhere gmsh cannot produce, e.g. a structured pixel-grid exported to .mat from MATLAB. There is no .msh at all, and path.mat IS the source of truth. Calling extract_msh_to_mat() here would raise (missing file) – or worse, overwrite the only copy of the mesh if a stale .msh happened to be lying around under the same name.
So the .msh is used when present and skipped when not, instead of requiring the caller to comment the conversion in and out by hand.
- Parameters:
path (SimpleNamespace from setup_save_file_paths())
verbose (print a one-line mesh summary and which source was used)
- Returns:
points, triangles, edges, vecteurs_rho
Modal quantities#
- harmolab.cma.characteristic_angle.characteristic_angle(eigenvalues)[source]#
Characteristic angle: delta_n = 180 deg - arctan(lambda_n)
The standard readable stand-in for the raw characteristic value. Unlike lambda_n – which is unbounded and routinely spans five orders of magnitude across a sweep, so that a single barely-radiating mode flattens every other curve onto zero on a linear axis – delta_n is confined to (90 deg, 270 deg) and spreads the modes out evenly:
delta = 90 deg <-> lambda -> +infinity (inductive, stores magnetic energy) delta = 180 deg <-> lambda = 0 (RESONANT, radiates best) delta = 270 deg <-> lambda -> -infinity (capacitive, stores electric energy)
So a mode resonates exactly where its curve crosses 180 deg, and how steeply it crosses is a qualitative indicator of its Q (a steep crossing means a narrow-band, high-Q mode).
Convention checked against AToM’s own characteristicAngle / eigNum outputs on the pixel-grid loop: agreement to 6e-14 deg.
- Parameters:
eigenvalues (array-like, characteristic values lambda_n (real, from) – GeneralizedEigenSolver.solve or a CMASweepData)
- Returns:
ndarray, same shape as eigenvalues, characteristic angle in DEGREES,
in (90, 270)
- harmolab.cma.modal_significance.modal_significance(eigenvalues)[source]#
Modal Significance: MS_n = |1 / (1 + j*lambda_n)| = 1 / sqrt(1 + lambda_n^2) A normalized (0, 1] alternative to the raw characteristic value lambda_n for judging how strongly a mode can be excited by an external source: MS_n = 1 exactly at resonance (lambda_n = 0) and decays as |lambda_n| grows, regardless of sign -- unlike lambda_n itself, which is unbounded and does not saturate away from resonance. Parameters ---------- eigenvalues : array-like, characteristic values lambda_n (real, from GeneralizedEigenSolver.solve or a CMAFrequencySweepResult) Returns ------- ndarray, same shape as `eigenvalues`, modal significance MS_n in (0, 1]
- class harmolab.cma.modal_current.ModalCurrent[source]#
Bases:
objectReconstruct the surface current density on each triangle for one characteristic mode.
The formula is identical to the one used in rwg5 for physical currents:
J⃗(T) = Σ_{m∈T} J_n[m] · (l_m / (2·A_T)) · ρ⃗_m(T)
where J_n[m] is the m-th component of eigenvector n (real, in A).
- static reconstruct(modal_coefficient: ndarray, triangles, edges, vecteurs_rho)[source]#
- Parameters:
modal_coefficient (float64 (N_edges,) — eigenvectors[:, n])
triangles
edges
DataManager_rwg2 (vecteurs_rho — mesh objects from)
- Returns:
surface_current_density (float64 (N_triangles,) — |J_surface| per triangle in A/m)
surface_current_vector (complex (3, N_triangles) — J_surface before taking its) – norm, so callers can draw current-direction arrows. Characteristic eigenvectors are real (eigh on real symmetric R, X), so this vector is real up to dtype: its direction is the mode’s standing-wave current pattern, with no phase to disambiguate.
- harmolab.cma.modal_farfield.compute_modal_farfield(triangles, edges, eigenvector, frequency, light_speed_c, eta)[source]#
Compute the far-field directivity pattern radiated by a single characteristic mode current (an eigenvector treated as a surface current distribution), over the standard far-field sphere.
Why directivity, not gain#
A characteristic mode has no associated physical excitation, so there is no input power P_in to normalize against (unlike harmolab.efield.efield2.radiation_intensity_distribution_over_sphere_surface, which also reports an efficiency against a real P_in – meaningless for a mode in isolation). Directivity D(theta,phi) = 4*pi*U(theta,phi)/P_rad only needs the mode’s own radiated power, and is invariant to the eigenvector’s arbitrary normalization: scaling the “current” by any constant scales U and P_rad by the same factor, so D is unaffected.
- param triangles:
- type triangles:
mesh objects (from DataManager_rwg2.load_data(path.mat_mesh2))
- param edges:
- type edges:
mesh objects (from DataManager_rwg2.load_data(path.mat_mesh2))
- param eigenvector:
ModalData.eigenvectors / CMASweepData.eigenvectors[freq_idx]
- type eigenvector:
float64 (n_edges,) – one column of
- param frequency:
- type frequency:
float, Hz – the frequency this eigenvector was solved at
- param light_speed_c:
(DataManager_rwg3.load_data(path.mat_impedance), or the omega/eta returned by calculate_z_matrice_sweep)
- type light_speed_c:
physical constants for that same solve
- param eta:
(DataManager_rwg3.load_data(path.mat_impedance), or the omega/eta returned by calculate_z_matrice_sweep)
- type eta:
physical constants for that same solve
- returns:
sphere_points, sphere_triangles (the far-field sphere mesh)
gain_db (float64 (n_sphere_points,), directivity in dBi at each sphere vertex)
directivity_linear_max (float, peak linear directivity)
- class harmolab.cma.modal_data.ModalData(eigenvalues: ndarray, eigenvectors: ndarray, frequency: float, n_modes: int, sort_order: ndarray)[source]#
Bases:
objectContainer for CMA results at a single frequency.
- eigenvalues: ndarray#
- eigenvectors: ndarray#
- frequency: float#
- n_modes: int#
- sort_order: ndarray#
Tracking across frequency#
Cross-frequency tracking of characteristic modes.
At every frequency the eigensolver returns an unordered set of modes, and
`GeneralizedEigenSolver._select_and_sign` then labels them by sorting on
`|lambda|`. That label is a property of the sweep point, not of the mode: two
eigenvalue curves that cross exchange their `|lambda|` ranks, so "mode 2"
before the crossing and "mode 2" after it are different physical currents.
Every downstream quantity inherits the problem -- a `lambda_n(f)` curve
develops a kink it does not physically have, a modal-significance peak gets
split between two labels, and the modal current plotted at two frequencies
shows two different patterns under one name.
Tracking replaces the per-frequency label by an identity that follows the
current distribution. Two modes at adjacent frequencies are the same mode when
their currents are the same current, which is measured here by the
`R`-weighted correlation
C_mn = |J_m^H R J_n| / sqrt( (J_m^H R J_m) (J_n^H R J_n) )
with `R = Re(Z)` the radiation operator. The weighting is not cosmetic. The
plain Euclidean overlap `|J_m^H J_n|` treats all `N` degrees of freedom alike,
including the many that radiate nothing at all -- on a real mesh most of them
(measured on the CubeSat mesh at 440 MHz: numerical rank of `R` is 93 out of
760, see `mode_diagnostics`). Two modes can therefore agree closely in the
directions that radiate and still correlate poorly in the Euclidean metric,
because their non-radiating content differs. `R` is exactly the metric in which
the eigenvectors are orthonormal (`scipy.linalg.eigh(X, R)` returns
`J^T R J = I`), so `C_mn` is the cosine between modes in the inner product the
problem is actually posed in, and `C_mm = 1` holds by construction.
Given `C`, assigning modes one-to-one is a linear assignment problem, and
taking each mode's best match greedily is not the same thing: greedy matching
can send two tracks to the same mode and is order-dependent, whereas maximising
the total correlation is what "these are the same K modes, re-labelled" means.
`scipy.optimize.linear_sum_assignment` (Jonker-Volgenant) solves it exactly.
What this module does NOT claim to fix
--------------------------------------
Correlation-based tracking has a known failure mode, and it is reported rather
than papered over. Where two eigenvalues are quasi-degenerate
(`lambda_m ~ lambda_n`), the two-dimensional eigenspace is very nearly
degenerate and any rotation inside it is an equally valid pair of eigenvectors:
the eigenvectors the solver returns there are set by roundoff, `C` approaches
the same value for both candidate assignments, and no correlation metric can
decide between them. `TrackingEvent`s of kind `degeneracy` and
`avoided_crossing` mark those bands, and the margin between the best and the
runner-up assignment is stored per step, so the confidence is visible in the
data instead of being implied by a smooth-looking curve.
Resolving those bands needs information correlation does not carry -- the local
behaviour of `lambda(f)` and of the operator itself, as in the TECA-style
eigenvalue correction of Chen, Pan and Su (IEEE TAP, 2021).
`ModeTrackingCorrection` is the extension point for that: a correction sees the
whole `TrackingStep` (both operators, both spectra, the correlation matrix and
the assignment) and may return a different assignment and/or corrected
eigenvalues. `TECACorrection` is registered and deliberately unimplemented; see
its docstring for the contract.
- class harmolab.cma.mode_tracking.TrackingParameters(metric: str = 'R', weight_at: str = 'mean', correlation_threshold: float = 0.7, margin_threshold: float = 0.1, degeneracy_rel_tol: float = 0.05, fix_sign: bool = True, correction: str = 'none')[source]#
Bases:
objectConfiguration for cross-frequency mode tracking.
- metric: str = 'R'#
- weight_at: str = 'mean'#
- correlation_threshold: float = 0.7#
- margin_threshold: float = 0.1#
- degeneracy_rel_tol: float = 0.05#
- fix_sign: bool = True#
- correction: str = 'none'#
- class harmolab.cma.mode_tracking.TrackingEvent(kind: str, freq_index: int, frequency: float, modes: tuple, detail: str)[source]#
Bases:
objectOne thing worth knowing about a single sweep step.
- kind: str#
- freq_index: int#
- frequency: float#
- modes: tuple#
- detail: str#
- class harmolab.cma.mode_tracking.ModeTrackingResult(frequencies: ndarray, order: ndarray, sign: ndarray, correlation: ndarray, margin: ndarray, events: list = <factory>, metric: str = 'R', correction: str = 'none', corrected_eigenvalues: ndarray = None)[source]#
Bases:
objectThe permutation that turns per-frequency labels into mode identities.
order[i, k] is the raw index, in the solver’s own |lambda|-sorted ordering at frequency i, of the mode belonging to track k. Applying it is what reorder / reorder_eigenvectors do; nothing here modifies the raw sweep arrays, so the untracked view remains available and reproducible.
- frequencies: ndarray#
- order: ndarray#
- sign: ndarray#
- correlation: ndarray#
- margin: ndarray#
- events: list#
- metric: str = 'R'#
- correction: str = 'none'#
- corrected_eigenvalues: ndarray = None#
- property n_modes#
- property n_freq#
- reorder(values)[source]#
Re-index a per-frequency, per-mode array (n_freq, K) into track order.
Works for eigenvalues, and equally for anything derived from them pointwise (modal significance, characteristic angle), since those are computed mode by mode.
- reorder_eigenvectors(eigenvectors)[source]#
Re-index (n_freq, N, K) modal currents, applying the sign continuity.
- applied()[source]#
The same result with the permutation marked as already consumed.
order becomes the identity and sign all ones, while the events and the per-step confidence are kept. This is what a container attaches to arrays it has ALREADY reordered, so that reordering a second time is a no-op instead of a second, wrong permutation.
- property is_applied#
True when order is the identity at every frequency (see applied).
- harmolab.cma.mode_tracking.correlation_matrix(J_a, J_b, R=None, return_overlap=False)[source]#
R-weighted correlation between two sets of modal currents. C_mn = |J_m^H R J_n| / sqrt( (J_m^H R J_m) (J_n^H R J_n) ) Parameters ---------- J_a : (N, Ka) modal currents at the first frequency, one mode per column J_b : (N, Kb) modal currents at the second frequency R : (N, N) symmetric positive-semidefinite weight, normally Re(Z). `None` gives the plain Euclidean overlap (`R = I`). return_overlap : also return the SIGNED overlap `M = J_a^H R J_b`, which the tracker needs to keep the sign of `J` continuous along a track. Returns ------- C : (Ka, Kb) float in [0, 1], 1 for identical currents. Invariant to the scaling and the sign of every column. M : (Ka, Kb), only if `return_overlap` -- signed (complex if the inputs are). Notes ----- A column whose weighted norm is zero radiates nothing, so it has no direction in this metric and cannot be correlated with anything; its row or column of `C` is set to 0 rather than to NaN, which lets the assignment still run and shows up afterwards as a low accepted correlation.
- class harmolab.cma.mode_tracking.TrackingStep(freq_index: int, f_prev: float, f_next: float, J_prev: ndarray, J_next: ndarray, lambda_prev: ndarray, lambda_next: ndarray, R_prev: ndarray, R_next: ndarray, X_prev: ndarray = None, X_next: ndarray = None, correlation: ndarray = None, assignment: ndarray = None, accepted: ndarray = None, margin: ndarray = None, degenerate_pairs: tuple = (), corrected_eigenvalues_next: ndarray = None)[source]#
Bases:
objectEverything known about one sweep step, handed to a correction stage.
A correction may read all of it and return a revised assignment (and optionally corrected_eigenvalues_next). It must not mutate the arrays it is given – they are views into the sweep.
- freq_index: int#
- f_prev: float#
- f_next: float#
- J_prev: ndarray#
- J_next: ndarray#
- lambda_prev: ndarray#
- lambda_next: ndarray#
- R_prev: ndarray#
- R_next: ndarray#
- X_prev: ndarray = None#
- X_next: ndarray = None#
- correlation: ndarray = None#
- assignment: ndarray = None#
- accepted: ndarray = None#
- margin: ndarray = None#
- degenerate_pairs: tuple = ()#
- corrected_eigenvalues_next: ndarray = None#
- class harmolab.cma.mode_tracking.ModeTrackingCorrection[source]#
Bases:
objectBase class for a correction applied after the Hungarian assignment.
The contract is deliberately narrow: refine receives a TrackingStep describing one sweep step and returns it, possibly with assignment and/or corrected_eigenvalues_next replaced. It runs once per step, inside the tracker’s forward loop, so it sees the history only through J_prev / lambda_prev, which are already in track order.
A correction needing the whole sweep at once (a backward pass, or a fit over several steps) should instead be written as a function taking a finished ModeTrackingResult and returning a revised one; this per-step hook is for local corrections.
- name = 'base'#
- refine(step: TrackingStep) TrackingStep[source]#
- class harmolab.cma.mode_tracking.NullCorrection[source]#
Bases:
ModeTrackingCorrectionKeep the Hungarian assignment exactly as it is. The default.
- name = 'none'#
- refine(step: TrackingStep) TrackingStep[source]#
- class harmolab.cma.mode_tracking.TECACorrection[source]#
Bases:
ModeTrackingCorrectionPlaceholder for the TECA-style eigenvalue correction of Chen, Pan and Su (IEEE Trans. Antennas Propag., 2021).
NOT IMPLEMENTED, on purpose: the numerical core is the content of the paper, and guessing at it would produce corrected eigenvalues that look authoritative and are not. What is provided here is the place it plugs into and the data it needs, so implementing it is a matter of filling in refine without touching the tracker.
What the hook already gives you#
step.J_prev (track order) and step.J_next (raw order), on the same RWG basis, together with step.lambda_prev / step.lambda_next;
step.R_prev/step.R_next and, when the caller passed them, step.X_prev/step.X_next, so Z = R + jX can be rebuilt at both ends of the step and a local derivative in frequency formed by finite differences;
step.correlation and step.assignment, i.e. the correlation-only answer the correction is meant to improve on, plus step.margin, which says how close the runner-up assignment was;
step.degenerate_pairs, the tracks the correlation metric cannot separate – exactly the bands such a correction exists to handle.
What an implementation must return#
The same TrackingStep with, at minimum, assignment set to a permutation of range(K) (one raw index per track, no repeats – the tracker validates this). If the scheme also revises the characteristic values, put the revised values for the LATER frequency, in RAW index order, into corrected_eigenvalues_next; they are collected into ModeTrackingResult.corrected_eigenvalues and left beside the raw eigenvalues rather than overwriting them.
- name = 'teca'#
- refine(step: TrackingStep) TrackingStep[source]#
- harmolab.cma.mode_tracking.get_correction(name)[source]#
Instantiate a registered correction stage by name.
- class harmolab.cma.mode_tracking.ModeTracker(params: TrackingParameters = None)[source]#
Bases:
objectFollow K characteristic modes across a frequency sweep.
Streaming by design: push one frequency at a time and only two consecutive frequencies are ever held, so a sweep can be tracked inside the assembly loop without keeping every R(f) (an (n_freq, N, N) array) alive for the tracking’s sake.
>>> tracker = ModeTracker(TrackingParameters()) >>> for f, lam, J, R in sweep_points: ... tracker.push(f, lam, J, R=R) >>> result = tracker.finalize() >>> lam_tracked = result.reorder(eigenvalues)
- push(frequency, eigenvalues, eigenvectors, R=None, X=None)[source]#
Add one frequency point.
- Parameters:
frequency (float, Hz -- must increase monotonically)
eigenvalues ((K,) lambda_n in the solver's raw order)
eigenvectors ((N, K) J_n in the same raw order)
R ((N, N) Re(Z) at this frequency. Required for) – metric=’R’; ignored for metric=’identity’.
X ((N, N) Im(Z), optional -- only carried through to a) – correction stage, never used by the correlation itself.
- finalize() ModeTrackingResult[source]#
Close the sweep and return the permutation plus the diagnostics.
- harmolab.cma.mode_tracking.track_sweep(frequencies, eigenvalues, eigenvectors, R_list=None, X_list=None, params: TrackingParameters = None) ModeTrackingResult[source]#
Track a sweep that has already been computed.
- Parameters:
frequencies ((n_freq,) Hz, increasing)
eigenvalues ((n_freq, K) raw per-frequency order)
eigenvectors ((n_freq, N, K) same order)
R_list ((n_freq, N, N) or a sequence of (N, N) -- Re(Z) per frequency.) – Required for the default metric=’R’.
X_list (optional Im(Z) per frequency, carried to a correction stage.)
params (TrackingParameters)
- Returns:
ModeTrackingResult
Diagnostics, reports, plots#
Numerical sanity checks on an EFIE/MoM impedance matrix Z, independent of CMA itself – useful whenever GeneralizedEigenSolver needs unusually large regularization (see eigen_solver.py), to tell apart two very different root causes:
Z is physically/numerically healthy, and R = Re(Z) is just close to singular because the structure is electrically small at that frequency (most RWG basis functions barely radiate there) – expected, not a bug.
Z itself is wrong (assembly bug, mesh defect, wrong quadrature order, …), which would typically also show up as broken reciprocity and/or R eigenvalues that are negative by much more than floating-point noise.
- harmolab.cma.z_matrix_diagnostics.check_reciprocity(Z)[source]#
Check Z's reciprocity (symmetry). The EXACT Galerkin MoM impedance matrix is symmetric: testing and basis functions are the same set, and the free-space Green's function is symmetric in its two arguments, so nothing in the physics breaks Z = Z^T. Since the assembler fills only m <= n and mirrors (impmet's _mirror_upper_triangle), production matrices satisfy Z = Z^T EXACTLY, and this function reads 0. That is worth being explicit about: a zero here confirms the mirroring ran, and nothing else. It cannot fail, so it cannot warn -- a completely wrong kernel would also read 0. What used to make this measurement informative was that the two halves were computed independently, by schemes that treat the pair's two triangles differently: SELF uses Gauss-Dunavant on the TEST triangle and Duffy on the SOURCE one, EDGE/VERTEX integrates the 1/R half of the kernel analytically over the SOURCE only. Their disagreement was therefore a direct readout of the quadrature's own error -- 5e-5 to 5e-4 when healthy, and 0.994 the one time a closed-form 1/R integral silently assumed the observation point was coplanar with the source triangle. That is what caught the bug. To recover that signal, assemble with impedance_matrix_z(..., full_fill=True) and pass the result here: at twice the fill cost, the two halves are independent again and the number means something. See test/test_impedance_non_coplanar.py, which keeps a standing 3D case. Two limits are worth knowing before reading a small value as "Z is accurate", because it does not mean that. This bounds the EDGE/VERTEX branch and, in practice, nothing else: a SELF pair puts both integrals on the SAME triangle, so swapping (m,n) leaves the geometry unchanged and its error very nearly cancels -- measured 8e-7 here against a true SELF error around 3e-2 on the same mesh. And on a small, locally symmetric mesh a vertex-permutation- invariant Gauss rule can make the two halves' errors cancel outright, so this reads roundoff while the branch is 1e-3 wrong. On a real mesh it does track the true EDGE error closely (1.27e-3 against 1.14e-3 on the CubeSat mesh) -- it is a lower bound on the assembly's error, never a measure of it. Parameters ---------- Z : complex (N, N) ndarray Returns ------- dict with: max_abs_diff : max|Z - Z^T| max_abs_z : max|Z| relative_asymmetry : max_abs_diff / max_abs_z (expect 5e-5 to 5e-4 with the default settings, depending on mesh size; orders of magnitude above that means something is actually wrong)
- harmolab.cma.z_matrix_diagnostics.check_r_positive_semidefinite(Z)[source]#
Check that R = Re(Z) is positive semi-definite, as required for a lossless PEC: radiated power P_rad = 0.5 * I^H R I >= 0 for ANY current I. A raw eigenvalue in Ohms is not meaningful on its own – radiation resistance can legitimately be tiny for weakly-radiating modes/low electrical size (see eigen_solver.py’s regularization comment) – so this also reports the smallest eigenvalue relative to R’s own scale (||R||_F / N), the same normalization eigen_solver.py’s regularization floor uses, to judge whether a negative eigenvalue is ordinary floating-point noise or something larger worth investigating.
- Parameters:
Z (complex (N, N) ndarray)
- Returns:
dict with – eigenvalues : full eigenvalue spectrum of R_sym, ascending min_eigenvalue : smallest eigenvalue (Ohm) frobenius_norm : ||R_sym||_F relative_min_eig : min_eigenvalue / (frobenius_norm / N)
- harmolab.cma.z_matrix_diagnostics.diagnose_z_matrix(Z, frequency=None, label='', reciprocity_tol=0.001, relative_min_eig_tol=-1e-06)[source]#
Print a combined reciprocity + R-positive-semidefinite report for an impedance matrix, and return the underlying numbers.
- Parameters:
Z (complex (N, N) impedance matrix)
frequency (float or None, Hz -- only used in the printed header)
label (str, prefix for the printed header (e.g. antenna name))
reciprocity_tol (relative_asymmetry above this prints a WARNING) – (defaults to RECIPROCITY_TOL – see its derivation at the top of this module)
relative_min_eig_tol (relative_min_eig below this prints a WARNING) – (default -1e-6: comfortably above floating-point noise, comfortably below “clearly wrong”)
- Returns:
dict with keys ‘reciprocity’ and ‘positive_semidefinite’ – see
check_reciprocity() / check_r_positive_semidefinite()
Per-mode physical diagnostics for Characteristic Mode Analysis.
A CMA run always returns modes. Whether those modes correspond to currents the structure can actually support is a separate question, and lambda / MS alone cannot answer it: a mode living in the null space of R = Re(Z) radiates nothing, yet the regularized eigensolver hands it an ordinary-looking lambda, and MS = 1/sqrt(1+lambda^2) will happily report 0.99 for it.
Two independent quantities separate the two cases.
Radiated power per unit current amplitude. For a real current vector J,
P_rad = (J^T R J) / (J^T J) (R is the radiation operator, in Ohms)
is >= 0 for a lossless PEC and zero for a non-radiating current. The division matters: eigensolvers return J normalised so that J^T R J = 1 exactly, for every mode, so the raw numerator reports 1.0 even for a mode lying entirely in R’s null space (it just comes back with an enormous ||J||). Compared against the strongest mode in the same set, a physical mode lands within a few orders of magnitude; an artefact of adding eps*I to R lands far below.
Null-space leakage. Writing R = U diag(mu) U^T and collecting into null the columns whose mu <= 1e-6 * mu_max, the fraction
leak = ||null^T J|| / ||J||
is the part of the mode that lies in directions R cannot see. A physical mode is built out of radiating directions and leaks little; a spurious one is almost entirely null-space and leaks close to 1.
The two criteria are not redundant: leakage catches a mode that is mostly null-space but picked up enough radiating content to keep P_rad off the floor.
One caveat worth keeping in view. Modes produced by CMAParameters(solver=’rank_truncated’) are built inside the range of R, so their leakage is 0 BY CONSTRUCTION and cannot flag anything – exactly as max|Z-Z^T| reads 0 once the assembler mirrors its upper triangle. For those modes the leakage column confirms that the truncation ran; the discriminating quantity is P_rad, which is still measured independently.
- harmolab.cma.mode_diagnostics.mode_report(J, R, X=None, eigenvalues=None, p_rel_tol=1e-06, leak_tol=0.5, null_tol=1e-06)[source]#
Physical diagnostics for one or more characteristic modes.
- Parameters:
J ((N,) or (N, K) real eigenvector(s), one mode per column)
R ((N, N) Re(Z), the radiation operator, in Ohms)
X ((N, N) Im(Z), optional -- enables the eigenvalue residual)
eigenvalues ((K,) optional lambda per mode; required for the residual)
p_rel_tol (P_rad relative to the strongest mode below which -> SPURIOUS)
leak_tol (null-space leakage above which -> SPURIOUS)
null_tol (eigenvalues of R at or below null_tol * max are null space)
- Returns:
dict of (K,) arrays plus scalars – p_rad (J^T R J)/(J^T J) per mode, in Ohms – see module docstring p_rel p_rad / p_rad.max() – the STEP D criterion leak ||null^T J|| / ||J||, in [0, 1] residual ||X J - lambda R J|| / ||X J||, NaN if X/eigenvalues absent spurious bool, p_rel < p_rel_tol OR leak > leak_tol verdict ‘PHYSICAL’ or ‘SPURIOUS’ per mode reason why each mode was flagged (’’ when PHYSICAL) rank_R numerical rank of R at null_tol n_null size of the null space
- harmolab.cma.mode_diagnostics.format_mode_report(report, eigenvalues=None, title=None)[source]#
Render mode_report’s output as a Markdown table (also readable on a terminal).
Markdown data sheets for Characteristic Mode Analysis runs.
A CMA run leaves behind a .mat holding eigenvalues and eigenvectors. That is enough to re-plot, but not enough to READ months later: it carries no record of which mesh produced it, at what electrical size, with which solver settings, or whether the impedance matrix behind it was numerically sound.
These reports write all of that down, together with the per-mode quantities derived from the eigenvalues (modal significance, characteristic angle), in a form a human or a later analysis can work from.
They deliberately stop at recording data and defining the quantities. They do NOT decide where the antenna resonates, how good it is, or which mode to feed: those readings depend on context a script does not have, and the obvious automations are traps – a sign change in lambda, for instance, is a resonance when lambda passes through zero but a POLE when it runs off through infinity, and the two look identical to a naive scan while meaning opposite things about whether the mode can be excited.
- harmolab.cma.cma_report.write_single_frequency_report(path, modal_data, points, triangles, edges, Z=None, params=None)[source]#
Write the Markdown data sheet for a single-frequency CMA run.
- Parameters:
path (SimpleNamespace from setup_save_file_paths())
modal_data (ModalData from CharacteristicModeSolver.solve())
points (the mesh objects the run used)
triangles (the mesh objects the run used)
edges (the mesh objects the run used)
Z (the impedance matrix, if available -- adds the health section)
params (CMAParameters, if available -- records the solver settings)
- Returns:
str (the file written)
- harmolab.cma.cma_report.write_sweep_report(path, sweep_data, points, triangles, edges, Z_all=None, params=None)[source]#
Write the Markdown data sheet for a CMA frequency sweep.
- Parameters:
path (SimpleNamespace from setup_save_file_paths())
sweep_data (CMASweepData from cma_frequency_sweep())
points (the mesh objects the run used)
triangles (the mesh objects the run used)
edges (the mesh objects the run used)
Z_all ((n_freq, E, E) impedance matrices, if available -- the health) – section is then reported at the mid-band frequency
params (CMAParameters, if available -- records the solver settings)
- Returns:
str (the file written)
- class harmolab.cma.modal_visualizer.ModalVisualizer[source]#
Bases:
objectPlotly/matplotlib visualisation of characteristic mode currents, far fields and spectra.
- static plot_mode(points, triangles, surface_current, mode_index, eigenvalue, title_prefix='CMA', current_vector=None)[source]#
Plot the surface current of a single characteristic mode. Parameters ---------- points, triangles — mesh objects from DataManager_rwg2 surface_current — float64 (N_triangles,) from ModalCurrent.reconstruct mode_index — 0-based mode index (displayed as mode_index+1) eigenvalue — λ_n for this mode title_prefix — string prefix for the figure title current_vector — complex (3, N_triangles) from ModalCurrent.reconstruct, or None. When given, black arrows show the direction the modal current flows in (see rwg5.visualize_surface_current). Returns ------- plotly.graph_objects.Figure
- static plot_all_modes(points, triangles, edges, vecteurs_rho, modal_data, show_current_arrows=True)[source]#
Reconstruct and plot every mode stored in modal_data.
- Returns:
list[plotly.graph_objects.Figure] — one figure per mode
- static plot_mode_farfield(sphere_points, sphere_triangles, gain_db, mode_index, eigenvalue, title_prefix='CMA', dynamic_range=20, save_image=False, save_folder=None, antenna_name='', directivity_max_db=None, show_annotation=True)[source]#
Plot the 3D far-field directivity pattern radiated by a single characteristic mode, using the same deformed-sphere rendering as the physical-antenna gain patterns (harmolab.efield.efield2.render_and_save_pattern).
- Parameters:
sphere_points
sphere_triangles
modal_farfield.compute_modal_farfield() (gain_db — from)
mode_index
eigenvalue
plot_mode() (title_prefix — see)
(see (dynamic_range — dB range shown before clipping) – deform_sphere_for_radiation_pattern)
to (save_image — also write the figure) – cma_mode<n>_farfield_<antenna_name>.pdf
'data/fig_image/') (save_folder — destination (defaults to)
filename (antenna_name — used in the saved)
in-figure (directivity_max_db — peak directivity in dBi shown in the) – annotation; defaults to max(gain_db)
number (show_annotation — draw the mode) – inside the figure body (survives the PDF export, unlike the title)
directivity (λ and peak) – inside the figure body (survives the PDF export, unlike the title)
- Returns:
plotly.graph_objects.Figure
- static plot_eigenvalues_vs_frequency(sweep_data, n_modes_to_plot=None, freq_unit='MHz', save_pdf=False, save_folder=None, antenna_name='', yscale='symlog', linthresh=1.0)[source]#
Plot characteristic eigenvalues lambda_n(f) for the first n_modes_to_plot modes across a CMA frequency sweep (harmolab.cma.cma_frequency_sweep.cma_frequency_sweep).
A mode is resonant where its curve crosses lambda_n = 0 (dashed reference line). Mode identity across the sweep —————————— sweep_data straight out of cma_frequency_sweep() is in the solver’s per-frequency order, so a curve here can jump from one physical mode to another where two eigenvalues cross. Pass sweep_data.tracked() instead – same object type, modes followed across the sweep by the R-weighted correlation – and read sweep_data.tracking.events for the bands where that identity is not decidable (see harmolab.cma.mode_tracking). The same applies to every plotter below.
Why the default y axis is symlog#
lambda_n is unbounded: a barely-radiating mode reaches ~1e5 while the near-resonant ones sit around 1, so on a linear axis one curve sets the scale and flattens every other mode onto the zero line – the exact complaint AToM’s own documentation makes about this plot. symlog keeps both visible, staying linear within +/-linthresh so the crossings through zero (the resonances) are not distorted. Pass yscale=’linear’ for the raw view. For a bounded alternative see plot_characteristic_angle_vs_frequency().
- param sweep_data — CMASweepData:
- param n_modes_to_plot — int or None (defaults to all modes stored in sweep_data):
- param freq_unit — ‘Hz’:
- param ‘kHz’:
- param ‘MHz’:
- param or ‘GHz’:
- param save_pdf — bool:
- param save as PDF if True:
- param save_folder — str:
- param destination folder (defaults to ‘data/fig_image/’):
- param antenna_name — str:
- param used in the title and the saved filename:
- param yscale — ‘symlog’ (default) or ‘linear’:
- param linthresh — half-width of the linear region when yscale=’symlog’:
- returns:
matplotlib.figure.Figure
- static plot_modal_significance(sweep_data, n_modes_to_plot=None, freq_unit='MHz', save_pdf=False, save_folder=None, antenna_name='')[source]#
Plot Modal Significance MS_n(f) = 1/sqrt(1 + lambda_n(f)^2) for the first n_modes_to_plot modes across a CMA frequency sweep.
The MS >= 1/sqrt(2) reference line marks the conventional “significantly contributing” threshold (the CMA analogue of a -3 dB bandwidth).
Parameters mirror plot_eigenvalues_vs_frequency().
- Returns:
matplotlib.figure.Figure
- static plot_characteristic_angle_vs_frequency(sweep_data, n_modes_to_plot=None, freq_unit='MHz', save_pdf=False, save_folder=None, antenna_name='')[source]#
Plot the characteristic angle delta_n(f) = 180 deg - arctan(lambda_n(f)) for the first n_modes_to_plot modes across a CMA frequency sweep.
This is the representation to read first. delta_n is confined to (90 deg, 270 deg), so every mode stays visible at the same scale – unlike lambda_n, where one barely-radiating mode reaching ~1e5 flattens all the others onto zero (see plot_eigenvalues_vs_frequency).
delta = 90 deg : lambda -> +inf, inductive delta = 180 deg : RESONANCE (dashed reference line) delta = 270 deg : lambda -> -inf, capacitive
A mode resonates where its curve crosses 180 deg; the steeper the crossing, the higher (qualitatively) its Q, i.e. the narrower its band.
Parameters mirror plot_eigenvalues_vs_frequency().
- Returns:
matplotlib.figure.Figure