From 8459f18ece67aef8a33c6300a63c5748744e6783 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 18:29:07 +0000 Subject: [PATCH 1/4] feat: exspy's window path for an SEM spectrum: lines in range, windows, intensities and Cliff-Lorimer EDSWindowPath (public) puts the kit's own functions behind the calls Electron Microscopy Studio's SEMEDSLines makes: the lines add_lines() picks for a list of elements at a beam energy, the lines in the spectral range, integration and background windows, line intensities on Double counts through WindowIntensity.resolve, the acquisition conditions with exspy's defaults and their take-off angle, and Cliff-Lorimer with the single-line rule named by the caller (.refuse, the kit's default, or .exspyHundredPercent, exspy's raw arithmetic). No default of the kit changes and no number moves. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VkKZEUynSt6RczY9oKhrDU --- Sources/SpectroEDX/EDSWindowPath.swift | 178 ++++++++++++++++++ .../SpectroEDX/SpectroEDX.docc/SpectroEDX.md | 5 + Sources/SpectroEDX/WindowIntensity.swift | 7 + 3 files changed, 190 insertions(+) create mode 100644 Sources/SpectroEDX/EDSWindowPath.swift diff --git a/Sources/SpectroEDX/EDSWindowPath.swift b/Sources/SpectroEDX/EDSWindowPath.swift new file mode 100644 index 0000000..5aae3d3 --- /dev/null +++ b/Sources/SpectroEDX/EDSWindowPath.swift @@ -0,0 +1,178 @@ +// +// EDSWindowPath.swift +// Role: eXSpy's window path for one spectrum, public: the lines `add_lines()` picks for a list of elements at a beam energy, their +// integration and background windows, the line intensities with and without background, the acquisition conditions with +// eXSpy's defaults, and Cliff-Lorimer on the intensities with the single-line rule named by the caller. A front over the +// kit's own functions (`XRayLines.defaultLines`, `WindowIntensity`, `BackgroundWindows`, `CliffLorimer`, `TakeOff`): no +// second implementation. Merged from Electron Microscopy Studio's `SEMEDSLines` (at e7212f9, SpectroKit#131). +// +// Ported from eXSpy 0.3.2 (the bundles) and 7185a4d1 (the kit's pins), the same functions in both: `signals/eds.py` +// (`_get_lines_from_elements`, `_get_xray_lines_in_spectral_range`, `estimate_integration_windows`, +// `estimate_background_windows`, `get_lines_intensity`, `get_take_off_angle`), `_misc/eds/utils.py` (`get_FWHM_at_Energy`, +// `take_off_angle`, `quantification_cliff_lorimer`), `_misc/material.py` (`_weight_to_atomic`), and HyperSpy's +// `UniformDataAxis.value2index` for the channel rule (`EnergyAxis`). Line width: Fiori and Newbury 1978; k-factor ratio: Cliff and +// Lorimer 1975. +// +// Numbers: float64, eXSpy's order of operations. A spectrum is a few thousand channels: plain loops on the CPU (D16). Parity: the +// bundles m7/eds-lines-tm002 and m7/eds-quant-tm002 (BAM TM002), the line table and the channel rule exact, the rest rtol 1e-7 +// (SEMEDSParityTests). +// +// DEVIATIONS from eXSpy (each the kit's, unchanged here): H and He get no line (`XRayLines.notRealLines`); a line whose width the +// Fiori-Newbury law cannot give throws `SpectralLineError.widthUndefined` where eXSpy's `math.sqrt` raises; a NaN window edge throws +// `EnergyAxisError.notANumber`. +// + +import Foundation +import SpectroCore + +/// Why the window path refuses a spectrum or its windows. +public nonisolated enum EDSWindowPathError: Error, Equatable, Sendable { + /// The spectrum holds `counts` channels and its axis `axis`. + case channelCount(counts: Int, axis: Int) + /// One background window pair per integration window: `background` pairs for `integration` lines. + case windowCount(background: Int, integration: Int) + /// An integration window has two edges, a background window pair four; this one has `edges`. + case windowEdges(expected: Int, edges: Int) +} + +/// eXSpy's window path on one spectrum: lines, windows, intensities, conditions and Cliff-Lorimer. +/// +/// Energies are keV, the axis is the spectrum's `EnergyAxis`. The functions are the kit's own (the line table of `XRayLines`, the +/// windows and channel rule of `WindowIntensity`), so a window or an intensity here is the one `ElementWindows` builds from the same +/// line and rules. +public nonisolated enum EDSWindowPath { + /// What the acquisition says about the detector and the stage, as eXSpy reads `Acquisition_instrument.SEM`; a value the file does + /// not state takes eXSpy's preference default (`_set_default_param`, `EDSConfig`). Unlike `EDXQuantification.takeOffAngle`, + /// which takes every angle from its caller, these are eXSpy's defaults, stated here by name. + public struct Conditions: Equatable, Sendable { + public var beamEnergyKeV: Double? + /// `Detector.EDS.energy_resolution_MnKa`, eV (default 130). + public var energyResolutionMnKaEV: Double + /// `Detector.EDS.elevation_angle`, degrees (default 35). + public var elevationAngleDeg: Double + /// `Detector.EDS.azimuth_angle`, degrees (default 0). + public var azimuthAngleDeg: Double + /// `Stage.tilt_alpha`, degrees (default 0). + public var tiltAlphaDeg: Double + /// `Stage.tilt_beta`, degrees (default 0, as `get_take_off_angle` reads it). + public var tiltBetaDeg: Double + public var liveTimeS: Double? + public var realTimeS: Double? + + /// eXSpy's defaults (`EDSConfig`): 130 eV at Mn K alpha, 35 degrees elevation, 0 degrees azimuth and stage tilt. + public static let defaultResolutionMnKaEV = 130.0 + public static let defaultElevationDeg = 35.0 + public static let defaultAzimuthDeg = 0.0 + public static let defaultTiltDeg = 0.0 + + /// A nil value takes eXSpy's default. + public init(beamEnergyKeV: Double?, energyResolutionMnKaEV: Double? = nil, elevationAngleDeg: Double? = nil, + azimuthAngleDeg: Double? = nil, tiltAlphaDeg: Double? = nil, tiltBetaDeg: Double? = nil, + liveTimeS: Double? = nil, realTimeS: Double? = nil) { + self.beamEnergyKeV = beamEnergyKeV + self.energyResolutionMnKaEV = energyResolutionMnKaEV ?? Self.defaultResolutionMnKaEV + self.elevationAngleDeg = elevationAngleDeg ?? Self.defaultElevationDeg + self.azimuthAngleDeg = azimuthAngleDeg ?? Self.defaultAzimuthDeg + self.tiltAlphaDeg = tiltAlphaDeg ?? Self.defaultTiltDeg + self.tiltBetaDeg = tiltBetaDeg ?? Self.defaultTiltDeg + self.liveTimeS = liveTimeS + self.realTimeS = realTimeS + } + + /// `get_take_off_angle()`: the take-off angle from the stage tilts and the detector's azimuth and elevation, degrees + /// (`EDXQuantification.takeOffAngle`). + public var takeOffAngleDeg: Double { + TakeOff.angle(tiltAlpha: tiltAlphaDeg, azimuth: azimuthAngleDeg, elevation: elevationAngleDeg, tiltBeta: tiltBetaDeg) + } + } + + // MARK: - Lines + + /// `_get_lines_from_elements(elements, only_one, only_lines)`, which `add_lines()` runs for `Sample.elements`: per element its + /// lines of `onlyLines` (default `["a"]`: Ka, La, Ma) inside the spectral range; with `onlyOne` the first of them, in Python's + /// string order, below half the beam energy, else the last; all lines sorted at the end. Without a beam energy the axis' last + /// channel stands in, as eXSpy's fallback. An element without lines, or a symbol the table does not know, adds none. + public static func lines(forElements elements: [String], axis: EnergyAxis, beamEnergyKeV: Double?, onlyOne: Bool = true, + onlyLines: [String]? = ["a"]) -> [String] { + XRayLines.defaultLines(elements: elements, axis: axis, beamEnergy: beamEnergyKeV, onlyOne: onlyOne, onlyLines: onlyLines) + } + + /// `_get_xray_lines_in_spectral_range`: the lines strictly between the axis' first channel and the smaller of its last channel and + /// the beam energy; the rest (eXSpy warns about them), each list in the order given. A line the table lacks is out of range. + public static func linesInSpectralRange(_ lines: [String], axis: EnergyAxis, + beamEnergyKeV: Double?) -> (inRange: [String], outOfRange: [String]) { + var inside: [String] = [] + var outside: [String] = [] + for line in lines { + if XRayLines.linesInRange([line], axis: axis, beamEnergy: beamEnergyKeV).isEmpty { outside.append(line) } else { inside.append(line) } + } + return (inside, outside) + } + + // MARK: - Windows + + /// `estimate_integration_windows(windows_width)`: per line `[E - width FWHM / 2, E + width FWHM / 2]`, keV, the FWHM from the + /// detector's resolution at Mn K alpha (`XRayLines.fwhm`). + public static func integrationWindows(_ lines: [String], width: Double = 2.0, resolutionMnKaEV: Double) throws -> [[Double]] { + WindowIntensity.integrationWindows(lines: try spectralLines(lines, resolutionMnKaEV: resolutionMnKaEV), windowsWidth: width) + } + + /// `estimate_background_windows(line_width, windows_width)`: per line a window `lineWidth.left` FWHM left of the line and one + /// `lineWidth.right` FWHM right of it, each `windowsWidth` FWHM wide, `[l0, l1, r0, r1]` keV; then eXSpy's merge of overlapping + /// windows (`BackgroundWindows.merge`). eXSpy's defaults are (2, 2) and 1; its EDS tutorial uses (5, 2). + public static func backgroundWindows(_ lines: [String], lineWidth: (left: Double, right: Double) = (2, 2), windowsWidth: Double = 1, + resolutionMnKaEV: Double) throws -> [[Double]] { + BackgroundWindows.estimate(lines: try spectralLines(lines, resolutionMnKaEV: resolutionMnKaEV), + lineWidth: [lineWidth.left, lineWidth.right], windowsWidth: windowsWidth) + } + + private static func spectralLines(_ lines: [String], resolutionMnKaEV: Double) throws -> [SpectralLine] { + try lines.map { try SpectralLine(id: $0, resolutionMnKaEV: resolutionMnKaEV) } + } + + // MARK: - Intensities + + /// `get_lines_intensity(integration_windows=…, background_windows=…)` on one spectrum: the counts summed over each integration + /// window (the EDS axis is binned, so `integrate1D` is a sum) and, with background windows, less the sum of the two background + /// windows times the integration window's channel count over theirs. The channels are `WindowIntensity.resolve`'s (HyperSpy's + /// `value2index`: half a channel goes towards zero at a non-negative energy); an edge off the axis throws where eXSpy raises + /// (`WindowIntensityError`). A window narrower than one channel sums no channel, as eXSpy's slice does. + public static func intensities(counts: [Double], axis: EnergyAxis, integrationWindows: [[Double]], + backgroundWindows: [[Double]]? = nil) throws -> [Double] { + guard counts.count == axis.size else { throw EDSWindowPathError.channelCount(counts: counts.count, axis: axis.size) } + if let bw = backgroundWindows, bw.count != integrationWindows.count { + throw EDSWindowPathError.windowCount(background: bw.count, integration: integrationWindows.count) + } + func sum(_ range: Range) -> Double { + var s = 0.0 + for c in range { s += counts[c] } + return s + } + var out: [Double] = [] + out.reserveCapacity(integrationWindows.count) + for (i, window) in integrationWindows.enumerated() { + guard window.count == 2 else { throw EDSWindowPathError.windowEdges(expected: 2, edges: window.count) } + let background = backgroundWindows?[i] + if let bw = background, bw.count != 4 { throw EDSWindowPathError.windowEdges(expected: 4, edges: bw.count) } + let resolved = try WindowIntensity.resolve(integration: window, background: background, axis: axis) + let left = resolved.background.map { sum($0.left) } ?? 0 + let right = resolved.background.map { sum($0.right) } ?? 0 + out.append(resolved.net(sum(resolved.signal), left, right)) + } + return out + } + + // MARK: - Cliff-Lorimer + + /// `quantification_cliff_lorimer(intensities, kfactors)` on one spectrum, as weight fractions (sum 1), with no absorption + /// correction. The two routes differ only where fewer than two lines lie above eXSpy's 0.1-count floor, and the caller names + /// the route: + /// - `.refuse`, the kit's route and its default everywhere else (`EDXQuantification.quantify`): such a spectrum throws + /// `QuantError.needTwoLines`. + /// - `.exspyHundredPercent`, eXSpy's raw arithmetic: the one line above the floor is 1 and the others 0 (all 0 with none). + /// With two or more lines above the floor both routes run the same arithmetic. Times 100 is eXSpy's `quantification(method="CL")`; + /// `EDXQuantification.weightToAtomic` gives the atomic percent. + public static func cliffLorimer(intensities: [Double], kFactors: [Double], singleLine: SingleLineRule) throws -> [Double] { + try CliffLorimer.weightFractions(intensities: intensities, kFactors: kFactors, singleLine: singleLine) + } +} diff --git a/Sources/SpectroEDX/SpectroEDX.docc/SpectroEDX.md b/Sources/SpectroEDX/SpectroEDX.docc/SpectroEDX.md index 40ea2bc..b3a3ca7 100644 --- a/Sources/SpectroEDX/SpectroEDX.docc/SpectroEDX.md +++ b/Sources/SpectroEDX/SpectroEDX.docc/SpectroEDX.md @@ -60,6 +60,11 @@ Read for the walk from a summed spectrum to a - ``UnlistedLineChecker`` - ``UnlistedLineCheck`` +### exSpy's window path on one spectrum + +- ``EDSWindowPath`` +- ``EDSWindowPathError`` + ### X-ray lines and windows - ``XRayLines`` diff --git a/Sources/SpectroEDX/WindowIntensity.swift b/Sources/SpectroEDX/WindowIntensity.swift index 1c45a84..5ed6998 100644 --- a/Sources/SpectroEDX/WindowIntensity.swift +++ b/Sources/SpectroEDX/WindowIntensity.swift @@ -124,6 +124,13 @@ public nonisolated struct ResolvedWindow: Equatable, Sendable { guard let b = background else { return Double(signal) } return Double(signal) - Double(left &+ right) * b.scale } + + /// The same formula on sums of Double counts (`EDSWindowPath.intensities`): `signal - (left + right) * scale`, the two + /// background sums added first as eXSpy adds them. Equal to the integer form on integer counts below 2^53. + package func net(_ signal: Double, _ left: Double, _ right: Double) -> Double { + guard let b = background else { return signal } + return signal - (left + right) * b.scale + } } public nonisolated enum WindowIntensityError: Error, Equatable, Sendable { From 5c9d218dd4c79704bdc53b0a5fedb9bfe3e177b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 18:29:07 +0000 Subject: [PATCH 2/4] test: SEMEDSParityTests and the m7 TM002 bundles move from the app Byte-identical copies (equal sha256) of Electron Microscopy Studio's tools/parity/sem m7/eds-lines-tm002 and m7/eds-quant-tm002 bundles and their input exspy_EDS_SEM_TM002.hspy (at e7212f9), under Tests/SpectroEDXTests/Fixtures/sem. The moved tests run on EDSWindowPath at the bundles' tolerances, unchanged; the hspy file is read with FormatoHDF5. A new test holds the app's line table (the bundle's db_ arrays) against XRayLines and QuantElementData. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VkKZEUynSt6RczY9oKhrDU --- Package.swift | 9 +- Tests/Fixtures/README.md | 23 +- .../sem/fixtures/exspy_EDS_SEM_TM002.hspy | Bin 0 -> 31008 bytes .../background_windows_keV.bin | 1 + .../integration_windows_keV.bin | 1 + .../intensity_background_subtracted.bin | Bin 0 -> 40 bytes .../m7/eds-lines-tm002/intensity_raw.bin | Bin 0 -> 40 bytes .../m7/eds-lines-tm002/manifest.json | 103 ++ .../atomic_percent_planted.bin | 1 + .../eds-quant-tm002/atomic_percent_unit.bin | 1 + .../background_windows_default_keV.bin | 1 + .../m7/eds-quant-tm002/db_atomic_weight.bin | Bin 0 -> 760 bytes .../m7/eds-quant-tm002/db_line_energy_keV.bin | Bin 0 -> 7576 bytes .../m7/eds-quant-tm002/db_line_weight.bin | Bin 0 -> 7576 bytes .../references/m7/eds-quant-tm002/db_z.bin | Bin 0 -> 760 bytes .../intensity_background_default.bin | Bin 0 -> 40 bytes .../intensity_raw_width_2_1.bin | Bin 0 -> 40 bytes .../m7/eds-quant-tm002/line_fwhm_keV.bin | 2 + .../m7/eds-quant-tm002/manifest.json | 1244 +++++++++++++++++ .../weight_percent_planted.bin | Bin 0 -> 40 bytes .../eds-quant-tm002/weight_percent_unit.bin | 1 + Tests/SpectroEDXTests/SEMEDSParityTests.swift | 327 +++++ .../SpectroEDXTests/SEMParityReference.swift | 226 +++ tools/fixtures/inventory.py | 6 + 24 files changed, 1942 insertions(+), 4 deletions(-) create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/fixtures/exspy_EDS_SEM_TM002.hspy create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/background_windows_keV.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/integration_windows_keV.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/intensity_background_subtracted.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/intensity_raw.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/manifest.json create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/atomic_percent_planted.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/atomic_percent_unit.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/background_windows_default_keV.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_atomic_weight.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_line_energy_keV.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_line_weight.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_z.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/intensity_background_default.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/intensity_raw_width_2_1.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/line_fwhm_keV.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/manifest.json create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/weight_percent_planted.bin create mode 100644 Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/weight_percent_unit.bin create mode 100644 Tests/SpectroEDXTests/SEMEDSParityTests.swift create mode 100644 Tests/SpectroEDXTests/SEMParityReference.swift diff --git a/Package.swift b/Package.swift index 210f83b..db54ef4 100644 --- a/Package.swift +++ b/Package.swift @@ -113,10 +113,15 @@ let package = Package( ] ), // SpectroEDX: windows, the fit, the proposer, quantification, absorption, energy axis and peak identification on pins (exSpy, - // HyperSpy, RosettaSciIO) and planted truth (Fixtures/). + // HyperSpy, RosettaSciIO) and planted truth (Fixtures/); exspy's window path on the app's SEM bundles (Fixtures/sem, whose + // hspy input FormatoHDF5 reads). .testTarget( name: "SpectroEDXTests", - dependencies: ["SpectroEDX", "SpectroCore", "SpectroTestSupport", .product(name: "FormatoEMD", package: "FormatoKit")], + dependencies: [ + "SpectroEDX", "SpectroCore", "SpectroTestSupport", + .product(name: "FormatoCore", package: "FormatoKit"), .product(name: "FormatoEMD", package: "FormatoKit"), + .product(name: "FormatoHDF5", package: "FormatoKit"), + ], exclude: ["Fixtures"], swiftSettings: [ .enableUpcomingFeature("NonisolatedNonsendingByDefault"), diff --git a/Tests/Fixtures/README.md b/Tests/Fixtures/README.md index 7713e5d..5e918dc 100644 --- a/Tests/Fixtures/README.md +++ b/Tests/Fixtures/README.md @@ -1,11 +1,11 @@ # Test fixtures -One row per committed fixture under `Tests/*/Fixtures/` (311 files): its size and what writes it. Written by +One row per committed fixture under `Tests/*/Fixtures/` (330 files): its size and what writes it. Written by `tools/fixtures/inventory.py`; do not edit by hand. Generators run in the Python reference `tools/reference/setup.sh` builds (`References/python`), from the repo root, as each script's header says. Licence: every fixture is generated from this kit's code and its pinned Python reference and ships under the kit's -GPL-3.0-only licence, except the 7 rows marked *third party*: keep their licence line when the files move. No +GPL-3.0-only licence, except the 8 rows marked *third party*: keep their licence line when the files move. No fixture holds anyone's measured data; real datasets are read from `$MACEM_DATA` and never copied into the repo. A moved fixture is its own commit with the reason and a CHANGELOG line. @@ -64,6 +64,25 @@ A moved fixture is its own commit with the reason and a CHANGELOG line. | `SpectroEDXTests/Fixtures/public/SI_empty selection.emd` | 2.0 MB | copied from References/rosettasciio (rsciio/tests/data/emd) | third party: RosettaSciIO public test data (GPL-3.0-or-later, commit 049e7d70), copied unchanged | | `SpectroEDXTests/Fixtures/public/Test SI 16x16 215 kx.emd` | 2.0 MB | copied from References/rosettasciio (rsciio/tests/data/emd) | third party: RosettaSciIO public test data (GPL-3.0-or-later, commit 049e7d70), copied unchanged | | `SpectroEDXTests/Fixtures/public/fei_emd_si.emd` | 955.3 KB | copied from References/rosettasciio (rsciio/tests/data/emd) | third party: RosettaSciIO public test data (GPL-3.0-or-later, commit 049e7d70), copied unchanged | +| `SpectroEDXTests/Fixtures/sem/fixtures/exspy_EDS_SEM_TM002.hspy` | 31.0 KB | copied byte for byte from Electron Microscopy Studio's tools/parity/sem/fixtures (at e7212f9) | third party: exSpy's demo spectrum `EDS_SEM_TM002` (BAM EDS-TM002, GPL-3.0-or-later), copied unchanged; the input of the two m7 bundles | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/background_windows_keV.bin` | 0.2 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/integration_windows_keV.bin` | 0.1 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/intensity_background_subtracted.bin` | 0.0 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/intensity_raw.bin` | 0.0 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/manifest.json` | 2.3 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/atomic_percent_planted.bin` | 0.0 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/atomic_percent_unit.bin` | 0.0 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/background_windows_default_keV.bin` | 0.2 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_atomic_weight.bin` | 0.8 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_line_energy_keV.bin` | 7.6 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_line_weight.bin` | 7.6 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_z.bin` | 0.8 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/intensity_background_default.bin` | 0.0 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/intensity_raw_width_2_1.bin` | 0.0 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/line_fwhm_keV.bin` | 0.0 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/manifest.json` | 20.3 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/weight_percent_planted.bin` | 0.0 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | +| `SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/weight_percent_unit.bin` | 0.0 KB | Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9 | the app's generator stays in the app; equal sha256 to its copy | | `SpectroEDXTests/Fixtures/velox-stream-1stream-1frame.emd` | 49.6 KB | `tools/edx-planted/make_velox_streams.py` | | | `SpectroEDXTests/Fixtures/velox-stream-1stream-3frames.emd` | 206.7 KB | `tools/edx-planted/make_velox_streams.py` | | | `SpectroEDXTests/Fixtures/velox-stream-4streams-2frames.emd` | 105.6 KB | `tools/edx-planted/make_velox_streams.py` | | diff --git a/Tests/SpectroEDXTests/Fixtures/sem/fixtures/exspy_EDS_SEM_TM002.hspy b/Tests/SpectroEDXTests/Fixtures/sem/fixtures/exspy_EDS_SEM_TM002.hspy new file mode 100644 index 0000000000000000000000000000000000000000..724222e433e5c42ab29da80bb44db80494b4e5d6 GIT binary patch literal 31008 zcmeG_2~<=^wy#A51r?Vdijj6hj7Vrez%9~X10CrG=@vmvng+U|$6kP@*<6A|6UJnW zWAY;|M{`hrkkQ1^Xk0jMnW!24%D6;aMrTZ7T;rB;ASnE*S9NLng`Ng=a*pyI=XAZQ zci*jB_uYG|>fWm2_py_syLTJVjlq|zE7O_rU~l24iC)4YQUZB+o=R^7G%cfPWhZhY zV4NBJ%!`(LQ2atCQcy$7m5CAwgCGGvr1UYfr3<-pg#te9P#lPrh!b#wlWD6#o{msC z17=7Hvo*OogT|O=W{W^BBLJYCX)h|TT)B2ord)$MkFBA< zK)}9$9Dzb~f%u;qU!2y9R z&ma%*Ss31&T|~_Z)0J{o6c8E^7?7dKr+H@%$3biW-)v113*kcH;JHd}GHO(4sA8ua z>gz|Jizcg(2&#|>sz3w-3}!V$20TpjXooAOZuEUf-02O_Ly4%AJbXtP=}ws5obnmD zq@WL{Jjy}}pgkZbQ55ba4!l@T3OqUG$tk1&z7OzO6gc{Iv3zt;ph(05K>zMd-O8eD8g;uYM1Kkg3G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*& zaTwAeecdq-#fN3cijRCRLSI6&o;sqB)enkqpbb9aM=Dr92v18s`Pkqg@~V_7S)1<&PfPnKw82C4E=iK8kjBd$ez%tG8f=4y$W?NJBrz&h zOjlhxwgc94Fv0$l^;yXY@d~LDQ6x05J*=blwOltn#D*?nx0999IHf`v1BSBw@=nWuK~3Hzq3@И@ \ No newline at end of file diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/intensity_background_subtracted.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/intensity_background_subtracted.bin new file mode 100644 index 0000000000000000000000000000000000000000..7c95c40da5fc9a5d9a5ff6061248e1371a9813f4 GIT binary patch literal 40 scmbQF;yJ10)dvR#ATap;$>Gfrzc*K^zJU1&@4h%}&%M2^R_KcZ0CWoy-v9sr literal 0 HcmV?d00001 diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/intensity_raw.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/intensity_raw.bin new file mode 100644 index 0000000000000000000000000000000000000000..e1a9cf0b1e7ee52c0dab7ed9340cf5aeb5491658 GIT binary patch literal 40 jcmZQzU|=xl`QiYi7z*}%1=9iL-@){O*$~>m;D-YM#o`Kl literal 0 HcmV?d00001 diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/manifest.json b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/manifest.json new file mode 100644 index 0000000..f065317 --- /dev/null +++ b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/manifest.json @@ -0,0 +1,103 @@ +{ + "arrays": { + "background_windows_keV": { + "atol": 0.0, + "dtype": "float64", + "file": "background_windows_keV.bin", + "rtol": 1e-07, + "sha256": "73e03d0835ec5b760f437e1d7074cd42af56a82b13c129fde3fff45e496df3fd", + "shape": [ + 5, + 4 + ] + }, + "integration_windows_keV": { + "atol": 0.0, + "dtype": "float64", + "file": "integration_windows_keV.bin", + "rtol": 1e-07, + "sha256": "4f3659664b6b60353eb2427843e33d880474087c7129809fb7cc83307bf9ea59", + "shape": [ + 5, + 2 + ] + }, + "intensity_background_subtracted": { + "atol": 0.0, + "dtype": "float64", + "file": "intensity_background_subtracted.bin", + "rtol": 1e-07, + "sha256": "0460b44e5d48709efd88ba594996e4df2a51895a5f9abfd17810c770d4917ba7", + "shape": [ + 5 + ] + }, + "intensity_raw": { + "atol": 0.0, + "dtype": "float64", + "file": "intensity_raw.bin", + "rtol": 1e-07, + "sha256": "a7699e5f0caffa4d09326dc06a9d8894074888828910b9790392b8725979fb33", + "shape": [ + 5 + ] + } + }, + "case": "m7/eds-lines-tm002", + "inputs": [ + { + "path": "fixtures/exspy_EDS_SEM_TM002.hspy", + "sha256": "b5a5828dc694c7ed6e33745b7022594f48457e33140fb8d7371472fe18b6b359" + } + ], + "milestone": 7, + "reference": { + "function": "exspy.signals.EDSSEMSpectrum.get_lines_intensity", + "package": "exspy", + "version": "0.3.2" + }, + "scalars": {}, + "schema": 1, + "stack": { + "diffsims": "0.7.0", + "exspy": "0.3.2", + "h5py": "3.16.0", + "hyperspy": "2.5.0", + "kikuchipy": "0.13.1", + "numpy": "2.5.4", + "orix": "0.15.0", + "pyebsdindex": "0.3.10.1", + "python": "3.14.6", + "rsciio": "0.15.0", + "scipy": "1.18.1" + }, + "values": { + "background_line_width": [ + 5.0, + 2.0 + ], + "beam_energy_keV": 10.0, + "elements": [ + "Al", + "C", + "Cu", + "Mn", + "Zr" + ], + "integration_windows_width": 2.0, + "line_energies_keV": { + "Al_Ka": 1.4865, + "C_Ka": 0.2774, + "Cu_La": 0.9295, + "Mn_La": 0.63316, + "Zr_La": 2.0423 + }, + "xray_lines": [ + "Al_Ka", + "C_Ka", + "Cu_La", + "Mn_La", + "Zr_La" + ] + } +} diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/atomic_percent_planted.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/atomic_percent_planted.bin new file mode 100644 index 0000000..d69e2f3 --- /dev/null +++ b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/atomic_percent_planted.bin @@ -0,0 +1 @@ +'ŸÀ×åü$@+›oë„P@>K¡õ. @Øî¡¿Øâ@—¥“T¹v@ \ No newline at end of file diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/atomic_percent_unit.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/atomic_percent_unit.bin new file mode 100644 index 0000000..78d8d2c --- /dev/null +++ b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/atomic_percent_unit.bin @@ -0,0 +1 @@ +_vâµÔ4@+€bæè:I@¤¤‚™$@Ǧ—âY(@Tšêh @ \ No newline at end of file diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/background_windows_default_keV.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/background_windows_default_keV.bin new file mode 100644 index 0000000..891dcd2 --- /dev/null +++ b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/background_windows_default_keV.bin @@ -0,0 +1 @@ +w§ Iô?zÿŒÓUõ?J!#ŸP<ú?¾©Òvû?|7-{­ ¾?(•`r,ÙÅ?h=Ä¢A•Ø?:)}lÿÛ?šÒýìRÉÜ?( 6åcYà?ÞRJ¥\ñ?÷mÂEmò?šÒýìRÉÜ?( 6åcYà?ÞRJ¥\ñ?÷mÂEmò?‹FFzS–ü?öÓèMóý?Ñ„»Ï›³@†Ë¦b@ \ No newline at end of file diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_atomic_weight.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_atomic_weight.bin new file mode 100644 index 0000000000000000000000000000000000000000..439c65a0913b04611a4943a88ee27cf71f011eeb GIT binary patch literal 760 zcmWex=l-zDCDLKbiL!n3-O?QxK)@l#A>Ac2|3hpjgnuC0;q*e+ZJ&2WI;`?&-Po$| z!T#x7XUSDe0uD;X;yY~ElpG=~fhK4rI((MDlpimj<&g07g3|4u!46qs8RZ^7?Hu|K zebtCLp6;L-17Zb1%w3V}(0t(3Lf5=NhdXY}72I zo@F{TJ->HY^@aECsoR1T-VUqn!lO6-*LT<<*ZMk;!vUiHR~m#L5#Ye2 z-7a?XUy?)VWC@nAb72nlrg6JGU!*vEXgwKnFv8cNTA!gc@voV~^L!^oCaZ7R^0iqh21fjzd82 z^gN-@Ar3dseGh&tYU5zbb$xNc+E|A-fj}3YPI3TAH&=K%_`T%`j;?ZZC|pkk>wQtVuY*f>&hy_p9U(NQi^D-+FmG#4bnr3nbWF%ha1hxX$MaM+)xjp%x$Nhh z1cz%!b4?oldqV6z>hIva!D7zOm_&ya$Gpuu4@x^+oEY=ZxhKa$RX*o#GQ{5v5e{5}1stLC(j00*0k<#}A|8<9u%uV{+M}KE z4i5xYU3qgL*TK@&z38W97(_lH$Kk|`-P0y~k8;R;{(I#|whV_~hoofPep@+A|39Jb z_pTs^%f3kh5kH+Bs=8#9-p$K^=yS+&FysJ+@Rk@zc>E2AnwJNm7vw_dhCBxV0VX$G literal 0 HcmV?d00001 diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_line_energy_keV.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_line_energy_keV.bin new file mode 100644 index 0000000000000000000000000000000000000000..969b89ea34b1eaef62f642ecebc0080402176d55 GIT binary patch literal 7576 zcmX|GbzD?g8-{_QW9Wuq=nk>P^VkYDh}dhbwXUnK-QB%*uex@NVytT}*4m<&EQ*EF zo!>dLdN;=$P5<>f!K%XG!0V8zE$o zW5)eShG_O@_YK}w1{l_Q#F%`w3LCsvP8jQEgwZ!^PfZ(VirMY|n&FXZj1hWc<`}Ad zG2~vq_*)6xu=(PK)z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+XAA7}3D`ebN@nB!TB=3inGPz$1`MHbe zRSp_cAC~1$ee28wv=9PUubYBTBlHsoc~yGE55xVHefNQc)ec|OtzYlIFH^1PvR3Ia z^r`P}V*v7@0i>gi0&wNiBAaXP)#SgnhtT=o^HY3`|5{ zX)w)cuF8Y4i628OcQu4kYWS`=tM}5j|1M-jij7TS{4e>uN C5EbwM literal 0 HcmV?d00001 diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_line_weight.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_line_weight.bin new file mode 100644 index 0000000000000000000000000000000000000000..b7e6777d1db2e780ba046103d4ba7b1c7e3fe497 GIT binary patch literal 7576 zcmbtZd036>7Vji9smw{pT+TtqkYrdCiF8C{%+zs&3@Ir?gQQfNMT65;_O3Ljc9Wsn zP1sF_q*9VfL`dc`+;7_=6KOy z&k1h`3#I>R2z$m_O#S><_+c=Zc_&G~_!73G)WY~??>XMkKkLAZWe1WWYHLKUoO?5v zg^ct)U{eXjf(?%?CY3`(p+@q4s{qOUX^=JC{l)UEBslb?UI1O^At!I}IJ2HLpe9CRt2lt96I%?*C}WrW?)zg+9tZ@?vdZ(6*6N6=0Z56_FY zI}Wc)hYFLeDr;t5!13yi3&EC8o@e`|fJ^4QV~saFp|^gji(Fk8ejeG2K1=6q`_ko8 zOZds+;3mimaQ2y_P*lHzB5dJXlD1PXEanOZb z;~pj8^HCfTu25bP4p2O^F7=>FpbSv_(DU7Kf$~We$(cR0%JOLKp+)N0TzPI>%xA78^f#DH}t^>x4${v88F}@N;E>Qq$9|)A9E^ zcJ@@K08<${ENEbNX(7Fh%+Xj?OOcVh1&xyi0Bu}vS_~3JV zXYt+MJ9GJ8leqK~-^mxpM~g!Bd(AfZgN9|=ZBS+|62nEBMpQ%+KH-5^P}eXo>2zE- z$nMOo&NXu!NxS!jR&4t{B@`&q8?yXCJRIprHr*8#12pQ!?IYvQ+QH!{sd|(Bvf-rN zR~9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T-5CoJUMp4C%W}N(XkgxV^HdTS-S;}L#Rd9_JCg7{fuQQ} zY7VzIrr#F9b#iY^ztsTMQer-QM!kJH^Dqb=XaxC0xO0An_L(BSxt5%}kS>ssv3>U` zo8w&+mwMlQ>)N9(5jtS#WLlY%^CH3#+AmU~)y!@Tx#w|E7^CUrlLuXN`B-u~1l`N_ zKR!6w(Qm>s0PQnejB<|-(~W^aj8G-#do=H%e6hUl1?aq))V5JwBNdUVU{{_v)I-RFKExan0- zy5@w>9QU!G9rUYzT=2HvT=Avv-0+ygUi6SdesIiHr+ww9N1gGBNBrrC2R!Tz4|>fL z-u0>HJ?lLuz2qs+_{b$+yX*xo`_KWu_}1T^bJ6F{`QA6a@V Spectrum { + let url = try XCTUnwrap(ref.inputURL(), "the bundle names the TM002 fixture") + let input = try XCTUnwrap(ref.manifest.inputs.first) + let digest = try SHA256.hash(data: Data(contentsOf: url)).map { String(format: "%02x", $0) }.joined() + XCTAssertEqual(digest, input.sha256, "the fixture is the bundle's input byte for byte") + + let reader = try HDF5Reader(url: url) + let name = try XCTUnwrap(reader.children(of: "/Experiments").first, "the file holds one experiment") + let experiment = "/Experiments/" + name + func attribute(_ key: String, _ group: String) throws -> HDF5AttributeValue? { + let path = experiment + group + guard try reader.attributeNames(of: path).contains(key) else { return nil } + return try reader.attribute(key, of: path) + } + func number(_ key: String, _ group: String) throws -> Double? { + switch try attribute(key, group) { + case .real(let v)?: return v + case .integer(let v)?: return Double(v) + default: return nil + } + } + guard let offset = try number("offset", "/axis-0"), let scale = try number("scale", "/axis-0") else { + throw Unreadable(description: "the axis has no offset or scale") + } + guard case .text(let units)? = try attribute("units", "/axis-0") else { throw Unreadable(description: "the axis has no units") } + let counts = try reader.readDataset(experiment + "/data").doubles() + let elements = try reader.readStrings(experiment + "/metadata/Sample/_list_elements") + let sem = "/metadata/Acquisition_instrument/SEM", eds = sem + "/Detector/EDS", stage = sem + "/Stage" + let conditions = try EDSWindowPath.Conditions( + beamEnergyKeV: number("beam_energy", sem), energyResolutionMnKaEV: number("energy_resolution_MnKa", eds), + elevationAngleDeg: number("elevation_angle", eds), azimuthAngleDeg: number("azimuth_angle", eds), + tiltAlphaDeg: number("tilt_alpha", stage), tiltBetaDeg: number("tilt_beta", stage), + liveTimeS: number("live_time", eds), realTimeS: number("real_time", eds)) + return Spectrum(counts: counts, axis: EnergyAxis(offset: offset, scale: scale, size: counts.count), units: units, + elements: elements, conditions: conditions) + } + + private static func element(_ line: String) -> String { XRayLines.line(line)?.element ?? "" } + + // MARK: - One line table + + /// exspy's element table (`exspy._misc.elements.elements`, the app's generated `XrayLineDatabase`, held exact by its `db_` arrays) + /// and the kit's `XRayLines` (from `xray_lines.json`) with `QuantElementData`: every line the app's table holds is in the kit's + /// at the same energy and weight, with no line more; every element has the same Z and atomic weight and the same lines. + func testTheAppsLineTableIsTheKits() throws { + let ref = try SEMParityReference.load("m7/eds-quant-tm002") + let elements = try XCTUnwrap(ref.values["db_elements"] as? [String]) + let lines = try XCTUnwrap(ref.values["db_xray_lines"] as? [String]) + let z = try ref.array("db_z").values, atomicWeight = try ref.array("db_atomic_weight").values + let energy = try ref.array("db_line_energy_keV").values, weight = try ref.array("db_line_weight").values + XCTAssertEqual(elements.count, 95) + XCTAssertEqual(lines.count, 947) + XCTAssertEqual(energy.count, lines.count) + XCTAssertEqual(weight.count, lines.count) + XCTAssertEqual(XRayLines.all.count, lines.count, "the kit's table has no line the app's lacks") + XCTAssertEqual(Set(XRayLines.all.map(\.id)), Set(lines)) + + var zOf: [String: Double] = [:] + for (i, symbol) in elements.enumerated() { + zOf[symbol] = z[i] + let entry = try XCTUnwrap(QuantElementData.entry(symbol), symbol) + XCTAssertEqual(Double(entry.z), z[i], symbol) + XCTAssertEqual(entry.atomicWeight, atomicWeight[i], symbol) + let own = Set(lines.filter { $0.hasPrefix(symbol + "_") }) + XCTAssertEqual(Set(XRayLines.all.filter { $0.element == symbol }.map(\.id)), own, symbol) + } + for (i, id) in lines.enumerated() { + let line = try XCTUnwrap(XRayLines.line(id), id) + XCTAssertEqual(line.energy, energy[i], id) + XCTAssertEqual(line.weight, weight[i], id) + XCTAssertEqual(Double(line.atomicNumber), zOf[line.element], id) + } + XCTAssertEqual(XRayLines.line("Mn_La")?.energy, 0.63316) + XCTAssertNil(XRayLines.line("Mn_Xa")) + XCTAssertEqual(XRayLines.lines(of: "Li"), [], "exspy lists Li without X-ray lines") + } + + // MARK: - The conditions the file states + + func testTM002ConditionsAreTheFilesAndTheTakeOffAngleIsExspys() throws { + let ref = try SEMParityReference.load("m7/eds-quant-tm002") + let spectrum = try tm002(ref) + XCTAssertEqual(spectrum.units, "keV") + XCTAssertEqual(spectrum.elements, ["Al", "C", "Cu", "Mn", "Zr"]) + let c = spectrum.conditions + XCTAssertEqual(c.beamEnergyKeV, 10.0) + XCTAssertEqual(c.energyResolutionMnKaEV, 130.0) + XCTAssertEqual(c.elevationAngleDeg, 37.0) + XCTAssertEqual(c.azimuthAngleDeg, 0.0) + XCTAssertEqual(c.tiltAlphaDeg, 0.0) + XCTAssertEqual(c.tiltBetaDeg, 0.0) + XCTAssertEqual(try XCTUnwrap(c.liveTimeS), 19.997292, accuracy: 1e-12) + SEMAssertParity(c.takeOffAngleDeg, ref, scalar: "take_off_angle_deg") + // exspy's docstring: 20° of stage tilt adds 20° to the take-off angle of this geometry. + XCTAssertEqual(EDXQuantification.takeOffAngle(tiltAlpha: 20, azimuth: 0, elevation: 37), 57.0, accuracy: 1e-9) + } + + /// What the file leaves out takes exspy's defaults (`EDSConfig`). + func testConditionsTakeExspysDefaults() { + let bare = EDSWindowPath.Conditions(beamEnergyKeV: nil) + XCTAssertNil(bare.beamEnergyKeV) + XCTAssertEqual(bare.energyResolutionMnKaEV, 130) + XCTAssertEqual(bare.elevationAngleDeg, 35) + XCTAssertEqual(bare.azimuthAngleDeg, 0) + XCTAssertEqual(bare.tiltAlphaDeg, 0) + XCTAssertEqual(bare.tiltBetaDeg, 0) + XCTAssertNil(bare.liveTimeS) + XCTAssertNil(bare.realTimeS) + XCTAssertEqual(bare.takeOffAngleDeg, EDXQuantification.takeOffAngle(tiltAlpha: 0, azimuth: 0, elevation: 35)) + } + + // MARK: - Figure F16 + + func testFigureF16LinesWindowsAndIntensitiesMatchExspy() throws { + let ref = try SEMParityReference.load("m7/eds-lines-tm002") + let spectrum = try tm002(ref) + let resolution = spectrum.conditions.energyResolutionMnKaEV + let lines = EDSWindowPath.lines(forElements: spectrum.elements, axis: spectrum.axis, beamEnergyKeV: spectrum.conditions.beamEnergyKeV) + XCTAssertEqual(lines, ref.values["xray_lines"] as? [String]) + let energies = try XCTUnwrap(ref.values["line_energies_keV"] as? [String: Double]) + for line in lines { XCTAssertEqual(XRayLines.line(line)?.energy, energies[line], line) } + + let integration = try EDSWindowPath.integrationWindows(lines, width: 2.0, resolutionMnKaEV: resolution) + try SEMAssertParity(integration.flatMap { $0 }, ref.array("integration_windows_keV"), shape: [lines.count, 2]) + let background = try EDSWindowPath.backgroundWindows(lines, lineWidth: (5.0, 2.0), resolutionMnKaEV: resolution) + try SEMAssertParity(background.flatMap { $0 }, ref.array("background_windows_keV"), shape: [lines.count, 4]) + + let raw = try EDSWindowPath.intensities(counts: spectrum.counts, axis: spectrum.axis, integrationWindows: integration) + try SEMAssertParity(raw, ref.array("intensity_raw")) + let net = try EDSWindowPath.intensities(counts: spectrum.counts, axis: spectrum.axis, integrationWindows: integration, + backgroundWindows: background) + try SEMAssertParity(net, ref.array("intensity_background_subtracted")) + + // One implementation: the kit's integer window sums (what `ElementWindows` reads) give the same numbers on these counts. + let integerCounts = spectrum.counts.map { UInt64($0) } + let resolved = try zip(integration, background).map { window, bw in + try WindowIntensity.resolve(integration: window, background: bw, axis: spectrum.axis) + } + XCTAssertEqual(WindowIntensity.netCounts(spectrum: integerCounts, windows: resolved), net) + } + + // MARK: - Figure F17 and the rest of the window path + + /// F17 pins exspy's raw arithmetic (`.exspyHundredPercent`); on TM002 every line is far above the floor, so the kit's refusing + /// route (`.refuse`, and `EDXQuantification.quantify`, its default) gives the same numbers. + func testFigureF17CliffLorimerMatchesExspy() throws { + let ref = try SEMParityReference.load("m7/eds-quant-tm002") + let spectrum = try tm002(ref) + let resolution = spectrum.conditions.energyResolutionMnKaEV + let lines = EDSWindowPath.lines(forElements: spectrum.elements, axis: spectrum.axis, beamEnergyKeV: spectrum.conditions.beamEnergyKeV) + XCTAssertEqual(lines, ref.values["xray_lines"] as? [String]) + var fwhm: [Double] = [] + for line in lines { + let energy = try XCTUnwrap(XRayLines.line(line)?.energy, line) + try fwhm.append(XCTUnwrap(XRayLines.fwhm(resolutionMnKaEV: resolution, atEnergy: energy), line)) + } + try SEMAssertParity(fwhm, ref.array("line_fwhm_keV")) + + // The intensities the EDS room quantifies: background-subtracted with exspy's tutorial windows (5, 2). + let net = try EDSWindowPath.intensities( + counts: spectrum.counts, axis: spectrum.axis, + integrationWindows: EDSWindowPath.integrationWindows(lines, resolutionMnKaEV: resolution), + backgroundWindows: EDSWindowPath.backgroundWindows(lines, lineWidth: (5.0, 2.0), resolutionMnKaEV: resolution)) + let elements = lines.map { Self.element($0) } + let planted = try XCTUnwrap(ref.values["kfactors_planted"] as? [Double]) + for (name, k) in [("unit", [Double](repeating: 1, count: lines.count)), ("planted", planted)] { + let expectedWeight = try ref.array("weight_percent_\(name)"), expectedAtomic = try ref.array("atomic_percent_\(name)") + for rule in [SingleLineRule.exspyHundredPercent, .refuse] { + let weight = try EDSWindowPath.cliffLorimer(intensities: net, kFactors: k, singleLine: rule).map { $0 * 100.0 } + SEMAssertParity(weight, expectedWeight) + try SEMAssertParity(EDXQuantification.weightToAtomic(weight, elements: elements), expectedAtomic) + XCTAssertEqual(weight.reduce(0, +), 100, accuracy: 1e-9, "\(name) \(rule)") + } + let setup = EDXQuantificationSetup(elements: elements, method: .cliffLorimer(kFactors: k, thicknessNm: nil)) + let pixel = try EDXQuantification.quantify(intensities: net, setup: setup) + SEMAssertParity(pixel.weightPercent, expectedWeight) + SEMAssertParity(pixel.atomicPercent, expectedAtomic) + } + } + + func testDefaultBackgroundWindowsAndAWiderWindowMatchExspy() throws { + let ref = try SEMParityReference.load("m7/eds-quant-tm002") + let spectrum = try tm002(ref) + let resolution = spectrum.conditions.energyResolutionMnKaEV + let lines = try XCTUnwrap(ref.values["xray_lines"] as? [String]) + let integration = try EDSWindowPath.integrationWindows(lines, resolutionMnKaEV: resolution) + let background = try EDSWindowPath.backgroundWindows(lines, resolutionMnKaEV: resolution) + try SEMAssertParity(background.flatMap { $0 }, ref.array("background_windows_default_keV"), shape: [lines.count, 4]) + let net = try EDSWindowPath.intensities(counts: spectrum.counts, axis: spectrum.axis, integrationWindows: integration, + backgroundWindows: background) + try SEMAssertParity(net, ref.array("intensity_background_default")) + let wider = try EDSWindowPath.integrationWindows(lines, width: 2.1, resolutionMnKaEV: resolution) + let raw = try EDSWindowPath.intensities(counts: spectrum.counts, axis: spectrum.axis, integrationWindows: wider) + try SEMAssertParity(raw, ref.array("intensity_raw_width_2_1")) + } + + func testLinesFollowTheBeamEnergyAsExspyPicksThem() throws { + let ref = try SEMParityReference.load("m7/eds-quant-tm002") + let spectrum = try tm002(ref) + let byBeam = try XCTUnwrap(ref.values["xray_lines_by_beam_energy"] as? [String: [String]]) + XCTAssertEqual(byBeam.count, 3) + for (kv, expected) in byBeam { + let beam = try XCTUnwrap(Double(kv)) + XCTAssertEqual(EDSWindowPath.lines(forElements: spectrum.elements, axis: spectrum.axis, beamEnergyKeV: beam), expected, "\(kv) kV") + } + } + + // MARK: - Rules the bundles do not reach + + /// HyperSpy's channel rule, the one the kit's windows use (`EnergyAxis`): half a channel rounds towards zero for a non-negative + /// energy, away from zero for a negative one; off the axis there is no channel. + func testChannelRoundingIsHyperSpys() { + let axis = EnergyAxis(offset: -0.1, scale: 0.01, size: 1024) + XCTAssertEqual(try axis.index(of: -0.1), 0) + XCTAssertEqual(try axis.index(of: 0.0), 10) + XCTAssertEqual(try axis.index(of: 0.105), 20, "20.5 rounds towards zero") + XCTAssertEqual(try axis.index(of: 0.106), 21) + XCTAssertEqual(try axis.index(of: -0.045), 6, "5.5 at a negative energy rounds away from zero") + XCTAssertThrowsError(try axis.index(of: -0.2)) + XCTAssertThrowsError(try axis.index(of: 10.5)) + XCTAssertEqual(try axis.channelRange(from: -0.5, to: 0.0), 0 ..< 10, "a start below the axis starts at 0") + XCTAssertEqual(try axis.channelRange(from: 10.0, to: 20.0), 1010 ..< 1024, "a stop above the axis runs to the end") + XCTAssertThrowsError(try axis.channelRange(from: 11.0, to: 12.0)) + } + + /// exspy's floor: a line at or below 0.1 counts never serves as the reference. One line above it is the whole composition on + /// exspy's route and a refusal on the kit's. + func testCliffLorimerFloorAndSingleLine() throws { + XCTAssertEqual(try EDSWindowPath.cliffLorimer(intensities: [0.05, 200, 0], kFactors: [1, 1, 1], singleLine: .exspyHundredPercent), [0, 1, 0]) + XCTAssertEqual(try EDSWindowPath.cliffLorimer(intensities: [0, 0], kFactors: [1, 1], singleLine: .exspyHundredPercent), [0, 0]) + XCTAssertThrowsError(try EDSWindowPath.cliffLorimer(intensities: [0.05, 200, 0], kFactors: [1, 1, 1], singleLine: .refuse)) { error in + XCTAssertEqual(error as? QuantError, .needTwoLines(linesAbove: 1)) + } + for rule in [SingleLineRule.exspyHundredPercent, .refuse] { + let two = try EDSWindowPath.cliffLorimer(intensities: [100, 300], kFactors: [1, 1], singleLine: rule) + XCTAssertEqual(two[0], 0.25, accuracy: 1e-15) + XCTAssertEqual(two[1], 0.75, accuracy: 1e-15) + XCTAssertThrowsError(try EDSWindowPath.cliffLorimer(intensities: [1, 2], kFactors: [1], singleLine: rule)) + } + XCTAssertEqual(try EDXQuantification.weightToAtomic([0, 0], elements: ["Cu", "Sn"]), [0, 0]) + } + + /// exspy's own docstring examples on this spectrum (`get_lines_intensity`): Mn La with the default window, and Mn Ka with + /// background windows when Mn is the only element. + func testExspyDocstringIntensities() throws { + let ref = try SEMParityReference.load("m7/eds-lines-tm002") + let spectrum = try tm002(ref) + let resolution = spectrum.conditions.energyResolutionMnKaEV + let la = try EDSWindowPath.intensities(counts: spectrum.counts, axis: spectrum.axis, + integrationWindows: EDSWindowPath.integrationWindows(["Mn_La"], resolutionMnKaEV: resolution)) + XCTAssertEqual(la, [96700]) + let ka = ["Mn_Ka"] + let ka21 = try EDSWindowPath.intensities(counts: spectrum.counts, axis: spectrum.axis, + integrationWindows: EDSWindowPath.integrationWindows(ka, width: 2.1, resolutionMnKaEV: resolution)) + XCTAssertEqual(ka21, [53597]) + let net = try EDSWindowPath.intensities(counts: spectrum.counts, axis: spectrum.axis, + integrationWindows: EDSWindowPath.integrationWindows(ka, resolutionMnKaEV: resolution), + backgroundWindows: EDSWindowPath.backgroundWindows(ka, resolutionMnKaEV: resolution)) + XCTAssertEqual(net, [46716]) + } + + /// The lines outside the spectral range are the rest, in order; a spectrum and its axis must agree, and a window off the axis is + /// refused where HyperSpy raises. + func testRangeAndRefusals() { + let axis = EnergyAxis(offset: 0, scale: 0.01, size: 1024) + let split = EDSWindowPath.linesInSpectralRange(["Mn_La", "Mn_Ka", "Xx_Ka", "Al_Ka"], axis: axis, beamEnergyKeV: 5) + XCTAssertEqual(split.inRange, ["Mn_La", "Al_Ka"]) + XCTAssertEqual(split.outOfRange, ["Mn_Ka", "Xx_Ka"]) + XCTAssertThrowsError(try EDSWindowPath.intensities(counts: [1, 2], axis: EnergyAxis(offset: 0, scale: 1, size: 3), + integrationWindows: [[0, 1]])) { error in + XCTAssertEqual(error as? EDSWindowPathError, .channelCount(counts: 2, axis: 3)) + } + let small = EnergyAxis(offset: 0, scale: 0.01, size: 100) + let counts = [Double](repeating: 1, count: 100) + XCTAssertThrowsError(try EDSWindowPath.intensities(counts: counts, axis: small, integrationWindows: [[1.5, 2]])) { error in + XCTAssertEqual(error as? WindowIntensityError, .axis(.sliceBeyondAxis(start: 1.5, stop: 2))) + } + XCTAssertThrowsError(try EDSWindowPath.intensities(counts: counts, axis: small, integrationWindows: [[0.1, 0.2]], + backgroundWindows: [])) { error in + XCTAssertEqual(error as? EDSWindowPathError, .windowCount(background: 0, integration: 1)) + } + XCTAssertThrowsError(try EDSWindowPath.integrationWindows(["Mn_Xa"], resolutionMnKaEV: 130)) { error in + XCTAssertEqual(error as? SpectralLineError, .unknownLine("Mn_Xa")) + } + } +} diff --git a/Tests/SpectroEDXTests/SEMParityReference.swift b/Tests/SpectroEDXTests/SEMParityReference.swift new file mode 100644 index 0000000..263112d --- /dev/null +++ b/Tests/SpectroEDXTests/SEMParityReference.swift @@ -0,0 +1,226 @@ +// +// SEMParityReference.swift +// Copied from FormatoKit's Tests/FormatoEDSTests (FormatoKit#183), itself moved from Electron Microscopy Studio's EMStudioTests, +// for exspy's window path (SpectroKit#131) with the two bundles it reads: m7/eds-lines-tm002 and m7/eds-quant-tm002 of the app's +// tools/parity/sem/references (at e7212f9) and their input fixtures/exspy_EDS_SEM_TM002.hspy, copied byte for byte into +// Fixtures/sem (the `references/` and `fixtures/` folders, laid out as there). +// The Swift side of the app's tools/parity/sem: a reference bundle (manifest.json plus raw little-endian arrays, written by the app's +// tools/parity/sem/emit.py from the pinned HyperSpy / exspy stack) loaded for a parity test, and the comparison every SEM port is +// held to: numpy's assert_allclose rule, |a - b| <= atol + rtol * |b|, with the reference as b and the tolerance the bundle states +// (0/0 is exact). A port's test loads its case by name, runs the Swift function on the same fixture (`inputs`) and compares; +// nothing here makes a number. +// +// Layout (the app's tools/parity/sem/lib/refbundle.py is the writer and the schema's owner): +// references///manifest.json schema 1: reference package and version, stack, inputs with sha256, +// values (exact JSON), scalars (value, rtol, atol), arrays (file, dtype, +// shape, sha256, rtol, atol) +// references///.bin C order, little-endian, no header; uint8 uint16 int32 int64 float32 float64 +// + +import CryptoKit +import Foundation +import XCTest + +/// One committed reference case. +nonisolated struct SEMParityReference { + struct ArrayEntry: Decodable, Sendable { + let file: String + let dtype: String + let shape: [Int] + let sha256: String + let rtol: Double + let atol: Double + let note: String? + var count: Int { shape.reduce(1, *) } + } + + struct ScalarEntry: Decodable, Sendable { + let value: Double + let rtol: Double + let atol: Double + } + + struct Input: Decodable, Sendable { + let path: String + let sha256: String + } + + struct Manifest: Decodable, Sendable { + struct Package: Decodable, Sendable { + let package: String + let version: String + let function: String + } + + let schema: Int + let caseName: String + let milestone: Int + let reference: Package + let stack: [String: String?] + let inputs: [Input] + let scalars: [String: ScalarEntry] + let arrays: [String: ArrayEntry] + // `values` is free-form JSON: read it as `[String: Any]` through `SEMParityReference.values`. + + enum CodingKeys: String, CodingKey { + case schema, milestone, reference, stack, inputs, scalars, arrays + case caseName = "case" + } + } + + /// A loaded array: its shape (row-major) and its elements widened to Double (every dtype the writer allows is exact in + /// Double except int64 beyond 2^53, which no bundle holds; a loader that needs the raw bytes reads `rawData`). + struct LoadedArray: Sendable { + let name: String + let shape: [Int] + let dtype: String + let values: [Double] + let rtol: Double + let atol: Double + } + + let directory: URL + let manifest: Manifest + let values: [String: Any] + + /// The bundles' copy beside this file: Fixtures/sem, laid out as the app's tools/parity/sem. + static var harnessRoot: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/sem", isDirectory: true) + } + + static var referencesRoot: URL { harnessRoot.appendingPathComponent("references", isDirectory: true) } + + static func load(_ caseName: String) throws -> SEMParityReference { + let dir = referencesRoot.appendingPathComponent(caseName, isDirectory: true) + let data = try Data(contentsOf: dir.appendingPathComponent("manifest.json")) + let manifest = try JSONDecoder().decode(Manifest.self, from: data) + guard manifest.schema == 1 else { throw Failure("\(caseName): manifest schema \(manifest.schema), this loader reads 1") } + guard manifest.caseName == caseName else { throw Failure("\(caseName): manifest names case \(manifest.caseName)") } + let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] + let values = json?["values"] as? [String: Any] ?? [:] + return SEMParityReference(directory: dir, manifest: manifest, values: values) + } + + /// The fixture an input names, as a URL under Fixtures/sem; nil for any other input (a downloaded dataset, not committed). + func inputURL(_ index: Int = 0) -> URL? { + guard manifest.inputs.indices.contains(index) else { return nil } + let path = manifest.inputs[index].path + if path.hasPrefix("fixtures/") { return Self.harnessRoot.appendingPathComponent(path) } + return nil + } + + func rawData(_ name: String) throws -> (ArrayEntry, Data) { + guard let entry = manifest.arrays[name] else { throw Failure("\(manifest.caseName): no array \(name)") } + let data = try Data(contentsOf: directory.appendingPathComponent(entry.file)) + return (entry, data) + } + + /// The array by name, its bytes checked against the manifest's sha256 and count. + func array(_ name: String) throws -> LoadedArray { + let (entry, data) = try rawData(name) + let digest = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + guard digest == entry.sha256 else { throw Failure("\(manifest.caseName)/\(name): file sha256 \(digest) is not the manifest's \(entry.sha256)") } + let values = try Self.decode(data, dtype: entry.dtype, count: entry.count, label: "\(manifest.caseName)/\(name)") + return LoadedArray(name: name, shape: entry.shape, dtype: entry.dtype, values: values, rtol: entry.rtol, atol: entry.atol) + } + + static func decode(_ data: Data, dtype: String, count: Int, label: String) throws -> [Double] { + func read(_: T.Type) throws -> [Double] { + guard data.count == count * MemoryLayout.size else { throw Failure("\(label): \(data.count) bytes for \(count) \(dtype)") } + return data.withUnsafeBytes { raw in (0...size, as: T.self))) } } + } + switch dtype { + case "uint8": return try read(UInt8.self) + case "uint16": return try read(UInt16.self) + case "int32": return try read(Int32.self) + case "int64": return try read(Int64.self) + case "float32": + guard data.count == count * 4 else { throw Failure("\(label): \(data.count) bytes for \(count) float32") } + return data.withUnsafeBytes { raw in (0.. Mismatch? { + guard actual.count == expected.count else { + return Mismatch(name: name, count: max(actual.count, expected.count), total: expected.count, worstIndex: -1, + actual: Double(actual.count), expected: Double(expected.count), rtol: rtol, atol: atol) + } + var bad = 0 + var worst = -1 + var worstExcess = -Double.infinity + for i in actual.indices { + let a = actual[i] + let b = expected[i] + if a.isNaN, b.isNaN { continue } + let excess = abs(a - b) - (atol + rtol * abs(b)) + if !(excess <= 0) { // NaN against a number fails too + bad += 1 + if excess > worstExcess || excess.isNaN { + worstExcess = excess + worst = i + } + } + } + guard bad > 0 else { return nil } + return Mismatch(name: name, count: bad, total: expected.count, worstIndex: worst, actual: actual[worst], expected: expected[worst], rtol: rtol, atol: atol) + } + + static func mismatch(actual: [Double], reference: SEMParityReference.LoadedArray) -> Mismatch? { + mismatch(name: reference.name, actual: actual, expected: reference.values, rtol: reference.rtol, atol: reference.atol) + } +} + +/// Assert a Swift result against a reference array at the bundle's tolerance. +nonisolated func SEMAssertParity(_ actual: [Double], _ reference: SEMParityReference.LoadedArray, shape: [Int]? = nil, + file: StaticString = #filePath, line: UInt = #line) { + if let shape, shape != reference.shape { + XCTFail("\(reference.name): shape \(shape), reference \(reference.shape)", file: file, line: line) + return + } + if let m = SEMParityCompare.mismatch(actual: actual, reference: reference) { + XCTFail(m.description, file: file, line: line) + } +} + +/// Assert a scalar against a reference scalar at its tolerance. +nonisolated func SEMAssertParity(_ actual: Double, _ reference: SEMParityReference, scalar name: String, + file: StaticString = #filePath, line: UInt = #line) { + guard let s = reference.manifest.scalars[name] else { + XCTFail("\(reference.manifest.caseName): no scalar \(name)", file: file, line: line) + return + } + if let m = SEMParityCompare.mismatch(name: name, actual: [actual], expected: [s.value], rtol: s.rtol, atol: s.atol) { + XCTFail(m.description, file: file, line: line) + } +} diff --git a/tools/fixtures/inventory.py b/tools/fixtures/inventory.py index 9c158c5..f6047bb 100644 --- a/tools/fixtures/inventory.py +++ b/tools/fixtures/inventory.py @@ -39,6 +39,12 @@ (r"SpectroCoreTests/Fixtures/spectro-golden/.*", "SpectroGoldenTests' recorder (`SPECTRO_GOLDEN_DIR= swift test --filter testRecordBaseline`; arrays: `SPECTRO_GOLDEN_ARRAYS_DIR= tools/test.sh --filter SpectroGoldenTests/testRecordPortableArrays`)", ""), (r"SpectroEDXTests/Fixtures/public/.*\.emd", "copied from References/rosettasciio (rsciio/tests/data/emd)", RSCIIO), (r"SpectroEDXTests/Fixtures/edx-0100-exspy\.json", "tools/edx-kfactor-import/pins.py", ""), + (r"SpectroEDXTests/Fixtures/sem/fixtures/exspy_EDS_SEM_TM002\.hspy", + "copied byte for byte from Electron Microscopy Studio's tools/parity/sem/fixtures (at e7212f9)", + "third party: exSpy's demo spectrum `EDS_SEM_TM002` (BAM EDS-TM002, GPL-3.0-or-later), copied unchanged; the input of the two m7 bundles"), + (r"SpectroEDXTests/Fixtures/sem/references/m7/eds-(lines|quant)-tm002/.*", + "Electron Microscopy Studio's tools/parity/sem/emit.py (exSpy 0.3.2, HyperSpy 2.5.0), copied byte for byte at e7212f9", + "the app's generator stays in the app; equal sha256 to its copy"), (r"SpectroEDXTests/Fixtures/edx-quant-maps-exspy\.json", "tools/edx-quant-maps/pins.py", ""), (r"SpectroEDXTests/Fixtures/xray-lines-exspy-7185a4d1\.json", "tools/edx-lines/pins.py", ""), (r"SpectroEDXTests/Fixtures/edx-(planted|calibration).*", "tools/edx-planted/make_planted.py", ""), From 90ee258bcdf2a92b91630239d9071cb2f892efaa Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 18:29:07 +0000 Subject: [PATCH 3/4] docs: the SEM-EDS window path in the README, status, parity table and NOTICE Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VkKZEUynSt6RczY9oKhrDU --- NOTICE | 10 ++++++++++ README.md | 2 +- docs/parity.md | 32 +++++++++++++++++++++++++++----- docs/status.md | 7 +++++-- 4 files changed, 43 insertions(+), 8 deletions(-) diff --git a/NOTICE b/NOTICE index 7c1a314..084084d 100644 --- a/NOTICE +++ b/NOTICE @@ -38,6 +38,16 @@ with eXSpy is not validation. The element table in Sources/SpectroEDX/Quant/QuantElementData.swift (atomic weights and densities) comes from eXSpy's elements data (GPL-3.0-or-later). +Sources/SpectroEDX/EDSWindowPath.swift (exSpy's window path for one SEM spectrum: lines, windows, +intensities, the acquisition defaults, Cliff-Lorimer) was merged from Electron Microscopy Studio +(https://github.com/EMSuite/Electron-Microscopy-Studio, GPL-3.0-only, commit e7212f9, SEMEDSLines.swift) +onto the functions above; it ports eXSpy 0.3.2 and HyperSpy 2.5.0 (GPL-3.0-or-later), the same +functions as the commit named above. Its test bundles in Tests/SpectroEDXTests/Fixtures/sem/references +hold eXSpy 0.3.2's outputs (GPL-3.0-or-later), written by the app's tools/parity/sem/emit.py and copied +byte for byte; their input, Tests/SpectroEDXTests/Fixtures/sem/fixtures/exspy_EDS_SEM_TM002.hspy +(sha256 b5a5828dc694c7ed6e33745b7022594f48457e33140fb8d7371472fe18b6b359), is eXSpy's demo spectrum +EDS_SEM_TM002 (the BAM EDS-TM002 reference material, GPL-3.0-or-later), copied unchanged. + The file readers (the Velox EMD reader, the DM4 reader with its EDS and EELS spectrum images, the HDF5 lock) moved to FormatoKit (https://github.com/EMSuite/FormatoKit, GPL-3.0-only) at SpectroKit 0.4.0, with their notices, their rosettasciio comparison and their fixtures. SpectroKit depends on FormatoKit 0.2.1. diff --git a/README.md b/README.md index ec876fd..82a90b0 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Three products, each a Swift module: | Product | What it does | |---|---| | `SpectroCore` | What EDS and EELS share: the spectrum image (dense and sparse), `EnergyAxis` (HyperSpy's channel rounding), opening a Velox `.emd` or a Gatan `.dm4` EDS spectrum image, linear least-squares and Poisson maximum-likelihood fits (Accelerate LAPACK), counting statistics and sigma propagation. | -| `SpectroEDX` | The X-ray part: the line table, the EDS line and continuum model and its fit, the element proposer (Currie detection limit), Cliff-Lorimer quantification with computed k-factors, the four-detector absorption correction, export. Depends on `SpectroCore`. | +| `SpectroEDX` | The X-ray part: the line table, the EDS line and continuum model and its fit, the element proposer (Currie detection limit), Cliff-Lorimer quantification with computed k-factors, the four-detector absorption correction, exSpy's window path for one SEM spectrum (`EDSWindowPath`: lines, windows, intensities, Cliff-Lorimer), export. Depends on `SpectroCore`. | | `SpectroEELS` | The thickness t/lambda by the log-ratio method (`EELSThickness.logRatio`); zero-loss alignment; Fourier-log, Fourier-ratio and Richardson-Lucy deconvolution; the edge model fit (joint or per-edge windows, with a 1σ per edge), the MLLS fit and composition in at% and wt%; areal density by the ratio method. Cross sections from the dft generalised oscillator strengths for 383 K, L and M edges of 95 elements. Depends on `SpectroCore`. | The numerical methods follow exSpy's line by line, with deviations named in the code and compared against exSpy's own diff --git a/docs/parity.md b/docs/parity.md index 3134f66..724f0b6 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -66,8 +66,8 @@ absorption loop must stop on the same iteration. | state | EDS | EELS | shared | all | |---|---|---|---|---| -| present | 24 | 24 | 10 | 58 | -| partial | 9 | 2 | 0 | 11 | +| present | 25 | 24 | 10 | 59 | +| partial | 8 | 2 | 0 | 10 | | missing | 13 | 9 | 1 | 23 | | not planned | 4 | 4 | 0 | 8 | | rows | 50 | 39 | 11 | 100 | @@ -77,7 +77,7 @@ recounted after the 0.9.0 EELS rows were added, so the EELS column moves by more four rows (sum and escape peaks, k-factor import, sigma on wt% and at%, the per-region result). The three-column tables above (CI portability, with the new line-profile, smoothing and sparse-transport rows) are not part of this count. -Of the present rows: BIT 10, TOL 33, DEV 8, NOPIN 5, and two rows with their own code (EXACT, NP). By priority: study 67 rows +Of the present rows: BIT 10, TOL 34, DEV 8, NOPIN 5, and two rows with their own code (EXACT, NP). By priority: study 67 rows (52 present, 15 partial or missing), useful 25, not planned 8. @@ -106,7 +106,7 @@ differ from raw SciPy where the CPU-dependent tie rule says so. | exSpy / HyperSpy | SpectroKit | state | code | priority | upstream tolerance (test file) | evidence | |---|---|---|---|---|---|---| | `EDSSpectrum.set_elements`, `add_elements` | element lists are plain input (`FitSettings.elements`, `QuantificationMethod.elements`, `ElementWindows.Pick`); no metadata tree | partial | PART | useful | no numeric test (`tests/signals/test_eds_sem.py::test_add_elements`, names only) | H and He are dropped where exSpy keeps them: SpectroEDXTests/SpectroscopyCoreTests `testHeliumAndHydrogenAreDroppedWhereExspyKeepsThem`; the bookkeeping itself is not compared | -| `EDSSpectrum.set_lines`, `add_lines` (`only_one`, `only_lines`) | `XRayLines.defaultLines` (package); the public `ElementWindows.build(picks:)` defaults to a different rule (`ElementWindows.defaultFamily`: K up to 20 keV, else L) | present | DEV | study | no numeric test (`test_eds_sem.py::test_add_lines`, names only) | `testDefaultLineChoiceMatchesExspy` (lists equal on 2 axes x 4 beam energies, for `defaultLines`); the deviation of the public default is named in `ElementWindows` | +| `EDSSpectrum.set_lines`, `add_lines` (`only_one`, `only_lines`) | `XRayLines.defaultLines`, public as `EDSWindowPath.lines(forElements:axis:beamEnergyKeV:onlyOne:onlyLines:)`; the public `ElementWindows.build(picks:)` defaults to a different rule (`ElementWindows.defaultFamily`: K up to 20 keV, else L) | present | DEV | study | no numeric test (`test_eds_sem.py::test_add_lines`, names only) | `testDefaultLineChoiceMatchesExspy` (lists equal on 2 axes x 4 beam energies, for `defaultLines`); SEMEDSParityTests on TM002 at 5, 10, 20 and 30 kV (exact, below); the deviation of the public default is named in `ElementWindows` | | `utils.eds.get_xray_lines` (`weight_threshold`, `energy_range`, `only_lines`) | `XRayLines.lines(of:)`, `.all`, `.linesInRange` | partial | PART | useful | `tests/misc/test_eds.py` (names, energies; exact) | `testDefaultLineChoiceMatchesExspy`, `testEmptyOnlyLinesIsNoFilter`; the weight and energy filters are not exposed | | `utils.eds.get_xray_lines_near_energy`, `print_lines_near_energy`, `print_lines`, `EDSSpectrum.print_lines*` | not in Sources: the rule is re-implemented inside the test over `XRayLines.all` | missing | NO | useful | `tests/misc/test_eds.py::test_xray_lines_near_energy` (exact line lists) | SpectroEDXTests/PeakGateTests `testP1LineLookupEqualsExSpy` (360 lookups equal) checks the table through that rule | | `material.elements` X-ray lines (Chantler energies, EPQ weights) | `XRayLines.all` (947 rows, Z 1...92), `XRayLines.line(_:)` | present | BIT | study | exact table; no tolerance (`tests/misc/test_eds_utils.py`) | SpectroEDXTests/LineTableParityTests `testEveryLineOfTheTableEqualsExSpy`: all 947 rows (Z, line, energy, weight, order) `==` exSpy's own loader (`tools/edx-lines/pins.py`); also SpectroEDXTests/SpectroscopyCoreTests `testLineTableIsExspyVerbatim` and SpectroEDXTests/PeakGateTests `testP1LineEnergyAndWidthEqualExSpy` | @@ -122,7 +122,7 @@ differ from raw SciPy where the CPU-dependent tie rule says so. | `get_lines_intensity` (net counts of integration windows less background windows) | `ElementWindows.build(picks:...)`, `ElementWindows.netCounts`, `.maps`, `.integratedMaps` (public); sigma added | present | BIT | study | `test_eds_tem.py::test_intensity` atol 1e-1; uint input rtol 0.03; `test_eds_sem.py::test_background_substraction` atol 1e-3 | FePt and TM002 net counts equal (`testFePtPins`, `testTM002Pins`, `==` on integer sums); WindowGateTests `testLineIntensitiesEqualExSpyOnEveryPlantedSpectrum` (26 280 values, 4e-16 relative). Two checked lines of one element closer than a window are clipped (`clipOverlaps`), which exSpy does not do | | `estimate_integration_windows` | `WindowIntensity.integrationWindows` (package), used by `ElementWindows.build` at width 2.0 | present | BIT | study | `test_eds_sem.py::test_estimate_integration_windows` atol 1e-2 | `testFePtPins`, `testTM002Pins` (windows `==`), WindowGateTests `testWindowsEqualExSpy` | | `estimate_background_windows` (with the merge of overlapping windows) | `BackgroundWindows.estimate`, `.merge` (package), used at `line_width` [2,2], `windows_width` 1 | present | BIT | study | `test_eds_sem.py::test_background_substraction` atol 1e-3 | `testFePtPins`, `testTM002Pins` (merged windows at [2,2] and [5,2]), `testMgAlSiMergedBackgroundSitsOnSiliconsFlank`, `testWindowsEqualExSpy` | -| the window parameters of the three rows above (`integration_window_factor`, `line_width`, `windows_width`, `xray_lines`) | not settable from the public API | partial | PART | study | as the three rows above | the package functions take them and are tested at [5,2] and at 2.1 FWHM (`testTM002Pins`) | +| the window parameters of the three rows above (`integration_window_factor`, `line_width`, `windows_width`, `xray_lines`) | `EDSWindowPath.integrationWindows(_:width:resolutionMnKaEV:)`, `.backgroundWindows(_:lineWidth:windowsWidth:resolutionMnKaEV:)`, `.intensities(counts:axis:integrationWindows:backgroundWindows:)` (public), over the package functions | present | TOL | study | as the three rows above | `testTM002Pins` at [5,2] and 2.1 FWHM; SEMEDSParityTests on the m7 TM002 bundles at [5,2], [2,2] and 2.1 FWHM (rtol 1e-7, below) | | `EDSSpectrum.sum` | `SpectrumImage.sum(mask:)`, `windowSums` (dense and sparse); exact UInt64; live time is passed through, not summed | present | NOPIN | study | `test_eds_tem.py::test_sum_live_time*` allclose defaults | CountsGateTests `testC1*`, `testC2*`, `testC3NoWrapAndNoLiveTimeProduct`: equal to a NumPy decode and planted draws; exSpy's `sum` was only probed (design note edx-stage-gates, archived in the suite's private folder, section 3, G-C) | | `EDSSpectrum.rebin` | none | missing | NO | study | `test_eds_tem.py::test_rebin_live_time`, `test_offset_after_rebin` (allclose defaults) | | | `LazyEDS*Spectrum` | none (a sparse store exists instead) | not planned | NP | not planned: lazy dask signals; the kit's sparse store is the lazy form | none | | @@ -237,6 +237,28 @@ differ from raw SciPy where the CPU-dependent tie rule says so. | `SEE`, `PESCoreLineShape`, `PESVoigt` | none | not planned | NP | not planned: photoelectron and secondary-electron components, not EELS | `test_pes_*.py` | | | `exspy.data` EELS datasets, `eelsdb` | none | not planned | NP | not planned: network database and bundled datasets | `tests/data/test_eelsdb.py` | | +## SEM-EDS (exspy's window path) + +The window path of one SEM spectrum as Electron Microscopy Studio ran it in its own `SEMEDSLines` until SpectroKit#131 merged it +here: `EDSWindowPath` (public) over the kit's own line table, windows, channel rule and Cliff-Lorimer, so there is one +implementation. References: the app's bundles `m7/eds-lines-tm002` (its figure F16) and `m7/eds-quant-tm002` (F17, with exspy's +element table as its `db_` arrays), written by the app's `tools/parity/sem/emit.py` (exspy 0.3.2, HyperSpy 2.5.0) on the BAM TM002 +spectrum and copied byte for byte with their input into `Tests/SpectroEDXTests/Fixtures/sem` (equal sha256); tests in +SpectroEDXTests/SEMEDSParityTests. The tolerances are the app's rows, unchanged. Line width: Fiori and Newbury 1978; k-factor ratio: +Cliff and Lorimer 1975. This table is not part of the seven-column count above; the rows it touches there are named in them. + +| Function | Reference | Test | Tolerance | Notes | +|---|---|---|---|---| +| `XRayLines.all`, `XRayLines.line(_:)`, `QuantElementData` | `exspy._misc.elements.elements` (the app's `XrayLineDatabase`) | `testTheAppsLineTableIsTheKits` | exact | all 947 lines (energy, weight, Z) and 95 elements (Z, atomic weight) equal; no line in one table that the other lacks; Li, Np, Pu and Am have no lines in either. The difference is in the choice, not the table: `lines(of:)` gives H and He no line (the DEVIATION in `XRayLines`) | +| `EDSWindowPath.lines(forElements:axis:beamEnergyKeV:)` | `EDSSpectrum._get_lines_from_elements` (`add_lines()`) | `testFigureF16…`, `testLinesFollowTheBeamEnergy…` | exact | Kα/Lα/Mα in range, the first below half the beam energy; an element without lines adds none (exspy raises); H and He add none where exspy adds `H_Ka`, `He_Ka` | +| `EDSWindowPath.linesInSpectralRange` | `_get_xray_lines_in_spectral_range` | `testRangeAndRefusals` | exact | strictly inside (axis low, min(axis high, beam)); the rest in order | +| `XRayLines.fwhm(resolutionMnKaEV:atEnergy:)` | `get_FWHM_at_Energy` | `testFigureF17…` | rtol 1e-7 | keV; nil (a thrown `SpectralLineError.widthUndefined` in the windows) where exspy's `math.sqrt` raises | +| `EDSWindowPath.integrationWindows`, `.backgroundWindows` | `estimate_integration_windows`, `estimate_background_windows` | `testFigureF16…`, `testDefaultBackgroundWindows…` | rtol 1e-7 | exspy's in-place merge of overlapping windows (`BackgroundWindows.merge`): with (5, 2) on TM002 every line takes C Kα's left window | +| `EnergyAxis.index(of:)`, `.channelRange(from:to:)` (package) | HyperSpy `UniformDataAxis.value2index`, `_get_array_slices` | `testChannelRoundingIsHyperSpys` | exact | the same rule as the app's: truncation at 1e-12 channels, half a channel towards zero at a non-negative energy and away from zero at a negative one; a NaN edge throws `notANumber` where the app's rule took it as off the axis | +| `EDSWindowPath.intensities` | `get_lines_intensity` | `testFigureF16…`, `testExspyDocstringIntensities` | rtol 1e-7 (measured bit-equal) | Double counts, the channels of `WindowIntensity.resolve`; equal to the kit's integer sums on TM002. A window off the axis throws where HyperSpy raises; a window narrower than one channel sums no channel, as exspy's slice does (the app refused it) | +| `EDSWindowPath.cliffLorimer(intensities:kFactors:singleLine:)`, `EDXQuantification.weightToAtomic` | `quantification_cliff_lorimer` (× 100), `material.weight_to_atomic` | `testFigureF17…`, `testCliffLorimerFloor…` | rtol 1e-7 | no absorption correction. Two named routes: `.exspyHundredPercent` is exspy's raw arithmetic, the one F17 pins (one line above the 0.1-count floor is 100 %, none gives zeros); `.refuse`, the kit's default everywhere (`EDXQuantification.quantify`), throws `needTwoLines` there. On TM002 both, and `EDXQuantification.quantify`, give F17's numbers | +| `EDSWindowPath.Conditions`, `.takeOffAngleDeg` | `get_take_off_angle` / `take_off_angle`, `EDSConfig` defaults | `testTM002Conditions…`, `testConditionsTakeExspysDefaults` | rtol 1e-7 | exspy's defaults (130 eV, 35°, 0°, 0°) for what a file leaves out; `EDXQuantification.takeOffAngle` keeps its own rule (every angle stated) | + ## Shared numerics (HyperSpy, SciPy, NumPy) that the rows above stand on | exSpy / HyperSpy | SpectroKit | state | code | priority | upstream tolerance (test file) | evidence | diff --git a/docs/status.md b/docs/status.md index d04063a..51f09f5 100644 --- a/docs/status.md +++ b/docs/status.md @@ -10,7 +10,10 @@ Live: escape peaks and, by default where the data support them, sum peaks; the continuum step at absorption edges broadened by the detector by default, an optional Si dead-layer term, the opt-in NIST EPQ line weights; Cliff-Lorimer, zeta and cross-section quantification with the absorption iteration, per pixel over a spectrum image, k-factor import, sigma on wt% and at% (with - take-off angle, thickness and dose terms) and per-pixel sigma maps, the per-region result. + take-off angle, thickness and dose terms) and per-pixel sigma maps, the per-region result; exSpy's window path for one SEM spectrum + (`EDSWindowPath`: the lines `add_lines()` picks at a beam energy, integration and background windows, line intensities, the + acquisition conditions with exSpy's defaults and their take-off angle, Cliff-Lorimer with the single-line rule named), on the app's + TM002 bundles. - **EELS**: t/lambda thickness, zero-loss alignment, power-law extrapolation, Fourier-log, Fourier-ratio and Richardson-Lucy deconvolution, the edge model fit (joint, or per-edge windows with a 1σ per edge intensity) on 383 bundled K, L and M edges, the MLLS fit, composition in at% and wt%, region sums. @@ -21,7 +24,7 @@ Since 0.16.0: 0.17.0 adds `countRows`, which hands out a spectrum image's counts power-law extrapolation past half the machine's memory before allocating it and takes FormatoKit and ImagoKit from the EMSuite org. What each version changed, with the migration notes: `CHANGELOG.md`. -Parity row by row: `docs/parity.md` (92 rows: 58 present, 11 partial, 23 missing); +Parity row by row: `docs/parity.md` (92 rows: 59 present, 10 partial, 23 missing); timings against Python: `docs/benchmarks.md`; what is open: the GitHub issues; known limits: `docs/parity.md`; fixtures and their generators: `Tests/Fixtures/README.md`. Tests: the fast targets run per change (`swift test -c release --parallel --skip SpectroKitParityTests`); the pinned Python comparisons From 9d2ea18019adda07b2e96f6277649fc96d483c85 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 18:39:12 +0000 Subject: [PATCH 4/4] docs: name eXSpy's NaN window and NaN resolution behaviour in the deviations Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VkKZEUynSt6RczY9oKhrDU --- Sources/SpectroEDX/EDSWindowPath.swift | 5 +++-- docs/parity.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Sources/SpectroEDX/EDSWindowPath.swift b/Sources/SpectroEDX/EDSWindowPath.swift index 5aae3d3..c4d105e 100644 --- a/Sources/SpectroEDX/EDSWindowPath.swift +++ b/Sources/SpectroEDX/EDSWindowPath.swift @@ -18,8 +18,9 @@ // (SEMEDSParityTests). // // DEVIATIONS from eXSpy (each the kit's, unchanged here): H and He get no line (`XRayLines.notRealLines`); a line whose width the -// Fiori-Newbury law cannot give throws `SpectralLineError.widthUndefined` where eXSpy's `math.sqrt` raises; a NaN window edge throws -// `EnergyAxisError.notANumber`. +// Fiori-Newbury law cannot give throws `SpectralLineError.widthUndefined`, where eXSpy's `math.sqrt` raises on a negative argument +// and gives NaN windows for a NaN resolution; a NaN window edge throws `WindowIntensityError.axis(.notANumber)`, where eXSpy 0.3.2 +// clamps a NaN integration edge to the axis end and raises only on a NaN background edge. // import Foundation diff --git a/docs/parity.md b/docs/parity.md index 724f0b6..12f1b36 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -254,7 +254,7 @@ Cliff and Lorimer 1975. This table is not part of the seven-column count above; | `EDSWindowPath.linesInSpectralRange` | `_get_xray_lines_in_spectral_range` | `testRangeAndRefusals` | exact | strictly inside (axis low, min(axis high, beam)); the rest in order | | `XRayLines.fwhm(resolutionMnKaEV:atEnergy:)` | `get_FWHM_at_Energy` | `testFigureF17…` | rtol 1e-7 | keV; nil (a thrown `SpectralLineError.widthUndefined` in the windows) where exspy's `math.sqrt` raises | | `EDSWindowPath.integrationWindows`, `.backgroundWindows` | `estimate_integration_windows`, `estimate_background_windows` | `testFigureF16…`, `testDefaultBackgroundWindows…` | rtol 1e-7 | exspy's in-place merge of overlapping windows (`BackgroundWindows.merge`): with (5, 2) on TM002 every line takes C Kα's left window | -| `EnergyAxis.index(of:)`, `.channelRange(from:to:)` (package) | HyperSpy `UniformDataAxis.value2index`, `_get_array_slices` | `testChannelRoundingIsHyperSpys` | exact | the same rule as the app's: truncation at 1e-12 channels, half a channel towards zero at a non-negative energy and away from zero at a negative one; a NaN edge throws `notANumber` where the app's rule took it as off the axis | +| `EnergyAxis.index(of:)`, `.channelRange(from:to:)` (package) | HyperSpy `UniformDataAxis.value2index`, `_get_array_slices` | `testChannelRoundingIsHyperSpys` | exact | the same rule as the app's: truncation at 1e-12 channels, half a channel towards zero at a non-negative energy and away from zero at a negative one; a NaN edge throws `notANumber` (wrapped as `WindowIntensityError.axis`), where the app's rule and eXSpy 0.3.2 clamp a NaN integration edge to the axis end (eXSpy raises on a NaN background edge) | | `EDSWindowPath.intensities` | `get_lines_intensity` | `testFigureF16…`, `testExspyDocstringIntensities` | rtol 1e-7 (measured bit-equal) | Double counts, the channels of `WindowIntensity.resolve`; equal to the kit's integer sums on TM002. A window off the axis throws where HyperSpy raises; a window narrower than one channel sums no channel, as exspy's slice does (the app refused it) | | `EDSWindowPath.cliffLorimer(intensities:kFactors:singleLine:)`, `EDXQuantification.weightToAtomic` | `quantification_cliff_lorimer` (× 100), `material.weight_to_atomic` | `testFigureF17…`, `testCliffLorimerFloor…` | rtol 1e-7 | no absorption correction. Two named routes: `.exspyHundredPercent` is exspy's raw arithmetic, the one F17 pins (one line above the 0.1-count floor is 100 %, none gives zeros); `.refuse`, the kit's default everywhere (`EDXQuantification.quantify`), throws `needTwoLines` there. On TM002 both, and `EDXQuantification.quantify`, give F17's numbers | | `EDSWindowPath.Conditions`, `.takeOffAngleDeg` | `get_take_off_angle` / `take_off_angle`, `EDSConfig` defaults | `testTM002Conditions…`, `testConditionsTakeExspysDefaults` | rtol 1e-7 | exspy's defaults (130 eV, 35°, 0°, 0°) for what a file leaves out; `EDXQuantification.takeOffAngle` keeps its own rule (every angle stated) |