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/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/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/Sources/SpectroEDX/EDSWindowPath.swift b/Sources/SpectroEDX/EDSWindowPath.swift new file mode 100644 index 0000000..c4d105e --- /dev/null +++ b/Sources/SpectroEDX/EDSWindowPath.swift @@ -0,0 +1,179 @@ +// +// 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 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 +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 { 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 0000000..724222e Binary files /dev/null and b/Tests/SpectroEDXTests/Fixtures/sem/fixtures/exspy_EDS_SEM_TM002.hspy differ diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/background_windows_keV.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/background_windows_keV.bin new file mode 100644 index 0000000..2ca5c7e --- /dev/null +++ b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/background_windows_keV.bin @@ -0,0 +1 @@ + Bƒ©à¥¿€Ž*@µÂ…?Ñ„»Ï›³@†Ë¦b@ Bƒ©à¥¿€Ž*@µÂ…?”œ M,è?oÀÉ!ê? Bƒ©à¥¿€Ž*@µÂ…?J!#ŸP<ú?¾©Òvû? Bƒ©à¥¿€Ž*@µÂ…?ÞRJ¥\ñ?÷mÂEmò? Bƒ©à¥¿€Ž*@µÂ…?Ñ„»Ï›³@†Ë¦b@ \ No newline at end of file diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/integration_windows_keV.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/integration_windows_keV.bin new file mode 100644 index 0000000..63a627f --- /dev/null +++ b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/integration_windows_keV.bin @@ -0,0 +1 @@ +î‡ræŽö?Ö˜=l‚ù?’Ž*'‚­Ì?³@_È+Õ?&ćUšë?Šo¤ ˜âï?1íSNâ?¹x[1“7æ?aaóUHPÿ?>И@ \ 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 0000000..7c95c40 Binary files /dev/null and b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/intensity_background_subtracted.bin differ 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 0000000..e1a9cf0 Binary files /dev/null and b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-lines-tm002/intensity_raw.bin differ 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 0000000..439c65a Binary files /dev/null and b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_atomic_weight.bin differ 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 0000000..969b89e Binary files /dev/null and b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_line_energy_keV.bin differ 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 0000000..b7e6777 Binary files /dev/null and b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_line_weight.bin differ diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_z.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_z.bin new file mode 100644 index 0000000..8e80489 Binary files /dev/null and b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/db_z.bin differ diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/intensity_background_default.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/intensity_background_default.bin new file mode 100644 index 0000000..aa0358a Binary files /dev/null and b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/intensity_background_default.bin differ diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/intensity_raw_width_2_1.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/intensity_raw_width_2_1.bin new file mode 100644 index 0000000..d7ea89a Binary files /dev/null and b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/intensity_raw_width_2_1.bin differ diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/line_fwhm_keV.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/line_fwhm_keV.bin new file mode 100644 index 0000000..d05e401 --- /dev/null +++ b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/line_fwhm_keV.bin @@ -0,0 +1,2 @@ +B‡X.㜳?©å'ÓVQ«?�±� +!±?±=rë¦K¯?¬Öhݦϵ? \ No newline at end of file diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/manifest.json b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/manifest.json new file mode 100644 index 0000000..1834b61 --- /dev/null +++ b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/manifest.json @@ -0,0 +1,1244 @@ +{ + "arrays": { + "atomic_percent_planted": { + "atol": 0.0, + "dtype": "float64", + "file": "atomic_percent_planted.bin", + "rtol": 1e-07, + "sha256": "9f6ad16762b05b8e5a8ac2311c82cf8d8be7319f763fb234000ff936ad49927f", + "shape": [ + 5 + ] + }, + "atomic_percent_unit": { + "atol": 0.0, + "dtype": "float64", + "file": "atomic_percent_unit.bin", + "rtol": 1e-07, + "sha256": "b16e6b279337aa36881d8cf7f9e186611e731340c1bba5b9d6df7ea7b311b40b", + "shape": [ + 5 + ] + }, + "background_windows_default_keV": { + "atol": 0.0, + "dtype": "float64", + "file": "background_windows_default_keV.bin", + "rtol": 1e-07, + "sha256": "32e6819994c19b45561f51b1f8602421777d6d9d7bcac7c4ca27058e94e71810", + "shape": [ + 5, + 4 + ] + }, + "db_atomic_weight": { + "atol": 0.0, + "dtype": "float64", + "file": "db_atomic_weight.bin", + "rtol": 0.0, + "sha256": "31b219d6aa80c75347ee65986d26d980832a62ad6b8cc6eefd12937d46b1bbc0", + "shape": [ + 95 + ] + }, + "db_line_energy_keV": { + "atol": 0.0, + "dtype": "float64", + "file": "db_line_energy_keV.bin", + "rtol": 0.0, + "sha256": "20c3f69f9a78d0750e92df6a53ff289a8f3df73f3a5a3348f7caeebd73921b67", + "shape": [ + 947 + ] + }, + "db_line_weight": { + "atol": 0.0, + "dtype": "float64", + "file": "db_line_weight.bin", + "rtol": 0.0, + "sha256": "ca33b9e0a4b0dd5862194acaf424cee20637c6bbe77a0eb9d2c30113d928fcd9", + "shape": [ + 947 + ] + }, + "db_z": { + "atol": 0.0, + "dtype": "int64", + "file": "db_z.bin", + "rtol": 0.0, + "sha256": "3b8ccdc8fbe3d5a09b462a299fa4a17db721ad3b9c4211fa6b5dbda15d5faad6", + "shape": [ + 95 + ] + }, + "intensity_background_default": { + "atol": 0.0, + "dtype": "float64", + "file": "intensity_background_default.bin", + "rtol": 1e-07, + "sha256": "b95194a2219ef9d8b822c02d6d841fe7d66e452f9bd155f054de69ba0786307e", + "shape": [ + 5 + ] + }, + "intensity_raw_width_2_1": { + "atol": 0.0, + "dtype": "float64", + "file": "intensity_raw_width_2_1.bin", + "rtol": 1e-07, + "sha256": "5d24940fcc353074d237b3a01a046eb3b9f81baa056028c859645c4bf5c64715", + "shape": [ + 5 + ] + }, + "line_fwhm_keV": { + "atol": 0.0, + "dtype": "float64", + "file": "line_fwhm_keV.bin", + "rtol": 1e-07, + "sha256": "738d71397903acfad554b667ece2251c0bc7d0d3257162a62d2023b386e8f1c0", + "shape": [ + 5 + ] + }, + "weight_percent_planted": { + "atol": 0.0, + "dtype": "float64", + "file": "weight_percent_planted.bin", + "rtol": 1e-07, + "sha256": "e29c757cda31a25d080b405313faab299b889d306153b339f44f0e122f719ab1", + "shape": [ + 5 + ] + }, + "weight_percent_unit": { + "atol": 0.0, + "dtype": "float64", + "file": "weight_percent_unit.bin", + "rtol": 1e-07, + "sha256": "2d38b00e811cb35a7145fcd4d8c361aa92f8548ae4a3074263dc98dc7f6a90b5", + "shape": [ + 5 + ] + } + }, + "case": "m7/eds-quant-tm002", + "inputs": [ + { + "path": "fixtures/exspy_EDS_SEM_TM002.hspy", + "sha256": "b5a5828dc694c7ed6e33745b7022594f48457e33140fb8d7371472fe18b6b359" + } + ], + "milestone": 7, + "reference": { + "function": "exspy._misc.eds.utils.quantification_cliff_lorimer", + "package": "exspy", + "version": "0.3.2" + }, + "scalars": { + "take_off_angle_deg": { + "atol": 0.0, + "rtol": 1e-07, + "value": 37.0 + } + }, + "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": { + "db_elements": [ + "Ru", + "Re", + "Ra", + "Rb", + "Rn", + "Rh", + "H", + "He", + "Be", + "Ba", + "Bi", + "Br", + "P", + "Os", + "Ge", + "Gd", + "Ga", + "Pr", + "Pt", + "C", + "Pb", + "Pa", + "Pd", + "Cd", + "Po", + "Pm", + "Ho", + "Hf", + "Hg", + "Mg", + "K", + "Mn", + "O", + "S", + "W", + "Zn", + "Eu", + "Zr", + "Er", + "Ni", + "Na", + "Nb", + "Nd", + "Ne", + "Fr", + "Fe", + "B", + "F", + "Sr", + "N", + "Kr", + "Si", + "Sn", + "Sm", + "V", + "Sc", + "Sb", + "Se", + "Co", + "Cl", + "Ca", + "Ce", + "Xe", + "Tm", + "Cs", + "Cr", + "Cu", + "La", + "Li", + "Tl", + "Lu", + "Th", + "Ti", + "Te", + "Tb", + "Tc", + "Ta", + "Yb", + "Dy", + "I", + "U", + "Y", + "Ac", + "Ag", + "Ir", + "Al", + "As", + "Ar", + "Au", + "At", + "In", + "Mo", + "Am", + "Np", + "Pu" + ], + "db_xray_lines": [ + "Ru_Lb1", + "Ru_Kb", + "Ru_Ka", + "Ru_Lb2", + "Ru_La", + "Ru_Ln", + "Ru_Ll", + "Ru_Lb3", + "Ru_Lg3", + "Ru_Lg1", + "Re_Lb1", + "Re_Kb", + "Re_Ka", + "Re_M2N4", + "Re_Ma", + "Re_Lb4", + "Re_La", + "Re_Ln", + "Re_M3O4", + "Re_Ll", + "Re_Mb", + "Re_Mg", + "Re_Lb2", + "Re_Lb3", + "Re_M3O5", + "Re_Lg3", + "Re_Lg1", + "Re_Mz", + "Ra_Lb1", + "Ra_Kb", + "Ra_Ka", + "Ra_M2N4", + "Ra_Lb4", + "Ra_La", + "Ra_Ln", + "Ra_Ll", + "Ra_Mb", + "Ra_Mg", + "Ra_Lb2", + "Ra_Lg3", + "Ra_Lg1", + "Ra_Lb3", + "Ra_Mz", + "Rb_Lb1", + "Rb_Kb", + "Rb_Ka", + "Rb_La", + "Rb_Ln", + "Rb_Ll", + "Rb_Lb3", + "Rb_Lg3", + "Rn_Lb1", + "Rn_Kb", + "Rn_Ka", + "Rn_M2N4", + "Rn_Lb4", + "Rn_La", + "Rn_Ln", + "Rn_Ll", + "Rn_Mb", + "Rn_Mg", + "Rn_Lb2", + "Rn_Lg3", + "Rn_Lg1", + "Rn_Lb3", + "Rn_Mz", + "Rh_Lb1", + "Rh_Kb", + "Rh_Ka", + "Rh_Lb2", + "Rh_Lb4", + "Rh_La", + "Rh_Ln", + "Rh_Ll", + "Rh_Lb3", + "Rh_Lg3", + "Rh_Lg1", + "H_Ka", + "He_Ka", + "Be_Ka", + "Ba_Lb1", + "Ba_Kb", + "Ba_Ka", + "Ba_Lb2", + "Ba_Lb4", + "Ba_La", + "Ba_Ln", + "Ba_Ll", + "Ba_Lb3", + "Ba_Lg3", + "Ba_Lg1", + "Bi_Lb1", + "Bi_Kb", + "Bi_Ka", + "Bi_M2N4", + "Bi_Ma", + "Bi_Lb4", + "Bi_La", + "Bi_Ln", + "Bi_M3O4", + "Bi_Ll", + "Bi_Mb", + "Bi_Mg", + "Bi_Lb2", + "Bi_Lb3", + "Bi_M3O5", + "Bi_Lg3", + "Bi_Lg1", + "Bi_Mz", + "Br_Lb1", + "Br_Kb", + "Br_Ka", + "Br_La", + "Br_Ln", + "Br_Ll", + "Br_Lb3", + "P_Kb", + "P_Ka", + "Os_Lb1", + "Os_Kb", + "Os_Ka", + "Os_M2N4", + "Os_Ma", + "Os_Lb4", + "Os_La", + "Os_Ln", + "Os_M3O4", + "Os_Ll", + "Os_Mb", + "Os_Mg", + "Os_Lb2", + "Os_Lb3", + "Os_M3O5", + "Os_Lg3", + "Os_Lg1", + "Os_Mz", + "Ge_Lb1", + "Ge_Kb", + "Ge_Ka", + "Ge_La", + "Ge_Ln", + "Ge_Ll", + "Ge_Lb3", + "Gd_Lb1", + "Gd_Kb", + "Gd_Ka", + "Gd_M2N4", + "Gd_Ma", + "Gd_Lb4", + "Gd_La", + "Gd_Ln", + "Gd_Ll", + "Gd_Mb", + "Gd_Mg", + "Gd_Lb2", + "Gd_Lb3", + "Gd_Lg3", + "Gd_Lg1", + "Gd_Mz", + "Ga_Lb1", + "Ga_Kb", + "Ga_Ka", + "Ga_La", + "Ga_Ln", + "Ga_Ll", + "Ga_Lb3", + "Pr_Lb1", + "Pr_Kb", + "Pr_Ka", + "Pr_M2N4", + "Pr_Ma", + "Pr_Lb4", + "Pr_La", + "Pr_Ln", + "Pr_Ll", + "Pr_Mb", + "Pr_Mg", + "Pr_Lb2", + "Pr_Lb3", + "Pr_Lg3", + "Pr_Lg1", + "Pr_Mz", + "Pt_Lb1", + "Pt_Kb", + "Pt_Ka", + "Pt_M2N4", + "Pt_Ma", + "Pt_Lb4", + "Pt_La", + "Pt_Ln", + "Pt_M3O4", + "Pt_Ll", + "Pt_Mb", + "Pt_Mg", + "Pt_Lb2", + "Pt_Lb3", + "Pt_M3O5", + "Pt_Lg3", + "Pt_Lg1", + "Pt_Mz", + "C_Ka", + "Pb_Lb1", + "Pb_Kb", + "Pb_Ka", + "Pb_M2N4", + "Pb_Ma", + "Pb_Lb4", + "Pb_La", + "Pb_Ln", + "Pb_M3O4", + "Pb_Ll", + "Pb_Mb", + "Pb_Mg", + "Pb_Lb2", + "Pb_Lb3", + "Pb_M3O5", + "Pb_Lg3", + "Pb_Lg1", + "Pb_Mz", + "Pa_Lb1", + "Pa_Kb", + "Pa_Ka", + "Pa_M2N4", + "Pa_Ma", + "Pa_Lb4", + "Pa_La", + "Pa_Ln", + "Pa_M3O4", + "Pa_Ll", + "Pa_Mb", + "Pa_Mg", + "Pa_Lb2", + "Pa_Lb3", + "Pa_M3O5", + "Pa_Lg3", + "Pa_Lg1", + "Pa_Mz", + "Pd_Lb1", + "Pd_Kb", + "Pd_Ka", + "Pd_Lb2", + "Pd_Lb4", + "Pd_La", + "Pd_Ln", + "Pd_Ll", + "Pd_Lb3", + "Pd_Lg3", + "Pd_Lg1", + "Cd_Lb1", + "Cd_Kb", + "Cd_Ka", + "Cd_Lb2", + "Cd_Lb4", + "Cd_La", + "Cd_Ln", + "Cd_Ll", + "Cd_Lb3", + "Cd_Lg3", + "Cd_Lg1", + "Po_Lb1", + "Po_Kb", + "Po_Ka", + "Po_M2N4", + "Po_Lb4", + "Po_La", + "Po_Ln", + "Po_Ll", + "Po_Mb", + "Po_Mg", + "Po_Lb2", + "Po_Lg3", + "Po_Lg1", + "Po_Lb3", + "Po_Mz", + "Pm_Lb1", + "Pm_Kb", + "Pm_Ka", + "Pm_M2N4", + "Pm_Ma", + "Pm_Lb4", + "Pm_La", + "Pm_Ln", + "Pm_Ll", + "Pm_Mb", + "Pm_Mg", + "Pm_Lb2", + "Pm_Lb3", + "Pm_Lg3", + "Pm_Lg1", + "Pm_Mz", + "Ho_Lb1", + "Ho_Kb", + "Ho_Ka", + "Ho_M2N4", + "Ho_Ma", + "Ho_Lb4", + "Ho_La", + "Ho_Ln", + "Ho_Ll", + "Ho_Mb", + "Ho_Mg", + "Ho_Lb2", + "Ho_Lb3", + "Ho_Lg3", + "Ho_Lg1", + "Ho_Mz", + "Hf_Lb1", + "Hf_Kb", + "Hf_Ka", + "Hf_M2N4", + "Hf_Ma", + "Hf_Lb4", + "Hf_La", + "Hf_Ln", + "Hf_Ll", + "Hf_Mb", + "Hf_Mg", + "Hf_Lb2", + "Hf_Lb3", + "Hf_Lg3", + "Hf_Lg1", + "Hf_Mz", + "Hg_Lb1", + "Hg_Kb", + "Hg_Ka", + "Hg_M2N4", + "Hg_Ma", + "Hg_Lb4", + "Hg_La", + "Hg_Ln", + "Hg_M3O4", + "Hg_Ll", + "Hg_Mb", + "Hg_Mg", + "Hg_Lb2", + "Hg_Lb3", + "Hg_M3O5", + "Hg_Lg3", + "Hg_Lg1", + "Hg_Mz", + "Mg_Kb", + "Mg_Ka", + "K_Kb", + "K_Ka", + "Mn_Kb", + "Mn_Ka", + "Mn_La", + "Mn_Ln", + "Mn_Ll", + "Mn_Lb3", + "O_Ka", + "S_Kb", + "S_Ka", + "W_Lb1", + "W_Kb", + "W_Ka", + "W_M2N4", + "W_Ma", + "W_Lb4", + "W_La", + "W_Ln", + "W_M3O4", + "W_Ll", + "W_Mb", + "W_Mg", + "W_Lb2", + "W_Lb3", + "W_M3O5", + "W_Lg3", + "W_Lg1", + "W_Mz", + "Zn_Lb1", + "Zn_Kb", + "Zn_Ka", + "Zn_La", + "Zn_Ln", + "Zn_Ll", + "Zn_Lb3", + "Eu_Lb1", + "Eu_Kb", + "Eu_Ka", + "Eu_M2N4", + "Eu_Ma", + "Eu_Lb4", + "Eu_La", + "Eu_Ln", + "Eu_Ll", + "Eu_Mb", + "Eu_Mg", + "Eu_Lb2", + "Eu_Lb3", + "Eu_Lg3", + "Eu_Lg1", + "Eu_Mz", + "Zr_Lb1", + "Zr_Kb", + "Zr_Ka", + "Zr_Lb2", + "Zr_La", + "Zr_Ln", + "Zr_Ll", + "Zr_Lb3", + "Zr_Lg3", + "Zr_Lg1", + "Er_Lb1", + "Er_Kb", + "Er_Ka", + "Er_M2N4", + "Er_Ma", + "Er_Lb4", + "Er_La", + "Er_Ln", + "Er_Ll", + "Er_Mb", + "Er_Mg", + "Er_Lb2", + "Er_Lb3", + "Er_Lg3", + "Er_Lg1", + "Er_Mz", + "Ni_Lb1", + "Ni_Kb", + "Ni_Ka", + "Ni_La", + "Ni_Ln", + "Ni_Ll", + "Ni_Lb3", + "Na_Kb", + "Na_Ka", + "Nb_Lb1", + "Nb_Kb", + "Nb_Ka", + "Nb_Lb2", + "Nb_La", + "Nb_Ln", + "Nb_Ll", + "Nb_Lb3", + "Nb_Lg3", + "Nb_Lg1", + "Nd_Lb1", + "Nd_Kb", + "Nd_Ka", + "Nd_M2N4", + "Nd_Ma", + "Nd_Lb4", + "Nd_La", + "Nd_Ln", + "Nd_Ll", + "Nd_Mb", + "Nd_Mg", + "Nd_Lb2", + "Nd_Lb3", + "Nd_Lg3", + "Nd_Lg1", + "Nd_Mz", + "Ne_Kb", + "Ne_Ka", + "Fr_Lb1", + "Fr_Kb", + "Fr_Ka", + "Fr_M2N4", + "Fr_Lb4", + "Fr_La", + "Fr_Ln", + "Fr_Ll", + "Fr_Mb", + "Fr_Mg", + "Fr_Lb2", + "Fr_Lg3", + "Fr_Lg1", + "Fr_Lb3", + "Fr_Mz", + "Fe_Kb", + "Fe_Ka", + "Fe_La", + "Fe_Ln", + "Fe_Ll", + "Fe_Lb3", + "B_Ka", + "F_Ka", + "Sr_Lb1", + "Sr_Kb", + "Sr_Ka", + "Sr_La", + "Sr_Ln", + "Sr_Ll", + "Sr_Lb3", + "Sr_Lg3", + "N_Ka", + "Kr_Lb1", + "Kr_Kb", + "Kr_Ka", + "Kr_La", + "Kr_Ln", + "Kr_Ll", + "Kr_Lb3", + "Kr_Lg3", + "Si_Kb", + "Si_Ka", + "Sn_Lb1", + "Sn_Kb", + "Sn_Ka", + "Sn_Lb2", + "Sn_Lb4", + "Sn_La", + "Sn_Ln", + "Sn_Ll", + "Sn_Lb3", + "Sn_Lg3", + "Sn_Lg1", + "Sm_Lb1", + "Sm_Kb", + "Sm_Ka", + "Sm_M2N4", + "Sm_Ma", + "Sm_Lb4", + "Sm_La", + "Sm_Ln", + "Sm_Ll", + "Sm_Mb", + "Sm_Mg", + "Sm_Lb2", + "Sm_Lb3", + "Sm_Lg3", + "Sm_Lg1", + "Sm_Mz", + "V_Kb", + "V_Ka", + "V_La", + "V_Ln", + "V_Ll", + "V_Lb3", + "Sc_Kb", + "Sc_Ka", + "Sc_La", + "Sc_Ln", + "Sc_Ll", + "Sc_Lb3", + "Sb_Lb1", + "Sb_Kb", + "Sb_Ka", + "Sb_Lb2", + "Sb_Lb4", + "Sb_La", + "Sb_Ln", + "Sb_Ll", + "Sb_Lb3", + "Sb_Lg3", + "Sb_Lg1", + "Se_Lb1", + "Se_Kb", + "Se_Ka", + "Se_La", + "Se_Ln", + "Se_Ll", + "Se_Lb3", + "Co_Kb", + "Co_Ka", + "Co_La", + "Co_Ln", + "Co_Ll", + "Co_Lb3", + "Cl_Kb", + "Cl_Ka", + "Ca_Ln", + "Ca_Kb", + "Ca_Ka", + "Ca_Ll", + "Ca_La", + "Ce_Lb1", + "Ce_Kb", + "Ce_Ka", + "Ce_M2N4", + "Ce_Ma", + "Ce_Lb4", + "Ce_La", + "Ce_Ln", + "Ce_Ll", + "Ce_Mb", + "Ce_Mg", + "Ce_Lb2", + "Ce_Lb3", + "Ce_Lg3", + "Ce_Lg1", + "Ce_Mz", + "Xe_Lb1", + "Xe_Kb", + "Xe_Ka", + "Xe_Lb2", + "Xe_Lb4", + "Xe_La", + "Xe_Ln", + "Xe_Ll", + "Xe_Lb3", + "Xe_Lg3", + "Xe_Lg1", + "Tm_Lb1", + "Tm_Kb", + "Tm_Ka", + "Tm_M2N4", + "Tm_Ma", + "Tm_Lb4", + "Tm_La", + "Tm_Ln", + "Tm_Ll", + "Tm_Mb", + "Tm_Mg", + "Tm_Lb2", + "Tm_Lb3", + "Tm_Lg3", + "Tm_Lg1", + "Tm_Mz", + "Cs_Lb1", + "Cs_Kb", + "Cs_Ka", + "Cs_Lb2", + "Cs_Lb4", + "Cs_La", + "Cs_Ln", + "Cs_Ll", + "Cs_Lb3", + "Cs_Lg3", + "Cs_Lg1", + "Cr_Kb", + "Cr_Ka", + "Cr_La", + "Cr_Ln", + "Cr_Ll", + "Cr_Lb3", + "Cu_Lb1", + "Cu_Kb", + "Cu_Ka", + "Cu_La", + "Cu_Ln", + "Cu_Ll", + "Cu_Lb3", + "La_Lb1", + "La_Kb", + "La_Ka", + "La_M2N4", + "La_Ma", + "La_Lb4", + "La_La", + "La_Ln", + "La_Ll", + "La_Mb", + "La_Mg", + "La_Lb2", + "La_Lb3", + "La_Lg3", + "La_Lg1", + "La_Mz", + "Tl_Lb1", + "Tl_Kb", + "Tl_Ka", + "Tl_M2N4", + "Tl_Ma", + "Tl_Lb4", + "Tl_La", + "Tl_Ln", + "Tl_M3O4", + "Tl_Ll", + "Tl_Mb", + "Tl_Mg", + "Tl_Lb2", + "Tl_Lb3", + "Tl_M3O5", + "Tl_Lg3", + "Tl_Lg1", + "Tl_Mz", + "Lu_Lb1", + "Lu_Kb", + "Lu_Ka", + "Lu_M2N4", + "Lu_Ma", + "Lu_Lb4", + "Lu_La", + "Lu_Ln", + "Lu_Ll", + "Lu_Mb", + "Lu_Mg", + "Lu_Lb2", + "Lu_Lb3", + "Lu_Lg3", + "Lu_Lg1", + "Lu_Mz", + "Th_Lb1", + "Th_Kb", + "Th_Ka", + "Th_M2N4", + "Th_Ma", + "Th_Lb4", + "Th_La", + "Th_Ln", + "Th_M3O4", + "Th_Ll", + "Th_Mb", + "Th_Mg", + "Th_Lb2", + "Th_Lb3", + "Th_M3O5", + "Th_Lg3", + "Th_Lg1", + "Th_Mz", + "Ti_Kb", + "Ti_Ka", + "Ti_La", + "Ti_Ln", + "Ti_Ll", + "Ti_Lb3", + "Te_Lb1", + "Te_Kb", + "Te_Ka", + "Te_Lb2", + "Te_Lb4", + "Te_La", + "Te_Ln", + "Te_Ll", + "Te_Lb3", + "Te_Lg3", + "Te_Lg1", + "Tb_Lb1", + "Tb_Kb", + "Tb_Ka", + "Tb_M2N4", + "Tb_Ma", + "Tb_Lb4", + "Tb_La", + "Tb_Ln", + "Tb_Ll", + "Tb_Mb", + "Tb_Mg", + "Tb_Lb2", + "Tb_Lb3", + "Tb_Lg3", + "Tb_Lg1", + "Tb_Mz", + "Tc_Lb1", + "Tc_Kb", + "Tc_Ka", + "Tc_Lb2", + "Tc_La", + "Tc_Ln", + "Tc_Ll", + "Tc_Lb3", + "Tc_Lg3", + "Tc_Lg1", + "Ta_Lb1", + "Ta_Kb", + "Ta_Ka", + "Ta_M2N4", + "Ta_Ma", + "Ta_Lb4", + "Ta_La", + "Ta_Ln", + "Ta_M3O4", + "Ta_Ll", + "Ta_Mb", + "Ta_Mg", + "Ta_Lb2", + "Ta_Lb3", + "Ta_M3O5", + "Ta_Lg3", + "Ta_Lg1", + "Ta_Mz", + "Yb_Lb1", + "Yb_Kb", + "Yb_Ka", + "Yb_M2N4", + "Yb_Ma", + "Yb_Lb4", + "Yb_La", + "Yb_Ln", + "Yb_Ll", + "Yb_Mb", + "Yb_Mg", + "Yb_Lb2", + "Yb_Lb3", + "Yb_Lg3", + "Yb_Lg1", + "Yb_Mz", + "Dy_Lb1", + "Dy_Kb", + "Dy_Ka", + "Dy_M2N4", + "Dy_Ma", + "Dy_Lb4", + "Dy_La", + "Dy_Ln", + "Dy_Ll", + "Dy_Mb", + "Dy_Mg", + "Dy_Lb2", + "Dy_Lb3", + "Dy_Lg3", + "Dy_Lg1", + "Dy_Mz", + "I_Lb1", + "I_Kb", + "I_Ka", + "I_Lb2", + "I_Lb4", + "I_La", + "I_Ln", + "I_Ll", + "I_Lb3", + "I_Lg3", + "I_Lg1", + "U_Lb1", + "U_Kb", + "U_Ka", + "U_M2N4", + "U_Ma", + "U_Lb4", + "U_La", + "U_Ln", + "U_M3O4", + "U_Ll", + "U_Mb", + "U_Mg", + "U_Lb2", + "U_Lb3", + "U_M3O5", + "U_Lg3", + "U_Lg1", + "U_Mz", + "Y_Lb1", + "Y_Kb", + "Y_Ka", + "Y_Lb2", + "Y_La", + "Y_Ln", + "Y_Ll", + "Y_Lb3", + "Y_Lg3", + "Y_Lg1", + "Ac_Lb1", + "Ac_Kb", + "Ac_Ka", + "Ac_M2N4", + "Ac_Ma", + "Ac_La", + "Ac_Ln", + "Ac_M3O4", + "Ac_Ll", + "Ac_Mb", + "Ac_Mg", + "Ac_M3O5", + "Ac_Lb2", + "Ac_Lg3", + "Ac_Lg1", + "Ac_Lb3", + "Ac_Mz", + "Ag_Lb1", + "Ag_Kb", + "Ag_Ka", + "Ag_Lb2", + "Ag_Lb4", + "Ag_La", + "Ag_Ln", + "Ag_Ll", + "Ag_Lb3", + "Ag_Lg3", + "Ag_Lg1", + "Ir_Lb1", + "Ir_Kb", + "Ir_Ka", + "Ir_M2N4", + "Ir_Ma", + "Ir_Lb4", + "Ir_La", + "Ir_Ln", + "Ir_M3O4", + "Ir_Ll", + "Ir_Mb", + "Ir_Mg", + "Ir_Lb2", + "Ir_Lb3", + "Ir_M3O5", + "Ir_Lg3", + "Ir_Lg1", + "Ir_Mz", + "Al_Kb", + "Al_Ka", + "As_Lb1", + "As_Kb", + "As_Ka", + "As_La", + "As_Ln", + "As_Ll", + "As_Lb3", + "Ar_Kb", + "Ar_Ka", + "Au_Lb1", + "Au_Kb", + "Au_Ka", + "Au_M2N4", + "Au_Ma", + "Au_Lb4", + "Au_La", + "Au_Ln", + "Au_M3O4", + "Au_Ll", + "Au_Mb", + "Au_Mg", + "Au_Lb2", + "Au_Lb3", + "Au_M3O5", + "Au_Lg3", + "Au_Lg1", + "Au_Mz", + "At_Lb1", + "At_Kb", + "At_Ka", + "At_M2N4", + "At_Lb4", + "At_La", + "At_Ln", + "At_Ll", + "At_Mb", + "At_Mg", + "At_Lb2", + "At_Lg3", + "At_Lg1", + "At_Lb3", + "At_Mz", + "In_Lb1", + "In_Kb", + "In_Ka", + "In_Lb2", + "In_Lb4", + "In_La", + "In_Ln", + "In_Ll", + "In_Lb3", + "In_Lg3", + "In_Lg1", + "Mo_Lb1", + "Mo_Kb", + "Mo_Ka", + "Mo_Lb2", + "Mo_La", + "Mo_Ln", + "Mo_Ll", + "Mo_Lb3", + "Mo_Lg3", + "Mo_Lg1" + ], + "kfactors_planted": [ + 1.0, + 2.5, + 1.5, + 1.25, + 2.0 + ], + "xray_lines": [ + "Al_Ka", + "C_Ka", + "Cu_La", + "Mn_La", + "Zr_La" + ], + "xray_lines_by_beam_energy": { + "20.0": [ + "Al_Ka", + "C_Ka", + "Cu_Ka", + "Mn_Ka", + "Zr_La" + ], + "30.0": [ + "Al_Ka", + "C_Ka", + "Cu_Ka", + "Mn_Ka", + "Zr_La" + ], + "5.0": [ + "Al_Ka", + "C_Ka", + "Cu_La", + "Mn_La", + "Zr_La" + ] + } + } +} diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/weight_percent_planted.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/weight_percent_planted.bin new file mode 100644 index 0000000..d332102 Binary files /dev/null and b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/weight_percent_planted.bin differ diff --git a/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/weight_percent_unit.bin b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/weight_percent_unit.bin new file mode 100644 index 0000000..2af7cb6 --- /dev/null +++ b/Tests/SpectroEDXTests/Fixtures/sem/references/m7/eds-quant-tm002/weight_percent_unit.bin @@ -0,0 +1 @@ +Ëo/«_1@„�·–šz3@8"þ“½5@v+Gi5@×_“�4@ \ No newline at end of file diff --git a/Tests/SpectroEDXTests/SEMEDSParityTests.swift b/Tests/SpectroEDXTests/SEMEDSParityTests.swift new file mode 100644 index 0000000..eb7c4d5 --- /dev/null +++ b/Tests/SpectroEDXTests/SEMEDSParityTests.swift @@ -0,0 +1,327 @@ +// +// SEMEDSParityTests.swift +// exspy's window path (`EDSWindowPath`, eXSpy 0.3.2's `get_lines_intensity`, `estimate_integration_windows`, +// `estimate_background_windows`, `quantification_cliff_lorimer` and `weight_to_atomic` on the kit's own line table, windows and channel +// rule) against the bundles of the app's tools/parity/sem on the BAM TM002 spectrum: `m7/eds-lines-tm002` (figure F16: the lines exspy +// picks, the integration and background windows, the raw and background-subtracted intensities), `m7/eds-quant-tm002` (figure F17: +// Cliff-Lorimer weight and atomic percent with unit and planted k-factors, the take-off angle, each line's FWHM, the default background +// windows, a 2.1-FWHM window, the lines at 5, 20 and 30 kV) with exspy's element table (its `db_` arrays, exact). Tolerances are the +// bundles' (the line table and the channel rule exact, float64 reductions rtol 1e-7, the app's docs/parity.md rows "SEM-EDS (exspy's +// window path)"). +// Moved from Electron Microscopy Studio's EMStudioTests/SEMEDSParityTests.swift (at e7212f9) by SpectroKit#131 with the two bundles and +// their input, byte for byte (Fixtures/sem); no number changed. The app read the spectrum through its HyperSpy door; here the hspy file +// is read with FormatoHDF5's plain HDF5 access (counts, axis, `Sample.elements`, the SEM conditions), and the app's own table +// (`XrayLineDatabase`) is checked through the bundle's `db_` arrays it was generated from. +// Red before the merge: no `EDSWindowPath`. Red after a change to the channel rounding, the window merge or the Cliff-Lorimer chain: +// the intensities move by whole channels' counts and the composition by percent. +// + +import CryptoKit +import Foundation +import FormatoCore +import FormatoHDF5 +import SpectroCore +import SpectroEDX +import XCTest + +nonisolated final class SEMEDSParityTests: XCTestCase { + + /// The TM002 spectrum as the hspy file stores it. + private struct Spectrum { + let counts: [Double] + let axis: EnergyAxis + let units: String + let elements: [String] + let conditions: EDSWindowPath.Conditions + } + + private struct Unreadable: Error, CustomStringConvertible { + let description: String + } + + private func tm002(_ ref: SEMParityReference) throws -> 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/docs/parity.md b/docs/parity.md index 3134f66..12f1b36 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` (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) | + ## 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 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", ""),