Files
SpectraElement/HardwareControl.Core/Scanning/SpectrumAnalysisService.cs
T
2026-11-19 16:42:26 +08:00

258 lines
9.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using CfLibs;
using HardwareControl.Core.Spectrometer;
using Microsoft.Extensions.Logging;
namespace HardwareControl.Core.Scanning
{
/// <summary>单个采样点的 NIST 定性/定量分析结果。</summary>
public sealed record PointAnalysisResult(
IReadOnlyList<ScanElementRecord> Elements,
double Temperature,
double ElectronDensity,
string? Error);
/// <summary>
/// NIST 谱线库分析封装:每个采样点独立执行 Identify(定性)+ Quantify(定量)。
/// 拼接光谱的段边界处不参与寻峰,避免接缝被识别成伪峰。
/// </summary>
public sealed class SpectrumAnalysisService
{
private readonly CfLibsIdentifier _identifier;
private readonly ILogger<SpectrumAnalysisService> _logger;
private readonly object _gate = new();
private readonly bool _dataReady;
public SpectrumAnalysisService(
string? dataPath,
ILogger<SpectrumAnalysisService> logger)
{
_logger = logger;
var path = string.IsNullOrWhiteSpace(dataPath)
? Path.Combine(AppContext.BaseDirectory, "db")
: dataPath;
_identifier = new CfLibsIdentifier();
_identifier.SetDataPath(path);
// 光栅修正使用 600c(gratingNo = 1)
_identifier.SetGratingNo(1);
_identifier.SetMatchTolerance(0.5);
_identifier.EnableGratingFix(true);
_identifier.Log = message => _logger.LogDebug("CfLibs: {Message}", message);
_dataReady =
File.Exists(Path.Combine(path, "element_lines.txt")) &&
File.Exists(Path.Combine(path, "nist_full_lines.txt"));
if (_dataReady)
{
_logger.LogInformation("NIST 谱线库目录:{Path}", path);
}
else
{
_logger.LogError(
"NIST 谱线库不完整,扫描结果将无法分析。请确认 {Path} 下存在 element_lines.txt 与 nist_full_lines.txt",
path);
}
}
public PointAnalysisResult Analyze(
float[] wavelengths,
float[] spectrum,
IReadOnlyList<ScanSegmentRecord> segments)
{
if (!_dataReady)
{
return new PointAnalysisResult(
Array.Empty<ScanElementRecord>(),
0,
0,
"NIST 谱线库文件缺失,无法分析元素");
}
if (wavelengths.Length == 0 || wavelengths.Length != spectrum.Length)
{
return new PointAnalysisResult(
Array.Empty<ScanElementRecord>(),
0,
0,
"光谱数据为空或波长/强度长度不一致");
}
var raw = new RawSpectrum();
raw.Points.Capacity = wavelengths.Length;
for (var i = 0; i < wavelengths.Length; i++)
{
raw.Points.Add(new SpectrumPoint
{
Wavelength = wavelengths[i],
Intensity = spectrum[i],
});
}
var boundaries = BuildBoundaries(segments, wavelengths.Length);
lock (_gate)
{
try
{
var identify = _identifier.Identify(raw, boundaries, out var lines);
if (identify != 0 || lines is null)
{
return new PointAnalysisResult(
Array.Empty<ScanElementRecord>(),
0,
0,
"NIST 定性分析失败");
}
if (lines.Lines.Count == 0)
{
// 没有匹配到有效谱线不算异常,结果页显示“未检出元素”。
return new PointAnalysisResult(
Array.Empty<ScanElementRecord>(),
0,
0,
null);
}
var quantified = _identifier.Quantify(lines, out var result) == 0
? result
: null;
return BuildResult(lines, quantified);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "NIST 分析失败");
return new PointAnalysisResult(
Array.Empty<ScanElementRecord>(),
0,
0,
$"NIST 分析失败:{ex.Message}");
}
}
}
private static PointAnalysisResult BuildResult(
SpectralLines lines,
Result? quantified)
{
var groups = lines.Lines
.GroupBy(line => line.Element, StringComparer.OrdinalIgnoreCase)
.ToDictionary(
group => group.Key,
group => group.ToList(),
StringComparer.OrdinalIgnoreCase);
var abundances = new Dictionary<string, ElementResult>(StringComparer.OrdinalIgnoreCase);
if (quantified?.Elements is not null)
{
foreach (var element in quantified.Elements)
{
if (!string.IsNullOrWhiteSpace(element.Element))
{
abundances[element.Element] = element;
}
}
}
var globalMaxIntensity = groups.Values
.SelectMany(list => list)
.Select(line => line.Intensity)
.DefaultIfEmpty(0)
.Max();
var elements = new List<ScanElementRecord>(groups.Count + abundances.Count);
foreach (var (symbol, matched) in groups)
{
var strongest = matched
.OrderByDescending(line => line.Intensity)
.First();
abundances.TryGetValue(symbol, out var quantifiedElement);
var abundance = quantifiedElement?.Abundance ?? 0;
var ratio = globalMaxIntensity <= 0
? 0
: strongest.Intensity / globalMaxIntensity;
elements.Add(new ScanElementRecord
{
Symbol = symbol,
Name = ElementNames.GetChineseName(symbol),
IntensityLevel = ratio >= 0.6 ? "高" : ratio >= 0.2 ? "中" : "低",
Abundance = abundance,
RawAbundance = quantifiedElement?.RawAbundance ?? 0,
// 含量 ≥ 0.5% 记为检出,其余记为痕量(与界面示例一致)。
Verdict = abundance >= 0.5 ? "检出" : "痕量",
MaxIntensity = strongest.Intensity,
MatchedWavelength = strongest.WavelengthSource,
MatchedLines = matched.Count,
});
}
// 定量结果中存在、但没有进入匹配谱线列表的元素(正常不会出现)也一并返回。
foreach (var (symbol, element) in abundances)
{
if (groups.ContainsKey(symbol))
{
continue;
}
elements.Add(new ScanElementRecord
{
Symbol = symbol,
Name = ElementNames.GetChineseName(symbol),
IntensityLevel = "低",
Abundance = element.Abundance,
RawAbundance = element.RawAbundance,
Verdict = element.Abundance >= 0.5 ? "检出" : "痕量",
MaxIntensity = 0,
MatchedWavelength = 0,
MatchedLines = 0,
});
}
elements.Sort((left, right) =>
{
var byAbundance = right.Abundance.CompareTo(left.Abundance);
return byAbundance != 0
? byAbundance
: right.MaxIntensity.CompareTo(left.MaxIntensity);
});
return new PointAnalysisResult(
elements,
quantified?.Temperature ?? 0,
quantified?.ElectronDensity ?? 0,
null);
}
/// <summary>把拼接光谱的段长度换算成寻峰时要跳过的边界索引。</summary>
private static int[] BuildBoundaries(
IReadOnlyList<ScanSegmentRecord> segments,
int pointCount)
{
if (segments.Count <= 1)
{
return Array.Empty<int>();
}
var boundaries = new List<int>(segments.Count - 1);
var offset = 0;
for (var i = 0; i < segments.Count - 1; i++)
{
offset += segments[i].PointCount;
if (offset > 0 && offset < pointCount)
{
boundaries.Add(offset);
}
}
return boundaries.Distinct().ToArray();
}
}
}