Repository navigation
Bug fixes, correctness guards, performance and test coverage from an in-depth review - #644
Conversation
The tapered-cone normal used the raw local (x, y) (magnitude r) against the unit-scaled slope dr/dz, tilting normals of SI-scale geometry almost into +-z. The ellipsoid normal used sign(x_i)*(x_i/r_i)^2 instead of the gradient x_i/r_i^2. Both now return normalized gradient-direction normals. Add flip for outwards EllipsoidMantle and regression tests against analytic normals. Created by generative AI.
- SolidStateDetector: doped-contact auto-detection referenced an undefined variable and never injected the detected contact ids, so omitting doped_contact_id always crashed; it now defaults to the contact(s) at maximum potential as documented. - InactiveLayerChargeDriftModel: the semiconductor temperature (already in internal units) was re-parsed with the config input units, shifting it for non-Kelvin units and making the mismatch check throw spuriously. - Semiconductor: unknown charge_trapping_model names silently disabled trapping; now a ConfigFileError. Missing model key no longer raises a raw KeyError. - Simulation: invalid grid coordinates hit bare @Assert with a string argument (TypeError at runtime); now a ConfigFileError with the intended message. - estimate_depletion_voltage: crashed with only() when both voltage candidates lay inside the search range. - calculate_capacitance_matrix: could never store its documented missing entries (MethodError); eltype narrows when all entries exist. Add config-robustness tests covering these paths. Created by generative AI.
The forward difference from the last phi column to phi = 0 divided by (axphi[1] - axphi[end]), a large negative non-distance, instead of the wrap gap (cyclic + axphi[1] - axphi[end]) that the mirror branch at iphi == 1 already uses. This corrupted e_phi on the last phi slice of every cylindrical field calculation; invisible for phi-symmetric detectors (e_phi = 0), wrong for segmented ones. Also: default use_nthreads to nthreads() instead of threadid(), keep the NaN/Inf guard type-stable for Float32, and store SVectors directly instead of allocating a temporary Vector per grid point. Add an analytic uniform-field regression test covering the wrap column. Created by generative AI.
- ADL2016 getVe: honor the Emag_threshold argument; zero field returned NaN instead of zero velocity (2006 model already guarded). - ADL getVh: clamp the acos argument; rounding could push it outside [-1, 1] for fields along the rotated crystal z-axis. - PtypePNJunctionImpurityDensity: offset corrections were added to both sub-models, shifting the summed density by twice the offset. - simulate_waveforms: accept unitless edep columns (as documented) and plain-Real time steps (dt.val crashed on Real). - readsiggen: missing taper_length keys no longer raise KeyError. - parse_config_file: mention siggen .config in the unsupported-format error. Created by generative AI.
- Box: config check tested hZ twice and never hY; missing entries now
raise ConfigFileError instead of KeyError or falling through.
- RegularPrism: the height assert accepted 'z' but only 'h' was parsed.
- Cone/Torus Dictionary: serializing a full-phi primitive carrying a
pure-Z rotation crashed on phi0 + nothing; keep the rotation entry.
- Polycone _in: remove dead partial-phi branch referencing an undefined
variable (Polycone is full-phi by construction).
- TorusMantle: phi-partial mantles now raise a clear ArgumentError from
distance_to_surface instead of MethodError; drop the dead guard.
- ConeMantle intersection: single-intersection branch lost the sign of
D1 (used sqrt(D3^2 S^2 - D2^2) = |D1|); use the -D1*L1 quadratic
limit.
- frame_transformation(a, b): the two half-transforms were composed in
the wrong order, wrong for any distinct frames.
- CartesianPoint{T}(v::AbstractVector) ignored the requested precision.
- _in_phi: avoid Float64 promotion in the Float32 hot path.
Created by generative AI.
- searchsortednearest on periodic axes now also snaps across the seam (a phi just below the period snapped to the last tick instead of the first); find_closest_gridpoint passes the axis so the periodic method is actually used. - check_grid: periodic Cartesian y/z axes require an even tick count for red-black parity, mirroring the cylindrical phi guard. - multiplicity: add the missing method for periodic Cartesian axes (capacitance calculations raised MethodError on periodic grids). - even_tick_axis no longer mutates and aliases the input axis ticks. - r=0 volume weight: replace a Float32 literal of 1/(2pi) with inv(T(2pi)) for full precision in Float64 setups. Created by generative AI.
- Correct parameter order in the RegularPrism docstring and typos in TorusMantle/EllipticalSurface annotations. - intersection docstrings for cone/ellipsoid/torus mantles claimed NaN returns for non-intersecting lines; describe the actual behavior. - Fix broken code examples of get_electron_and_hole_contribution and plot_electron_and_hole_contribution (package name, variable names) and of PtypePNJunctionImpurityDensity in the manual (missing doped-contact-id argument). - min_tick_distance docstrings described defaults the code no longer uses. - Lithium-diffusion parameter docstrings: render the formulas correctly (raw strings; the plain strings mangled the LaTeX via string escapes). - Reword misleading temperature-scaling comments (anisotropy is preserved, not dropped). - CartesianVector docstring example used CartesianPoint. Created by generative AI.
- CGD stored-energy check used an atol larger than the expected value (any result in [0, 1.4e-5] passed, including zero); use rtol. - Two-step weighting-potential refinement compared only array sizes; also compare grids and values. - test_gpu_backend.jl relied on T leaking from a previously included test file; define it locally. - Load test config files via @__DIR__ instead of cwd-relative paths. - Replace duplicated copy-paste assertions in the partial-tube tests with distinct points on the φ-boundaries of the wedge. Created by generative AI.
The periodic wrap for the compressed dimension (Cartesian x, and the cylindrical z-axis routed through the same method) copied ghost rows into ghost rows: row 1 read row end (a ghost) and row end read the just-overwritten row 1. The update loop therefore never received wrapped interior values. In compressed indexing real index 1 sits at row 2 and real index N at row size-1, so the wrap is ghost[1] <- interior[end-1] and ghost[end] <- interior[2], matching all other methods of this file. Add a red-black layout unit test pinning this. Also drop unused red-black helpers (AbstractRBArray, RBEven/RBOdd, rb_bool_*, the non-extended RBArray constructors). Created by generative AI.
- ChargeDrift: drop the unused DriftPath struct and the bogus 500 m default diffusion length of the internal diffusion kick (the only caller always passes it). - Depletion: delete `old_estimate_depletion_voltage` - calculate_weighting_potential!: remove the silently-ignored n_points_in_phi keyword; passing it now fails loudly. Created by generative AI.
The example originally named its phi axis 'y' (ignored, so the full-2pi default applied); a later rename to 'phi' kept 'from: 0, to: 0', which means 2D phi-symmetric - wrong for a cuboid detector. Restore a full phi range. New tests: CGD on cylindrical vs Cartesian grid (active-volume agreement, would have caught this), get_2pi_potential periodic and reflecting extensions against analytic phi-dependence, NBodyChargeCloud energy conservation, and numeric velocities of the simple drift models. Created by generative AI.
|
For completeness, let me list the commit in #623 that did NOT make it into this PR and why:
|
e281a66 to
2e9ea0d
Compare
|
Out of the manual cross-checks listed in #623, the ones relevant for this PR might be: Major things:
Manual cross-checks:
|
fhagemann
left a comment
There was a problem hiding this comment.
These would be my open questions for this PR
0ae9e2c to
b352ef8
Compare
|
For some reason, this PR did not correctly squash
into
so, I'm just cherry-picking those two commits and adding them to the end of this PR. Tests should hopefully pass now. |
…odel getVe recomputed sqrt of the four constant reciprocal mass tensors via generic (allocating) matrix square roots on every call and summed the scattering weights inside the valley loop. Store sqrtgamma in the model (a 6-argument convenience constructor keeps all construction sites and the temperature-scaling path unchanged) and hoist the sum. getVe: 20.8 us -> 0.55 us per call (38x) with identical results. Created by generative AI.
Whether a cylindrical simulation runs in 2D (or on a reduced phi wedge) was decided purely by the grid's phi interval; nothing verified that the detector actually has the corresponding symmetry, so a config mistake silently produced wrong fields (as happened to the CGD_CylGrid example for years). Grid construction now runs a sampled phi-invariance check of all field-relevant objects and raises a ConfigFileError with a clear message for 2D grids of non-symmetric detectors and for periodic wedges without the matching n-fold periodicity. One mismatching sample is tolerated for robustness against points on object surfaces; reflecting wedges (mirror symmetry) are not yet checked. Created by generative AI.
The cylindrical interpolation helpers closed the φ axis at ticks[1] + 2π regardless of the axis range. For a symmetry-reduced periodic wedge the repeat period is the interval width, so the wrap knot must sit at the wedge end - otherwise evaluations between the last tick and the wedge end (reachable e.g. through the capacitance integration over the closed wedge grid) interpolate across one giant cell spanning the rest of the circle. Non-periodic axes keep the full-circle closure, since a mirror-symmetric extension is not a plain periodic repetition. Vector fields on reduced grids remain meaningful only within their φ range (Cartesian components do not transform trivially); noted in a comment. Created by generative AI.
11418da to
9fff61e
Compare
|
As per my last commit, all One thing we might want to do (but defer to a follow-up PR) is solidifying the constructors of CSG primitives to restrict the parameters to reasonable values, e.g. that radii of tubes, spheres, etc. should ALWAYS be ≥ 0, etc. |
|
New ToDos:
Old ToDos:
|
387b664 to
088e481
Compare
|
In the interest of getting this merged soon, would it make sense to split this into two: with the open questions about the φ-wrapping for |
|
Both options are fine with me, either this PR or a new one. I think the latest change should take care of the @testset "Interpolation on reflecting φ wedges mirrors at the interval boundaries" begin
axr = DiscreteAxis(0.0, 0.02, :r0, :infinite, :closed, :closed, collect(range(0.0, 0.02, length = 3)))
axz = DiscreteAxis(0.0, 0.03, :infinite, :infinite, :closed, :closed, collect(range(0.0, 0.03, length = 3)))
wedge(φticks) = CylindricalGrid{Float64}((axr, DiscreteAxis(0.0, π/6, :reflecting, :reflecting, :closed, :closed, φticks), axz))
f(r, φ, z) = 1 + r + φ + z # linear in φ: interpolation is exact and the mirror images are known
# 0°-30° wedge: extended midpoints grid as for `sim.ϵ_r` of :Coax (ticks beyond 0° and 30°),
# and a grid whose ticks (2°-28°) do not reach the boundaries
for g in (SolidStateDetectors.get_extended_midpoints_grid(wedge(collect(range(0.0, π/6, length = 7)))),
wedge(collect(range(deg2rad(2), deg2rad(28), length = 6))))
ϵ = DielectricDistribution([f(r, φ, z) for r in g.axes[1].ticks, φ in g.axes[2].ticks, z in g.axes[3].ticks], g)
itp = SolidStateDetectors.interpolated_scalarfield(ϵ)
for φ in range(deg2rad(2), deg2rad(28), length = 7)
@test itp(0.01, φ, 0.015) ≈ f(0.01, φ, 0.015) # inside: unchanged
@test itp(0.01, π/3 - φ, 0.015) ≈ f(0.01, φ, 0.015) # mirrored at 30°
@test itp(0.01, -φ, 0.015) ≈ f(0.01, φ, 0.015) # mirrored at 0°
end
end
end |
49e6025 to
0529568
Compare
0529568 to
31a897e
Compare
In an effort to get the changes of the monster PR #623 merged into SSD eventually, I decided to split up #623 into multiple PRs with approved changes, and with changes that we might need to discuss separately.
This should be the PR with all (most) approved changes.
Let me comment on the individual comments in this PR and what went into them:
src/Simulation/Capacitance.jl462c2c1 Use the φ interval width as the angular period (squashed)72121f2 Wrap periodic wedge interpolation with the wedge period (squashed)Δtto be discussed in a separate PR--> except for the
Δtscalingsrc/Axes/DiscreteAxis.jlsrc/Event/Event.jlandsrc/PlotRecipes/Waveform.jl8bb6c28 Speed up the GPU SOR iteration loop(moved to Fuse the GPU boundary-condition updates into one kernel per color #647)
4eb8e12 Speed up the GPU SOR iteration loop (original)ae4fe80 Rename_ka_ordered_syncto_ka_synchronize(squashed)775d23f ReplaceCUDAKernelswithCUDAintest_utils.jl(squashed)crystal_orientationin the ADL charge drift models is a rotation matrix (squashed)sqrtinstead of^1/2in variable namesrc/Simulation/Simulation.jl16b70a7 Cover the GPU dispatch path and untested SOR/drift components(moved to Fuse the GPU boundary-condition updates into one kernel per color #647)
d296530 Cover the GPU dispatch path and untested SOR/drift components (original)0d97e7c Loosen equality in kernel/CPU matching test to approx (squashed)spacing_surface_refinement(squashed)docs/src/man/csg.mdInactiveLayerChargeDriftModel(squashed)--> just the benchmark part
--> just the metal permittivity part
find . -type f -exec dos2unix {} +, which caught even more files.gitattributesthat should prevent inconsistent line endings in the future