提交代码

This commit is contained in:
ldh
2026-11-19 16:42:26 +08:00
parent c5908eff03
commit 9d06abe41c
209 changed files with 158631 additions and 1311 deletions
@@ -0,0 +1,648 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CfLibs
{
public partial class CfLibsIdentifier
{
// --- 全局配置(对应 C++ 的 static 全局变量)---
private string _dataPath = ".";
private double _matchTol = 0.5;
private double _wavelengthCorr = 0.0; // 原代码未在 Identify 中使用
private int _gratingNo = 1;
private bool _enableGratingFix = true;
// --- 延迟加载的数据库 ---
private bool _dbLoaded = false;
private Dictionary<string, List<ElementLines>> _qualDb;
private SortedList<double, NistLine> _fullDb;
// --- 最近一次结果 ---
private List<SpecData> _lastSpec = new List<SpecData>();
private int _lastPeakCount = 0;
// --- 可选日志 ---
public Action<string> Log = null;
public int LastPeakCount => _lastPeakCount;
public IReadOnlyList<MatchedLine> LastMatchedLines
{
get
{
var list = new List<MatchedLine>(_lastSpec.Count);
foreach (var s in _lastSpec)
{
list.Add(new MatchedLine
{
Element = s.EleName,
WavelengthSource = s.WavelengthSource,
Wavelength = s.WaveLength,
Intensity = s.Intensity,
TransProb = s.TransPro,
UpperLevel = s.UpperLevel,
StatWeight = s.Statis,
Ionization = s.Ionization
});
}
return list;
}
}
// ---------- 配置接口 ----------
public void SetDataPath(string path) { _dataPath = string.IsNullOrEmpty(path) ? "." : path; }
public void SetMatchTolerance(double tol) { _matchTol = tol; }
public void SetWavelengthCorrection(double corr) { _wavelengthCorr = corr; }
public void SetGratingNo(int g) { _gratingNo = g; }
public void EnableGratingFix(bool enable) { _enableGratingFix = enable; }
private string GetPath(string f) => Path.Combine(_dataPath, f);
private void Print(string s) { Log?.Invoke(s); }
// =================================================================
// 定性分析主入口(对应 CF_LIBS_Identify)
// =================================================================
public int Identify(RawSpectrum spectrum, out SpectralLines outLines) =>
Identify(spectrum, null, out outLines);
/// <summary>
/// 定性分析,可指定段边界。边界索引表示下一段数据的起始位置,
/// 边界附近的点不参与寻峰,避免拼接光谱的接缝被识别成伪峰。
/// </summary>
public int Identify(
RawSpectrum spectrum,
IReadOnlyCollection<int>? segmentBoundaries,
out SpectralLines outLines)
{
outLines = null;
if (spectrum?.Points == null) return -1;
// 1. 延迟加载数据库
if (!_dbLoaded)
{
_qualDb = LoadElementDatabase(GetPath("element_lines.txt"));
_fullDb = LoadFullNistDb(GetPath("nist_full_lines.txt"));
_dbLoaded = true;
}
var spec = spectrum.Points;
// 2. 寻峰(拼接光谱的段边界处不参与寻峰)
var peaks = FindPeaks(spec, segmentBoundaries: segmentBoundaries);
_lastPeakCount = peaks.Count;
Print($"检测到 {peaks.Count} 个谱峰");
// 3. 定性粗匹配
var matches = MatchAgainstDatabase(peaks, _qualDb, _matchTol);
// ===== Step 1: 元素级粗过滤 =====
var detectedElems = new HashSet<string>();
var elemConfidence = new Dictionary<string, double>();
/*var rareElems = new HashSet<string>
{
"Pt","Ir","Au","Ag","Rh","Pd","Os","Ru","Bi","Ge","Sb","Te","Se","Ta",
"Hf","W","Mo","Tc","Sc","Y","Sr","Ba","In","Tl","Cs","La","Ce","Pr",
"Nd","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu","Ti","TiO",
"V","Co","Na","K"
};*/
var rareElems = new HashSet<string>
{
"Pt","Ir","Au","Ag","Rh","Pd","Os","Ru","Bi","Ge","Sb","Te","Se","Ta",
"Hf","W","Mo","Tc","Sc","Y","Sr","Ba","In","Tl","Cs","La","Ce","Pr",
"Nd","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu"
};
foreach (var m in matches)
{
double matchRate = m.TotalLines > 0 ? (double)m.MatchedLines / m.TotalLines : 0;
double intRatio = matchRate;
double combinedConf = matchRate * 0.7 + Math.Min(1.0, m.MatchedLines / 5.0) * 0.3;
if (combinedConf <= 0.55) continue;
if (m.MatchedLines >= 6 && intRatio <= 0.10) continue;
if (m.MatchedLines >= 7 && intRatio <= 0.08) continue;
if (combinedConf < 0.70 && m.MatchedLines < 5) continue;
bool isRare = rareElems.Contains(m.Element);
if (isRare && m.MatchedLines < 30) continue;
detectedElems.Add(m.Element);
if (!elemConfidence.ContainsKey(m.Element) || combinedConf > elemConfidence[m.Element])
elemConfidence[m.Element] = combinedConf;
}
Print($"粗过滤后元素数: {detectedElems.Count}");
// ===== Step 2: NIST 精确匹配(三层去重) =====
// --- 第一层:key = 元素 + NIST 库线波长,每条库线只匹配最强峰 ---
var bestMatch = new Dictionary<string, SpecData>();
var matchDist = new Dictionary<string, double>();
var fullKeys = _fullDb.Keys;
var fullVals = _fullDb.Values;
foreach (var p in peaks)
{
double tol = _matchTol;
int start = LowerBound(fullKeys, p.Wavelength - tol);
for (int idx = start; idx < fullKeys.Count; idx++)
{
double k = fullKeys[idx];
if (k > p.Wavelength + tol) break;
var nl = fullVals[idx];
if (!nl.HasFullParams) continue;
if (!detectedElems.Contains(nl.Element)) continue;
string key = nl.Element + nl.Wavelength.ToString("F6", CultureInfo.InvariantCulture);
double dist = Math.Abs(p.Wavelength - nl.Wavelength);
if (!bestMatch.TryGetValue(key, out var cur) || p.Intensity > cur.Intensity)
{
bestMatch[key] = new SpecData
{
EleName = nl.Element,
WavelengthSource = p.Wavelength, // 原始光谱中实际找到的峰位
WaveLength = nl.Wavelength, // 定性依据的谱线库(NIST)波长
Intensity = p.Intensity,
TransPro = nl.TransProb,
UpperLevel = nl.UpperLevel,
Statis = nl.StatWeight,
Ionization = nl.Ionization
};
matchDist[key] = dist;
}
}
}
// --- 第二层:同一峰 + 同一元素 + 同一电离态,只保留偏移最小者 ---
var dedupMap = new Dictionary<string, DedupEntry>();
foreach (var kv in bestMatch)
{
var sd = kv.Value;
double dist = matchDist[kv.Key];
string peakKey = $"{sd.EleName}_{sd.Ionization}_{sd.WavelengthSource.ToString("F3", CultureInfo.InvariantCulture)}";
if (!dedupMap.TryGetValue(peakKey, out var cur) || dist < cur.Dist)
dedupMap[peakKey] = new DedupEntry { Sd = sd, Dist = dist };
}
// --- 第三层:多元素竞争同一峰 ---
// 偏移差 < 0.02 nm 全部保留;否则按 评分 = dist / (1 + conf) 最小者胜出
var slTmp = new List<SpecData>();
var peakGroup = new Dictionary<double, List<DedupEntry>>();
foreach (var kv in dedupMap)
{
var sd = kv.Value.Sd;
if (!peakGroup.TryGetValue(sd.WavelengthSource, out var list))
{
list = new List<DedupEntry>();
peakGroup[sd.WavelengthSource] = list;
}
list.Add(kv.Value);
}
foreach (var g in peakGroup)
{
var cands = g.Value;
if (cands.Count == 1) { slTmp.Add(cands[0].Sd); continue; }
double bestScore = double.MaxValue;
int bestIdx = 0;
bool allClose = true;
double refDist = cands[0].Dist;
for (int k = 0; k < cands.Count; k++)
{
double d = cands[k].Dist;
double conf = elemConfidence.TryGetValue(cands[k].Sd.EleName, out var c) ? c : 0.0;
double score = d / (1.0 + conf);
if (Math.Abs(d - refDist) > 0.02) allClose = false;
if (score < bestScore) { bestScore = score; bestIdx = k; }
}
if (allClose) { foreach (var c in cands) slTmp.Add(c.Sd); }
else slTmp.Add(cands[bestIdx].Sd);
}
slTmp.Sort((a, b) => a.WaveLength.CompareTo(b.WaveLength)); // 按匹配到的库线波长排序
// ===== Step 2b: 元素级验证(通用 + 特异性规则) =====
{
var elemLineCount = new Dictionary<string, int>();
var elemAtomLineCount = new Dictionary<string, int>();
var elemMaxInt = new Dictionary<string, double>();
var elemTotalInt = new Dictionary<string, double>();
var elemLines = new Dictionary<string, List<SpecData>>();
double globalMaxInt = 0;
foreach (var s in slTmp)
{
Inc(elemLineCount, s.EleName);
if (!elemLines.TryGetValue(s.EleName, out var lst))
{
lst = new List<SpecData>();
elemLines[s.EleName] = lst;
}
lst.Add(s);
AddTo(elemTotalInt, s.EleName, s.Intensity);
if (s.Ionization == 0) Inc(elemAtomLineCount, s.EleName);
if (!elemMaxInt.TryGetValue(s.EleName, out var mx) || s.Intensity > mx)
elemMaxInt[s.EleName] = s.Intensity;
if (s.Intensity > globalMaxInt) globalMaxInt = s.Intensity;
}
var slClean = new List<SpecData>();
foreach (var s in slTmp)
{
string elem = s.EleName;
int nLines = elemLineCount[elem];
int nAtomLines = elemAtomLineCount.TryGetValue(elem, out var a) ? a : 0;
// 规则1:只有 1 条线 → 剔除;C 例外(> 全局 5% 保留)
if (nLines < 2)
{
if (elem == "C" && globalMaxInt > 0 &&
elemMaxInt.TryGetValue("C", out var cm) && cm > globalMaxInt * 0.05)
{
// 保留
}
else continue;
}
// 规则2:只有离子线 → 严格限定
if (nAtomLines == 0)
{
int nIonLines = nLines;
bool isTiOnly = (elem == "Ti");
if (!isTiOnly || nIonLines < 3) continue;
if (globalMaxInt > 0 && elemTotalInt[elem] < globalMaxInt * 0.02) continue;
}
// 规则3:只有 1 条原子线且强度 < 全局 3% → 剔除
if (nAtomLines == 1 && globalMaxInt > 0)
{
double atomMaxInt = 0;
foreach (var es in elemLines[elem])
if (es.Ionization == 0 && es.Intensity > atomMaxInt) atomMaxInt = es.Intensity;
if (atomMaxInt < globalMaxInt * 0.03) continue;
}
// 规则4:总强度 < 全局 2% → 剔除
if (globalMaxInt > 0 && elemTotalInt[elem] < globalMaxInt * 0.02) continue;
// 规则5:极罕见重金属要求 ≥4 条原子线;Be/Ga 要求 ≥2 条线
bool isVeryRareHeavy = elem == "Hg" || elem == "Cd" || elem == "Sb" || elem == "Zr";
if (isVeryRareHeavy && nAtomLines < 4) continue;
bool isTraceAlloy = elem == "Be" || elem == "Ga";
if (isTraceAlloy && nLines < 2) continue;
slClean.Add(s);
}
slTmp = slClean;
}
// ===== Step 3: 光栅修正 + 基线扣除(可选) =====
if (_enableGratingFix)
{
var fixLst = GetFixLst(_gratingNo);
if (fixLst.Count > 0)
{
var sortedInt = spec.Select(p => p.Intensity).OrderBy(x => x).ToList();
int noiseCount = Math.Max(1, Math.Min(sortedInt.Count, Math.Max(100, sortedInt.Count / 10)));
double baseline = 0;
for (int i = 0; i < noiseCount; i++) baseline += sortedInt[i];
baseline /= noiseCount;
FixIntensity(slTmp, fixLst, baseline);
}
}
_lastSpec = slTmp;
outLines = new SpectralLines
{
Lines = slTmp.Select(s => new MatchedLine
{
Element = s.EleName,
WavelengthSource = s.WavelengthSource,
Wavelength = s.WaveLength,
Intensity = s.Intensity,
TransProb = s.TransPro,
UpperLevel = s.UpperLevel,
StatWeight = s.Statis,
Ionization = s.Ionization
}).ToList()
};
return 0;
}
// =================================================================
// 寻峰
// =================================================================
private static List<DetectedPeak> FindPeaks(
IList<SpectrumPoint> spectrum,
double snrThreshold = 3.0,
IReadOnlyCollection<int>? segmentBoundaries = null)
{
var peaks = new List<DetectedPeak>();
int n = spectrum.Count;
if (n == 0) return peaks;
HashSet<int>? boundaries = segmentBoundaries is { Count: > 0 }
? new HashSet<int>(segmentBoundaries)
: null;
var sorted = spectrum.Select(p => p.Intensity).OrderBy(x => x).ToArray();
int noiseCount = Math.Max(1, Math.Min(n, Math.Max(100, n / 10)));
double mean = 0;
for (int i = 0; i < noiseCount; i++) mean += sorted[i];
mean /= noiseCount;
double variance = 0;
for (int i = 0; i < noiseCount; i++) variance += (sorted[i] - mean) * (sorted[i] - mean);
variance /= noiseCount;
double noiseStd = Math.Sqrt(variance);
if (noiseStd <= 1e-12) noiseStd = 1e-12;
double threshold = mean + snrThreshold * noiseStd;
for (int i = 1; i < n - 1; i++)
{
// 段边界附近(±2 个采样点)不生成峰,避免跨段比较
if (boundaries is not null && CrossesBoundary(boundaries, i))
{
continue;
}
double cur = spectrum[i].Intensity;
double left = spectrum[i - 1].Intensity;
double right = spectrum[i + 1].Intensity;
if (cur > left && cur >= right && cur > threshold)
{
const int window = 2;
bool isPeak = true;
for (int w = 1; w <= window && isPeak; w++)
{
if (i - w >= 0 && cur <= spectrum[i - w].Intensity) isPeak = false;
if (i + w < n && cur <= spectrum[i + w].Intensity) isPeak = false;
}
if (isPeak)
{
peaks.Add(new DetectedPeak
{
Wavelength = spectrum[i].Wavelength,
Intensity = cur,
Snr = (cur - mean) / noiseStd
});
}
}
}
return peaks;
}
private static bool CrossesBoundary(HashSet<int> boundaries, int index)
{
for (var offset = -2; offset <= 2; offset++)
{
if (boundaries.Contains(index + offset))
{
return true;
}
}
return false;
}
// =================================================================
// 粗匹配
// =================================================================
private static List<MatchResult> MatchAgainstDatabase(
IList<DetectedPeak> peaks,
Dictionary<string, List<ElementLines>> db,
double tolerance)
{
var dbUsed = new Dictionary<string, HashSet<double>>();
var resultMap = new Dictionary<string, MatchResult>();
foreach (var peak in peaks)
{
double wl = peak.Wavelength;
double bestWlDiff = tolerance;
string bestElement = null;
int bestIon = 0;
double bestDbWl = 0;
foreach (var kv in db)
{
foreach (var el in kv.Value)
{
string key = el.Element + (el.Ionization == 0 ? "I" : "II");
dbUsed.TryGetValue(key, out var used);
foreach (double dbWl in el.Wavelengths)
{
if (used != null && used.Contains(dbWl)) continue;
double diff = Math.Abs(wl - dbWl);
if (diff <= bestWlDiff)
{
bestWlDiff = diff;
bestElement = kv.Key;
bestIon = el.Ionization;
bestDbWl = dbWl;
}
}
}
}
if (!string.IsNullOrEmpty(bestElement))
{
string key = bestElement + (bestIon == 0 ? "I" : "II");
if (!dbUsed.TryGetValue(key, out var set))
{
set = new HashSet<double>();
dbUsed[key] = set;
}
set.Add(bestDbWl);
if (!resultMap.TryGetValue(key, out var mr))
{
mr = new MatchResult { Element = bestElement, Ionization = bestIon };
resultMap[key] = mr;
}
mr.MatchedLines++;
mr.MatchedWavelengths.Add(wl);
}
}
foreach (var kv in resultMap)
{
var mr = kv.Value;
if (db.TryGetValue(mr.Element, out var elList))
foreach (var el in elList)
if (el.Ionization == mr.Ionization) mr.TotalLines += el.Wavelengths.Count;
double matchRate = mr.TotalLines > 0
? Math.Min(1.0, (double)mr.MatchedLines / mr.TotalLines) : 0;
mr.Confidence = matchRate * 0.7 + Math.Min(1.0, mr.MatchedLines / 5.0) * 0.3;
if (mr.Confidence > 1.0) mr.Confidence = 1.0;
}
return resultMap.Values.OrderByDescending(r => r.Confidence).ToList();
}
// =================================================================
// 数据库加载
// =================================================================
private static Dictionary<string, List<ElementLines>> LoadElementDatabase(string filename)
{
var db = new Dictionary<string, List<ElementLines>>();
if (!File.Exists(filename))
{
Console.Error.WriteLine($"错误:无法打开谱线数据库文件 {filename}");
return db;
}
foreach (var raw in File.ReadLines(filename))
{
var line = raw.Trim();
if (line.Length == 0 || line[0] == '#') continue;
var parts = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 3) continue;
string element = parts[0];
string ionStr = parts[1];
int ionization = (ionStr == "II") ? 1 : 0;
var el = new ElementLines { Element = element, Ionization = ionization };
for (int i = 2; i < parts.Length; i++)
if (double.TryParse(parts[i], NumberStyles.Float, CultureInfo.InvariantCulture, out var w))
el.Wavelengths.Add(w);
if (el.Wavelengths.Count == 0) continue;
if (!db.TryGetValue(element, out var list))
{
list = new List<ElementLines>();
db[element] = list;
}
list.Add(el);
}
return db;
}
private static SortedList<double, NistLine> LoadFullNistDb(string filename)
{
var db = new SortedList<double, NistLine>();
if (!File.Exists(filename))
{
Console.Error.WriteLine($"错误:无法打开完整谱线库 {filename}");
return db;
}
foreach (var raw in File.ReadLines(filename))
{
var line = raw.Trim();
if (line.Length == 0 || line[0] == '#') continue;
var parts = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 7) continue;
try
{
var nl = new NistLine
{
Element = parts[0],
Wavelength = double.Parse(parts[1], CultureInfo.InvariantCulture),
Intensity = double.Parse(parts[2], CultureInfo.InvariantCulture),
TransProb = double.Parse(parts[3], CultureInfo.InvariantCulture),
UpperLevel = double.Parse(parts[4], CultureInfo.InvariantCulture),
StatWeight = double.Parse(parts[5], CultureInfo.InvariantCulture),
Ionization = int.Parse(parts[6], CultureInfo.InvariantCulture)
};
// 与 C++ 相同的数据库质量过滤
bool paramOk = nl.TransProb > 0 && nl.UpperLevel > 0 && nl.StatWeight > 0;
bool akiOk = nl.TransProb >= 1.0e7;
bool ekOk = nl.Ionization == 0 ? nl.UpperLevel <= 8.0 : nl.UpperLevel <= 10.0;
bool ionOk = nl.Ionization == 0 || nl.Ionization == 1;
nl.HasFullParams = paramOk && akiOk && ekOk && ionOk;
db[nl.Wavelength] = nl;
}
catch { /* 跳过坏行 */ }
}
return db;
}
// =================================================================
// 光栅修正
// =================================================================
private List<FixData> GetFixLst(int gratingNo)
{
string file = null;
switch (gratingNo)
{
case 1: file = GetPath("600c"); break;
case 2: file = GetPath("1200c"); break;
case 3: file = GetPath("2400c"); break;
default: break; // file 保持 null
}
var list = new List<FixData>();
if (file == null || !File.Exists(file)) return list;
foreach (var raw in File.ReadLines(file))
{
var parts = raw.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) continue;
if (double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var w) &&
double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var f))
list.Add(new FixData { Wavelength = w, Fix = f });
}
return list;
}
private static void FixIntensity(List<SpecData> list, List<FixData> fixLst, double baseline)
{
foreach (var item in list)
{
double v = item.Intensity - baseline;
item.Intensity = v < 0 ? 0 : v;
}
if (fixLst.Count == 0) return;
foreach (var item in list)
{
int ng = 0;
double best = double.MaxValue;
for (int j = 0; j < fixLst.Count; j++)
{
double d = Math.Abs(fixLst[j].Wavelength - item.WavelengthSource); // 按原始峰位匹配光栅曲线
if (d <= best) { best = d; ng = j; }
}
double fix = fixLst[ng].Fix;
if (fix > 1e-9) item.Intensity /= fix;
}
}
// =================================================================
// 工具函数
// =================================================================
private static int LowerBound(IList<double> keys, double key)
{
int lo = 0, hi = keys.Count;
while (lo < hi)
{
int mid = (lo + hi) >> 1;
if (keys[mid] < key) lo = mid + 1;
else hi = mid;
}
return lo;
}
private static void Inc(Dictionary<string, int> d, string k)
=> d[k] = d.TryGetValue(k, out var v) ? v + 1 : 1;
private static void AddTo(Dictionary<string, double> d, string k, double v)
=> d[k] = d.TryGetValue(k, out var cur) ? cur + v : v;
}
}