API — nefi.fields¶
Generated by scripts/gen_api_docs.py — do not edit by hand. Index
nefi.fields¶
Field parameterizations (the prior) and their building blocks.
nefi.fields.adaptive¶
Adaptive representation tools: let the data and the operator choose the geometry.
nefi.fields.adaptive.annealing¶
Adaptive annealing: open frequency bands when the data ask for them.
class BandwidthSchedule(schedule: Callable[[float], float] | Sequence[tuple[float, float]], module: nn.Module | None = None, per_stage: bool = True)¶
Prescribe the open bandwidth (cycles per unit normalized coordinate) over each stage.
bandwidth_for(field: nn.Module, progress: float) -> floaton_run_start(self, solver)on_stage_start(self, solver, stage_idx, stage)on_step(self, solver, state: StepState)progress_for(field: nn.Module, bandwidth: float) -> float
class OperatorAwareAnnealing(sensitivity: Spectrum | torch.Tensor | Sequence[float], noise_level: float | None = None, freqs: torch.Tensor | Sequence[float] | None = None, *, field: str...¶
Open frequency ν only when σ_F(ν) × |X̂(ν)| exceeds the noise.
on_stage_start(self, solver, stage_idx, stage)on_step(self, solver, state: StepState)sensitivity_at(self, f: torch.Tensor) -> torch.Tensortarget_bandwidth(self, x: torch.Tensor, progress: float) -> float— Resolvable bandwidth predicted from the current fieldx(stage grid).
class PlateauDetector(patience: int = 50, delta: float = 0.001, relative: bool = True, min_steps: int = 0, smoothing: float = 0.0, rate_fraction: float = 0.0)¶
Detect when a monitored loss stops paying off (windowed, scale-free).
reset(self)update(self, value: float) -> bool— Feed one value; returns True when a plateau is detected.
class ResidualDrivenAnnealing(patience: int = 25, delta: float = 0.001, n_levels: int | None = None, start_level: int = 0, ramp_steps: int = 50, relative: bool = True, min_steps_per_leve...¶
Open the next frequency band only when the data loss plateaus ("earn your frequencies").
on_run_start(self, solver)on_stage_start(self, solver, stage_idx, stage)on_step(self, solver, state: StepState)
def band_frequencies(obj: Any) -> list[float]¶
Frequency (cycles per unit normalized coordinate) opened by each successive band.
def bandwidth_to_progress(obj: Any, bandwidth: float) -> float¶
Smallest progress at which the band containing bandwidth is fully open.
def find_band_module(field: nn.Module) -> nn.Module | None¶
First module with an annealed band structure (annealed FourierFeatures or any module exposing band_frequencies() and effective_bandwidth(progress)).
def n_levels(obj: Any, default: int = 8) -> int¶
Number of annealing levels (bands) of a field / encoding (default if none).
def progress_to_bandwidth(obj: Any, progress: float) -> float¶
Highest open frequency at progress (effective_bandwidth, NeTMY Eq. 37).
def stage_noise_std(problem: Any, shape: Sequence[int] | None, scale: bool = True) -> float | None¶
The measurement noise std at a curriculum stage's resolution.
nefi.fields.adaptive.capacity¶
Capacity growth: start small, add degrees of freedom when the residual plateaus.
class Growable(*args, **kwargs)¶
Protocol for representations with a capacity pool.
can_grow(self) -> boolgrow(self, hint: Mapping | None = None) -> bool
class GrowCapacity(patience: int = 25, delta: float = 0.001, order: Sequence[str] = ('modules', 'progress'), use_progress: bool = True, n_levels: int | None = None, start_leve...¶
On data-loss plateaus, add capacity: grow modules and/or open annealing bands.
on_run_start(self, solver)on_stage_start(self, solver, stage_idx, stage)on_step(self, solver, state: StepState)
def field_space_gradient(solver: Any, state: StepState, data_only: bool = True) -> dict[str, Any]¶
Gradient of the (data) loss with respect to the field values at the current state.
def growable_modules(field: nn.Module) -> list[nn.Module]¶
Sub-modules implementing :class:Growable (depth-first order).
nefi.fields.adaptive.selection¶
Measurement-driven model selection: cross-validation for per-measurement inverse problems.
class CandidateScore(name: str, score: float, val_mse: float, train_mse: float, val_relative: float, val_nmse: float | None, n_parameters: int, seconds: float, steps: int, final...¶
Cross-validation outcome of one candidate representation.
to_dict(self) -> dict[str, Any]
class RepresentationEnsemble(fields: Mapping[str, Field], scores: Mapping[str, float] | None = None, weights: Mapping[str, float] | Sequence[float] | None = None, temperature: float | N...¶
Weighted average of fitted representations, weights from held-out fit.
extra_repr(self) -> strfrom_report(cls, report: SelectionReport, top_k: int | None = None, temperature: float | None = None) -> RepresentationEnsemble— Ensemble of the (top-k) fitted candidates of a :class:SelectionReport.on_stage_start(self, stage, domain)raw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)spread(self, coords: torch.Tensor, progress: float = 1.0) -> dict[str, torch.Tensor]— Weighted standard deviation across members per output field.weight_dict(self) -> dict[str, float]
class SelectionReport(ranking: list[CandidateScore], holdout: float, n_folds: int, n_train: int, n_val: int, noise_std: float | None, budget_scale: float, seed: int, score_name: ...¶
Ranked cross-validation report (best first); report.winner is the chosen name.
scores(self) -> dict[str, float]table(self) -> str— Markdown table of the ranking.to_dict(self) -> dict[str, Any]winner(property)winner_field(property)
def build_problem(problem_factory: Callable[..., Any], field: Field) -> Any¶
problem_factory(field), or replace(problem_factory(), field=field) for 0-arg factories (the replacement re-validates the operator's required fields).
def holdout_masks(measurement: Measurement, holdout: float = 0.1, seed: int = 0, group_axes: Sequence[int] | None = None, n_folds: int = 1) -> list[tuple[torch.Tensor, torch....¶
Random (train_mask, val_mask) pairs over the observed entries of a measurement.
def masked_downsampler(operator: Any, original: Callable[[Measurement, tuple[int, ...]], Measurement] | None = None, min_fraction: float = 0.0) -> Callable[[Measurement, tuple[int...¶
Down-sampler that averages only observed entries: data D(y·m) / D(m), weights D(m).
def select_representation(problem_factory: Callable[..., Any], candidates: Mapping[str, Callable[[], Field] | Field], curriculum: Curriculum | None = None, holdout: float = 0.1, seed...¶
Choose a representation by held-out prediction error on the measurement itself.
def softmax_weights(scores: Mapping[str, float] | Sequence[float], temperature: float | None = None) -> torch.Tensor¶
w_i ∝ exp(−(s_i − s_min) / T) (non-finite scores get weight 0).
nefi.fields.adaptive.spectrum¶
Radial spectra of representations and operators, and the match report that compares them.
class MatchReport(representation: Spectrum, operator: Spectrum, data: Spectrum | None, noise_std: float, noise_source: str, data_bandwidth: float, rep_bandwidth: float, nyqui...¶
Representation vs. operator at the noise level (see :func:match_report).
to_dict(self) -> dict[str, Any]to_markdown(self) -> str
class Spectrum(freqs: torch.Tensor, values: torch.Tensor, power: torch.Tensor, counts: torch.Tensor, kind: str = 'field', meta: dict[str, Any] = <factory>)¶
A radially averaged spectrum.
at(self, f: float | torch.Tensor) -> torch.Tensor— Linear interpolation ofvaluesat frequenciesf(clamped to the range).bandwidth(self, level: float = 0.1, ref: str = 'max', max_freq: float | None = None) -> float— First non-DC frequency wherevalues / referencedrops belowlevel.energy_bandwidth(self, fraction: float = 0.9, max_freq: float | None = None) -> float— Radius containingfractionof the (non-DC) energyΣ counts · power.normalized(self, ref: str = 'max') -> Spectrum— Copy withvaluesdivided by :meth:reference(powerby its square).nyquist(property)reference(self, ref: str = 'max') -> float— Normalization value: max over non-DC rings ("max"), the DC ring ("dc") or the first non-DC ring ("low").table(self, max_rows: int = 12) -> str— Compact text table (log-spaced subset of the rings).to_dict(self) -> dict[str, Any]
def estimate_noise_std(data: torch.Tensor) -> float¶
Robust white-noise estimate from first differences along the last axis (MAD / √2).
def field_spectrum(x: torch.Tensor, spacing: Sequence[float] | None = None, axes: Sequence[int] | None = None, center: bool = True, kind: str = 'field', window: str | None = '...¶
Radial amplitude spectrum of a field (orthonormal FFT, mean removed, Hann-windowed by default — images of layered media are far from periodic).
def jvp(fn: TensorFn, x: torch.Tensor, v: torch.Tensor, mode: str = 'auto') -> tuple[torch.Tensor, str]¶
J v by forward mode, falling back to double-backward, then central differences.
def kernel_row(field_module: torch.nn.Module, coords: torch.Tensor, index: tuple[int, ...], progress: float = 1.0, name: str | None = None) -> torch.Tensor¶
G_θ e_i = J_θ J_θᵀ e_i for the pixel index (NeTMY Lemma 2, Eq. 32–34).
def match_report(field: torch.nn.Module | None, problem: Any, *, progress: float = 1.0, noise_std: float | None = None, n_probes: int = 8, energy: float = 0.9, tol: float = ...¶
Compare a representation's pass band with what the data can resolve at the noise level.
def operator_spectrum(operator: Any, domain: Any, fields: Any, n_probes: int = 8, *, name: str | None = None, shape: Sequence[int] | None = None, seed: int = 0, mode: str = 'jtj'...¶
Radial amplitude sensitivity σ_F(ν) of the (linearized) forward operator.
def radial_average(x: torch.Tensor, spacing: Sequence[float] | None = None, axes: Sequence[int] | None = None, norm: str = 'ortho', center: bool = False, crop: bool = True, wi...¶
Radially averaged |FFT| and |FFT|² of a field-shaped tensor.
def representation_spectrum(field: torch.nn.Module, domain: Any, n_probes: int = 8, progress: float = 1.0, *, shape: Sequence[int] | None = None, name: str | None = None, seed: int = 0...¶
Radial transfer function of the representation's update kernel G_θ (NeTMY Lemma 2).
def resolvable_bandwidth(operator: Spectrum, noise_std: float, data_norm: float, prior_decay: float = 0.0, margin: float = 1.0) -> float¶
Resolvable band under a power-law field prior |X̂(ν)| = c (1 + ν/ν₁)^{−p}.
def smooth_octave(f: torch.Tensor, r: torch.Tensor, counts: torch.Tensor | None = None, width: float = 0.5) -> torch.Tensor¶
Counts-weighted average of r over [ν 2^{−width}, ν 2^{width}] around each ring.
nefi.fields.base¶
Field base class: a parameterization of the unknown(s) queried on a coordinate grid.
class Field(heads: Heads | Mapping | None)¶
Maps normalized coordinates (*shape, ndim) to {name: Tensor(*shape)}.
forward(self, coords: torch.Tensor, progress: float = 1.0) -> dict[str, torch.Tensor]n_parameters(self) -> intnames(property)on_stage_start(self, stage: Stage, domain: Domain)— Hook called by the solver when a curriculum stage starts (e.g. to resample a grid).primary(property)raw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)— Re-initialize all parameters (used for multi-restart).
nefi.fields.encoding¶
Coordinate encodings.
class Encoding(*args: Any, **kwargs: Any)¶
Base class: maps (..., in_dim) coordinates to (..., out_dim) features.
forward(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor
class FourierFeatures(in_dim: int, n_octaves: int = 12, base: float = 2.0, include_input: bool = True, annealed: bool = True, scale: float = 3.141592653589793)¶
Annealed Fourier features.
band_weights(self, progress=1.0, device=None, dtype=None) -> torch.Tensor— Gate weightsw_k(β)of shape(K,)(progress: float or 0-dim tensor).clear_cache(self)— Drop the memoized features / gates (they are rebuilt on demand).effective_bandwidth(self, progress: float = 1.0) -> float— Approximate highest active frequency (NeTMY Eq. 37), in cycles per unit coordinate.forward(self, coords: torch.Tensor, progress=1.0) -> torch.Tensor
class IdentityEncoding(in_dim: int)¶
forward(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor
nefi.fields.geometric¶
Geometric representations: fields whose structure encodes the geometry of the unknown.
nefi.fields.geometric.composite¶
Composite fields: one unknown assembled from several sub-fields (background ⊕ anomaly, ...).
class AnomalyField(background: Field, anomaly: Field, mode: str = 'add', heads: Heads | Mapping | None = None, support: torch.Tensor | Callable[[torch.Tensor], torch.Tensor] |...¶
background ⊕ anomaly with the anomaly gated by a support prior.
anomaly_map(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor— Effective anomalya(x)·s(x)(the gated, support-restricted indicator/amplitude).background_map(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor— The background's primary output at its mapped progress.combine(self, tensors, coords, progress)extra_repr(self) -> strinclusion_value(self) -> torch.Tensor— The inclusion valuevper channel (blend mode).support_at(self, coords: torch.Tensor) -> torch.Tensor | None— Support priors(x)of shapecoords.shape[:-1](None= everywhere).
class Combiner(fn: Callable[[Tensors], torch.Tensor], identity: float | tuple[float | None, ...] | None = None, n_components: int | None = None, description: str = '')¶
A rule c(t_1, …, t_n) combining component tensors (*shape, C_i) (broadcastable).
identity_for(self, i: int) -> float | None
class CompositeField(components: Mapping[str, Field] | Sequence[tuple[str, Field]], combiner: str | Combiner | Callable[[Tensors], torch.Tensor] = 'sum', heads: Heads | Mapping ...¶
Combine named sub-fields into one field; heads are applied to the combined raw tensor.
combine(self, tensors: list[torch.Tensor], coords: torch.Tensor, progress: float) -> torch.Tensor— Merge component tensors (override in subclasses for parameterized combinations).component(self, name: str) -> Fieldcomponent_channels(self, name: str) -> intcomponent_names(property)component_outputs(self, coords: torch.Tensor, progress: float = 1.0) -> dict[str, dict[str, torch.Tensor]]— Each component's own head outputs at its mapped progress (for plots / diagnostics).component_progress(self, name: str, progress: float) -> float— The progress a component sees at globalprogress.component_tensor(self, name: str, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor— Component output(*shape, C_i)at its mapped progress, weight ramp applied.components(property) — Orderedname -> Fieldmapping.extra_repr(self) -> strfreeze_prefixes(self, *names: str) -> tuple[str, ...]— Stagefreezeprefixes that freeze the given components (default: all).on_stage_start(self, stage, domain)raw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)
def register_combiner(name: str, fn: Callable[[Tensors], torch.Tensor], identity: float | tuple[float | None, ...] | None = None, n_components: int | None = None, description: st...¶
Register a named combiner usable as CompositeField(..., combiner=name).
def resolve_combiner(combiner: str | Combiner | Callable[[Tensors], torch.Tensor], identity: float | None = None) -> tuple[str, Combiner]¶
(name, Combiner) from a registered name, a :class:Combiner or a plain callable.
nefi.fields.geometric.layered¶
Stratified media: layered fields with learnable monotone interfaces (NeFTY layered setting).
class LateralModel(kind: str | Field, n_out: int, lat_ndim: int, lateral_shape: int | Sequence[int] = 8, hidden: int = 32, depth: int = 2, n_octaves: int = 4)¶
Perturbation δ(ℓ) of n_out quantities over the lateral coordinates (zero at init).
forward(self, lat: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)
class LayerCakeField(ndim: int, n_layers: int = 2, anomaly: Field | None = None, mode: str = 'add', name: str = 'x', depth_axis: int = -1, layer_values: Sequence[float] | None =...¶
Defects in a laminate: LayeredField background ⊕ gated anomaly (NeFTY layered setting).
layers(property) — The layered background component.
class LayeredField(ndim: int, n_layers: int = 2, heads: Heads | Mapping | None = None, depth_axis: int = -1, values: Sequence[float] | Sequence[Sequence[float]] | torch.Tensor...¶
Stratified field with n_layers layers and monotone learnable interfaces.
can_grow(self) -> boolcapacity(self) -> dict[str, int]eps(self, progress: float = 1.0) -> float— Interface softnessε(progress)in normalized depth units.extra_repr(self) -> strgrow(self, hint: Mapping | None = None) -> bool— Activate the next (deeper) layer without changing the current field.interfaces(self, lateral_coords: torch.Tensor | None = None, progress: float = 1.0) -> torch.Tensor— Interface depths(*lateral, K − 1)(normalized;None→ at the lateral center).layer_index(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor— Hard layer assignment(*shape)(long): number of active interfaces above.raw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)values(self, lateral_coords: torch.Tensor | None = None, progress: float = 1.0) -> torch.Tensor— Per-layer raw values(*lateral, K, C)(None→ base values(K, C)).
def default_anomaly_field(ndim: int, mode: str = 'blend', hidden: int = 32, depth: int = 3, n_octaves: int = 6, eps_start: float = 1.0, eps_end: float = 0.05, init_value: float | Non...¶
A small anomaly network suited to an :class:AnomalyField mode.
nefi.fields.geometric.shape¶
Explicit shape representations rendered with smooth, sharpening indicators.
class ContourRegularizer(perimeter: float = 1.0, smoothness: float = 0.0, order: float = 1.0, name: str | None = None)¶
Loss wrapper of :func:contour_regularizer on ctx.field_module (perimeter + boundary smoothness of every shape component).
forward(self, ctx: Context) -> torch.Tensor
class PolygonField(n_polygons: int = 1, n_vertices: int = 4, heads: Heads | Mapping | None = None, centers: Sequence[Sequence[float]] | torch.Tensor | None = None, radius: flo...¶
n_polygons simple polygons with learnable vertices, soft-rendered via a signed distance.
areas(self) -> torch.Tensor— Shoelace areas(S,)(absolute value; aspect-scaled).extra_repr(self) -> strgrow(self, hint: Mapping | None = None) -> boolperimeters(self) -> torch.Tensorreset_parameters(self)shape_indicators(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorsigned_distance(self, coords: torch.Tensor) -> torch.Tensor— Signed distance(*shape, S)to each polygon (negative inside; aspect-scaled).
class StarShapeField(ndim: int = 2, n_shapes: int = 1, n_harmonics: int = 4, heads: Heads | Mapping | None = None, centers: Sequence[Sequence[float]] | torch.Tensor | None = Non...¶
n_shapes star-shaped inclusions with Fourier-descriptor boundaries.
areas(self, n_quad: int = 256) -> torch.Tensor— Enclosed areas(S,):½ ∫ r(θ)² dθ(aspect-scaled normalized units).capacity(self) -> dict[str, int]descriptor_energy(self, order: float = 1.0) -> torch.Tensor—Σ_i Σ_m m^{2·order} (a_m² + b_m²)— a Sobolev penalty on boundary roughness.extra_repr(self) -> strgrow(self, hint: Mapping | None = None) -> bool— Activate the next pooled shape, at the hinted location if a gradient hint is given.perimeters(self, n_quad: int = 256) -> torch.Tensor— Boundary lengths(S,)(aspect-scaled normalized units):∫ sqrt(r² + r'²) dθ.r0(property) — Base radii(S,).radius(self, theta: torch.Tensor) -> torch.Tensor— Boundary radiusr_i(θ)for anglestheta (..., S)or(n,)(broadcast).radius_factor(self, cos1: torch.Tensor, sin1: torch.Tensor) -> torch.Tensor—max_s(1 + Σ_m a_m cos mθ + b_m sin mθ, floor)forcos θ, sin θ(..., S).reset_parameters(self)shape_indicators(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor
def contour_regularizer(field: Field, perimeter: float = 1.0, smoothness: float = 0.0, order: float = 1.0) -> torch.Tensor¶
perimeter · Σ|∂Ω_i| + smoothness · Σ m^{2·order}(a_m² + b_m²) over every shape field in field (searched recursively, so composites work).
def hint_location(hint: Mapping | None, contrast: float, extent: float = 0.9) -> torch.Tensor | None¶
Best location for a new inclusion from a growth hint (topological-derivative heuristic).
def interface_length(field: Any, spacing: Sequence[float] | None = None, lo: float = 0.0, hi: float = 1.0, n_quad: int = 256, periodic_axes: Sequence[int] = ()) -> torch.Tensor¶
Interface measure of a shape field or of a two-phase field tensor (differentiable).
nefi.fields.geometric.spectral¶
Spectral representations: explicit Fourier bases and Fourier-domain preconditioning.
class FourierBasisField(ndim: int, n_modes: int | Sequence[int] = 8, heads: Heads | Mapping | None = None, basis: str = 'cosine', annealed: bool = True, n_active: int | None = None...¶
Explicit low-frequency basis with learnable coefficients (the smooth-background prior).
band_frequencies(self) -> list[float]— Frequencies of shells1 … n_levels(for bandwidth ↔ progress mapping).basis_1d(self, u: torch.Tensor, n: int) -> torch.Tensor— Per-axis basis matrix(len(u), n).can_grow(self) -> boolcapacity(self) -> dict[str, int]cycles_per_shell(property) — Frequency increment per shell (cycles per unit normalized coordinate).effective_bandwidth(self, progress: float = 1.0) -> float— Highest open frequency (cycles per unit normalized coordinate).extra_repr(self) -> strgrow(self, hint: Mapping | None = None) -> bool— Open the next shell of modes (coefficients start at their current values, zero by default, so the field is unchanged at the moment of growth).mode_weights(self, progress: float = 1.0) -> torch.Tensorraw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)shell_weights(self, progress: float = 1.0) -> torch.Tensor— Gate per shell(n_levels + 1,): constant always on, shellsramps forβ ∈ [s − 1, s],β = progress · n_levels; shells≥ n_activeclosed.sobolev_norm(self, s: float = 1.0) -> torch.Tensor—Σ_k (1 + |k|²)^s |c_k|²over non-constant modes (a smoothness penalty).
class SpectralPreconditionedField(inner: Field, gain: GainFn | torch.Tensor | Sequence[float] | None = None, freqs: torch.Tensor | Sequence[float] | None = None, boundary: str = 'reflect', c...¶
x = F⁻¹(g(|k|) · F f_θ) — a field whose raw output passes through a radial Fourier gain.
extra_repr(self) -> strfrom_operator(cls, inner: Field, operator: Any, domain: Any, fields: Mapping[str, torch.Tensor] | None = None, floor: float = 0.01, power: float = 1.0, n_probes: int = 4,...— Measure the operator's radial sensitivity (JᵀJ probes) and build the preconditioner.from_sensitivity(cls, inner: Field, freqs: Sequence[float] | torch.Tensor, sensitivity: Sequence[float] | torch.Tensor, floor: float = 0.01, power: float = 1.0, **kw: Any) -...— Preconditionerg = (σ_max / max(σ, floor σ_max))^powerfrom a sensitivity profile (e.g.nefi.fields.adaptive.operator_spectrum(...):.freqs,.values).gain_at(self, kr: torch.Tensor) -> torch.Tensor— The (normalized, clipped, possibly learnable) gain at radial frequencieskr.ndim(property)on_stage_start(self, stage, domain)raw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)
def inverse_sensitivity_gain(freqs: Sequence[float] | torch.Tensor, sensitivity: Sequence[float] | torch.Tensor, floor: float = 0.01, power: float = 1.0) -> GainFn¶
g(k) = (σ_max / max(σ(k), floor · σ_max))^power — a floored inverse of the operator's amplitude sensitivity σ(k) (power = 1 ≈ Gauss–Newton for a free grid, since the image-space step scales with g²).
def lowpass_gain(cutoff: float, order: int = 4) -> GainFn¶
Butterworth-like radial low-pass g = 1 / sqrt(1 + (k/cutoff)^{2·order}).
def profile_gain(freqs: Sequence[float] | torch.Tensor, values: Sequence[float] | torch.Tensor)¶
Radial gain from a sampled profile (piecewise linear, constant beyond the ends).
nefi.fields.geometric.warp¶
Coordinate warps: reshape where a field spends its capacity.
class ComposeWarp(warps: Sequence[CoordinateWarp])¶
Apply warps in sequence (φ_n ∘ … ∘ φ_1).
forward(self, coords, progress=1.0)inverse(self, coords)on_stage_start(self, stage, domain)reset_parameters(self)
class CoordinateWarp(*args: Any, **kwargs: Any)¶
Base class: φ: (..., in_dim) → (..., out_dim) (optionally progress-dependent).
forward(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorinverse(self, coords: torch.Tensor) -> torch.Tensoron_stage_start(self, stage: Any, domain: Any)— Hook forwarded by :class:WarpedField.reset_parameters(self)— Re-initialize learnable warps (no-op for fixed ones).
class DeformableField(template: Field, warp_field: DisplacementWarp | None = None, max_displacement: float = 0.2, hidden: int = 32, depth: int = 2, n_octaves: int = 3, init_scale...¶
Template field + learned smooth displacement: x(u) = T(u + D(u)).
displacement(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensortemplate(property)
class DepthStretchWarp(gamma: float = 0.5, axis: int = -1, face: str = 'low', offset: float = 0.02, ndim: int | None = None)¶
Power-law depth stretch t' = ((t + δ)^γ − δ^γ) / ((1 + δ)^γ − δ^γ).
extra_repr(self) -> str
class DisplacementWarp(ndim: int, max_displacement: float = 0.2, axes: Sequence[int] | None = None, hidden: int = 32, depth: int = 2, n_octaves: int = 3, init_scale: float = 0.0, ...¶
Learned displacement φ(u) = u + D(u), D = m · tanh(net(u)), identity at init.
displacement(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor—D(u)of shape(*shape, len(axes)).extra_repr(self) -> strforward(self, coords, progress=1.0)reset_parameters(self)
class IdentityWarp(*args: Any, **kwargs: Any)¶
forward(self, coords, progress=1.0)inverse(self, coords)
class LogDepthWarp(scale: float = 0.1, axis: int = -1, face: str = 'low', ndim: int | None = None)¶
Logarithmic depth warp t' = log(1 + t/s) / log(1 + 1/s).
extra_repr(self) -> str
class PolarWarp(ndim: int = 2, center: Sequence[float] = (0.0, 0.0), axes: Sequence[int] = (0, 1), r_max: float | None = None, embed: str = 'angle')¶
Polar coordinates in a plane: (x, y, …) → (r̃, θ/π, …) or (r̃, cos θ, sin θ, …).
extra_repr(self) -> strforward(self, coords, progress=1.0)inverse(self, coords)
class SensitivityWarp(profiles: Mapping[int, torch.Tensor | Sequence[float]], ndim: int | None = None, strength: float = 1.0, power: float = 1.0, floor: float = 0.05)¶
Per-axis equidistribution warp u'_a = 2 C_a(u_a) − 1 from sensitivity profiles.
density(self, axis: int, u: torch.Tensor) -> torch.Tensor— Local stretchdu'/dualongaxisat coordinatesu(piecewise constant).extra_repr(self) -> strforward(self, coords, progress=1.0)from_map(cls, sensitivity: torch.Tensor, axes: Sequence[int] | None = None, strength: float = 1.0, power: float = 1.0, floor: float = 0.05) -> SensitivityWarp— Build from a field-shaped sensitivity map (marginal mean profile per warped axis).inverse(self, coords)
class WarpedField(inner: Field, warp: CoordinateWarp | str | Sequence[CoordinateWarp], inner_progress: Any = None, warp_progress: Any = None)¶
x(u) = f_θ(φ(u)): an inner coordinate field evaluated in warped coordinates.
ndim(property)on_stage_start(self, stage, domain)raw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)warped_coords(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor
class WarpRegularizer(smoothness: float = 1.0, magnitude: float = 0.0, folding: float = 0.0, margin: float = 0.1, module: DisplacementWarp | None = None, name: str | None = None)¶
Smoothness / magnitude / folding penalty on every :class:DisplacementWarp in the field.
forward(self, ctx: Context) -> torch.Tensor
def cylindrical(center: Sequence[float] = (0.0, 0.0), axis: int = 2, r_max: float | None = None, embed: str = 'angle') -> PolarWarp¶
3-D cylindrical warp around axis: (x, y, z) → (r̃, θ/π, z) (plane = other axes).
def depth_stretch(gamma: float = 0.5, axis: int = -1, face: str = 'low', offset: float = 0.02) -> DepthStretchWarp¶
Power-law depth stretch (γ < 1 concentrates capacity near the observed face).
def log_depth(scale: float = 0.1, axis: int = -1, face: str = 'low') -> LogDepthWarp¶
Logarithmic depth warp (capacity ∝ 1/(scale + depth)).
def polar(center: Sequence[float] = (0.0, 0.0), r_max: float | None = None, embed: str = 'angle') -> PolarWarp¶
2-D polar warp (x, y) → (r̃, θ/π) (or (r̃, cos θ, sin θ) with embed="circle").
def sensitivity_warp(sensitivity: torch.Tensor | Mapping[int, torch.Tensor], axes: Sequence[int] | None = None, strength: float = 1.0, power: float = 1.0, floor: float = 0.05) -...¶
Equidistribution warp from a sensitivity map (field-shaped tensor) or per-axis profiles.
def warp_regularizer(smoothness: float = 1.0, magnitude: float = 0.0, folding: float = 0.0, margin: float = 0.1) -> WarpRegularizer¶
Factory for :class:WarpRegularizer (smooth, small, fold-free displacements).
nefi.fields.grid¶
Free pixel/voxel parameterization (the "Tikhonov" / "Grid Opt." baseline of both papers).
class GridField(shape: Sequence[int], heads: Heads | Mapping | None = None, init: float | Sequence[float] | torch.Tensor | None = None, resample_mode: str = 'auto')¶
Raw values stored on a grid (*shape, n_in); heads applied pointwise.
extra_repr(self) -> stron_stage_start(self, stage, domain)raw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)set_fields(self, fields: Mapping[str, torch.Tensor])— Warm start from field values (through head inverses where available).
nefi.fields.hashgrid¶
Multiresolution hash-grid encoding (Instant-NGP-lite, Müller et al. 2022).
class HashGridEncoding(in_dim: int, n_levels: int = 12, n_features: int = 2, log2_table_size: int = 15, base_resolution: int = 4, max_resolution: int = 256, include_input: bool = ...¶
Multiresolution hash-grid encoding with progress-driven level annealing.
extra_repr(self) -> strforward(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorlevel_weights(self, progress: float = 1.0, device=None, dtype=None) -> torch.Tensor— Per-level gates(L,): coarse levels first, all active atprogress = 1.n_parameters(self) -> intreset_parameters(self)
class HashGridField(ndim: int, heads: Heads | Mapping | None = None, hidden: int = 64, depth: int = 2, activation: str = 'relu', n_levels: int = 12, n_features: int = 2, log2_t...¶
A small MLP on a :class:HashGridEncoding (the Instant-NGP recipe) with nefi heads.
reset_parameters(self)
nefi.fields.heads¶
Output heads: bounded / gated / masked transforms that encode physical priors on the unknowns.
class Bounded(lo: float, hi: float, init_value: float | None = None)¶
Hard-bracketed field lo + (hi - lo) σ(h) (NeFTY Eq. 6, NeTMY Larmor band).
init_bias(self)inverse(self, value)transform(self, raw, others)
class Exp(*args: Any, **kwargs: Any)¶
Strictly positive field exp(h) (log-parameterization; good for large dynamic range).
inverse(self, value)transform(self, raw, others)
class GatedSoftplus(beta: float = 1.0, init_value: float | None = None, gate_init: float = 0.0)¶
ρ = softplus(h) · σ(g) (NeTMY Eq. 5): non-negative with a pixelwise on/off gate.
gate(self, raw: torch.Tensor) -> torch.Tensorinit_bias(self)transform(self, raw, others)
class Head(*args: Any, **kwargs: Any)¶
Base class for output transforms. Subclasses set n_in and implement transform.
forward(self, raw: torch.Tensor, others: Mapping[str, torch.Tensor] | None = None, progress: float = 1.0)init_bias(self) -> list[float] | None— Suggested output-layer bias for this head's raw channels (None= zeros).inverse(self, value: torch.Tensor) -> torch.Tensor— Map a field value back to raw space where well-defined (used for warm starts).transform(self, raw: torch.Tensor, others: Mapping[str, torch.Tensor]) -> torch.Tensor
class Heads(heads: Mapping[str, Head | dict | str] | Sequence[tuple[str, Head]], primary: str | None = None)¶
Ordered collection of named heads consuming consecutive slices of a raw output tensor.
forward(self, raw: torch.Tensor, progress: float = 1.0) -> dict[str, torch.Tensor]init_bias(self) -> torch.Tensor— Concatenated suggested output biases (zeros where a head has no preference).inverse(self, fields: Mapping[str, torch.Tensor]) -> torch.Tensor— Raw tensor reproducingfieldswhere heads are invertible (else zeros).items(self)
class Identity(*args: Any, **kwargs: Any)¶
inverse(self, value)transform(self, raw, others)
class Softplus(beta: float = 1.0, init_value: float | None = None)¶
Non-negative field softplus(h) / beta.
init_bias(self)inverse(self, value)transform(self, raw, others)
class SupportMasked(inner: Head | dict | str, depends_on: str, tau: float = 0.3, fill: float = 0.0)¶
Multiply an inner head by a hard support mask of another field (NeTMY Eq. 26).
init_bias(self)inverse(self, value)support_mask(self, ref: torch.Tensor) -> torch.Tensortransform(self, raw, others)
nefi.fields.levelset¶
Two-phase (binary) fields through a sharpening level-set head.
class LevelSetField(ndim: int, lo: float = 0.0, hi: float = 1.0, name: str = 'x', eps_start: float = 1.0, eps_end: float = 0.05, schedule: str = 'geometric', **neural_kw)¶
A :class:~nefi.fields.NeuralField with a single :class:LevelSetHead.
phase_mask(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor— Boolean mask of thehiphase.phi(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensor— The level-set function (raw output)(*shape).
class LevelSetHead(lo: float = 0.0, hi: float = 1.0, eps_start: float = 1.0, eps_end: float = 0.05, schedule: str = 'geometric', init_value: float | None = None)¶
Two-phase head lo + (hi − lo) · σ(φ / ε(progress)) with a sharpening schedule.
eps(self, progress: float = 1.0) -> float— Interface softnessεat trainingprogressin[0, 1].init_bias(self)inverse(self, value)phase(self, raw: torch.Tensor) -> torch.Tensor— Boolean phase indicatorφ > 0(True where the field ishi).transform(self, raw, others, progress: float = 1.0)
def interface_length(field: torch.Tensor, spacing: Sequence[float] | None = None, lo: float = 0.0, hi: float = 1.0, periodic_axes: Sequence[int] = (), eps: float = 1e-08) -> tor...¶
Interface measure of a two-phase field (perimeter in 2-D, area in 3-D, #jumps in 1-D).
nefi.fields.lowrank¶
Low-rank (CP / canonical-polyadic) tensor field.
class LowRankField(shape: Sequence[int], heads: Heads | Mapping | None = None, rank: int = 8, bias: bool = True, init_std: float | None = None, resample_on_stage: bool = True)¶
Rank-R CP decomposition on a grid with per-axis factor vectors.
compression_ratio(self) -> float— Dense parameter count divided by the CP parameter count.dense(self, shape: Sequence[int] | None = None) -> torch.Tensor— Raw tensor(*shape, n_in)on the cell-centered grid ofshape.extra_repr(self) -> stron_stage_start(self, stage, domain)raw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)
nefi.fields.modifiers¶
Extra heads used by the prior catalogue (:mod:nefi.priors).
class Affine(scale: float = 1.0, offset: float = 0.0, init_value: float | None = None)¶
Unconstrained (signed) field offset + scale · h.
init_bias(self)inverse(self, value)transform(self, raw, others)
class ExpHead(init_value: float | None = None)¶
Strictly positive field exp(h) (log-parameterization) with an optional init_value.
init_bias(self)
class MaskedHead(inner: Head | dict | str, mask: torch.Tensor, fill: float = 0.0, binary: bool = True)¶
x = inner(h) · m + fill · (1 − m) with a fixed support mask m (known support).
mask_at(self, shape, device=None, dtype=None) -> torch.Tensor— The support mask resampled toshape(cached).transform(self, raw, others, progress=1.0)
class MassNormalized(inner: Head | dict | str, total: float = 1.0, volume: float = 1.0, kind: str = 'sum', eps: float = 1e-12)¶
Rescale a non-negative inner head so that its total is exactly total (conservation).
transform(self, raw, others, progress=1.0)
class ScaledHead(inner: Head | dict | str, scale: float = 1.0)¶
x = scale · inner(h): puts the network output in natural units.
inverse(self, value)transform(self, raw, others, progress=1.0)
class ZeroMean(inner: Head | dict | str, n_dims: int | None = None)¶
x = inner(h) − mean(inner(h)): a field whose spatial mean is exactly zero (a gauge).
transform(self, raw, others, progress=1.0)
def find_head(head: Head, cls: type) -> Head | None¶
First head of type cls along the .inner chain of a (wrapped) head.
def head_init_value(head: Head) -> float | None¶
The init_value of a (possibly wrapped) head, None if unsupported/unset.
def innermost(head: Head) -> Head¶
Follow .inner links of wrapped heads down to the defining head.
def set_head_init_value(head: Head, value: float | None) -> bool¶
Set init_value on the innermost head that supports it; returns success.
def value_range(head: Head) -> tuple[float, float]¶
Interval of values a (possibly wrapped) head can produce (best effort).
nefi.fields.neural¶
Coordinate neural field: annealed Fourier features -> MLP with skip -> heads.
class NeuralField(ndim: int, heads: Heads | Mapping | None = None, hidden: int = 256, depth: int = 6, skip_at: int | None = 3, activation: str = 'tanh', encoding: Encoding | ...¶
Coordinate MLP with annealed Fourier features and a mid-network skip connection.
extra_repr(self) -> strraw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)
class Sine(w0: float = 30.0)¶
forward(self, x)
nefi.fields.parametric¶
Low-dimensional parametric fields (analytic ansätze with a handful of learnable numbers).
class Ellipses(n: int = 1, ndim: int = 2, sharpness: float = 0.05, amplitudes: float | Sequence[float] = 1.0, centers: Sequence | None = None, radii: float | Sequence = 0....¶
Sum of smooth ellipse indicators Σ_k A_k σ((1 − q_k(r)) / sharpness).
init(self) -> torch.Tensorunpack(self, params)
class GaussianBlobs(n: int = 1, ndim: int = 2, centered: bool = False, amplitudes: float | Sequence[float] = 1.0, centers: Sequence | None = None, sigmas: float | Sequence[floa...¶
Sum of isotropic Gaussians Σ_k A_k exp(−‖r − c_k‖² / 2σ_k²) in normalized coordinates.
init(self) -> torch.Tensorunpack(self, params)
class ParametricField(fn: ParamFn | Callable[[torch.Tensor, torch.Tensor], torch.Tensor], init: torch.Tensor | Sequence[float] | None = None, heads: Heads | Mapping | None = None...¶
A field given by a closed-form family with a learnable parameter vector.
extra_repr(self) -> strraw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)unpack(self) -> dict[str, torch.Tensor]— Readable parameters (viafn.unpackwhen available).
class ParamFn()¶
A parametric family fn(params, coords) -> Tensor.
init(self) -> torch.Tensorunpack(self, params: torch.Tensor) -> dict[str, torch.Tensor]
def ellipses(n: int = 1, ndim: int = 2, **kw) -> Ellipses¶
n smooth ellipses (rotated in 2-D, axis-aligned ellipsoids in 3-D).
def gaussian_blobs(n: int = 1, ndim: int = 2, **kw) -> GaussianBlobs¶
n isotropic Gaussian blobs (NeTMY §5.5 ansatz when n=1, centered=True).
nefi.fields.symmetric¶
Exact symmetries by coordinate folding: mirror planes and radial symmetry.
class SymmetricField(inner: Field, kind: str = 'mirror_x', ndim: int | None = None, axes: Sequence[int] | None = None, center: float | Sequence[float] = 0.0, mode: str = 'auto')¶
Wrap a field so that its output has an exact mirror or radial symmetry.
extra_repr(self) -> strfold(self, coords: torch.Tensor) -> torch.Tensor— Folded coordinates fed to the inner field.on_stage_start(self, stage, domain)raw(self, coords: torch.Tensor, progress: float = 1.0) -> torch.Tensorreset_parameters(self)
def symmetry_axes(kind: str, ndim: int, axes: Sequence[int] | None = None) -> tuple[int, ...]¶
Axes involved in a symmetry kind for an ndim-D domain (validated).