提交代码

This commit is contained in:
ldh
2026-11-19 16:42:26 +08:00
parent dd6edce089
commit 4929d5dcd5
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;
}
}
@@ -0,0 +1,416 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CfLibs
{
public partial class CfLibsIdentifier
{
// ===== 定量专用字段(与 C++ 全局变量 temprature / electroD / g_lastRsq 对应)=====
private double _temperature; // 全局等离子体温度 K
private double _electronDensity; // 全局电子密度 cm^-3
private double _lastRsq; // 最近一次 Boltzmann 拟合 R²
private double _forcedTemperature; // 强制温度(SetTemperature 用,0=自动)
private bool _enableCalibration; // 标样校正开关
private List<ElementData> _lastElem = new List<ElementData>();
// 懒加载缓存:避免每次定量都开文件
private Dictionary<string, double> _ionizationEnergies;
private Dictionary<string, double> _atomicWeights;
// ===== 对外只读属性 =====
public double Temperature => _temperature;
public double ElectronDensity => _electronDensity;
// 定量结果(对外的 MatchedLine 列表形式)
public IReadOnlyList<ElementResult> LastElements
{
get
{
var list = new List<ElementResult>(_lastElem.Count);
foreach (var e in _lastElem)
{
list.Add(new ElementResult
{
Element = e.EleName,
Abundance = e.Abundence,
RawAbundance = e.RawAbundence,
AbundanceAtom = 0,
Csa = e.Csa,
Csit = e.Csit,
Temperature = _temperature,
ElectronDensity = _electronDensity
});
}
return list;
}
}
// ===== 配置 =====
public void EnableCalibration(bool enable) => _enableCalibration = enable;
/// <summary>强制设置温度 K,0 = 使用自动计算</summary>
public void SetTemperature(double t) => _forcedTemperature = t;
// =================================================================
// Quantify 主入口(对应 CF_LIBS_Quantify)
// =================================================================
public int Quantify(SpectralLines lines, out Result outResult)
{
outResult = null;
if (lines?.Lines == null) return -1;
// 1. 对外结构 → 内部 SpecData
var spec = new List<SpecData>(lines.Lines.Count);
foreach (var l in lines.Lines)
{
spec.Add(new SpecData
{
EleName = l.Element,
WavelengthSource = l.WavelengthSource,
WaveLength = l.Wavelength,
Intensity = l.Intensity,
TransPro = l.TransProb,
UpperLevel = l.UpperLevel,
Statis = l.StatWeight,
Ionization = l.Ionization
});
}
if (spec.Count == 0) return -1;
// 2. 三步核心计算
var nameList = SpecNameLst(spec);
AverageTemperElect(spec, nameList);
var elem = CalculateConcentration(spec, nameList);
// 3. 低浓度过滤:<0.01% 归零
foreach (var e in elem)
if (e.Abundence < 0.01) e.Abundence = 0.0;
// 4. 输出
outResult = new Result
{
Status = 0,
ErrorMsg = "",
Temperature = _temperature,
ElectronDensity = _electronDensity,
Elements = new List<ElementResult>(elem.Count)
};
foreach (var e in elem)
{
outResult.Elements.Add(new ElementResult
{
Element = e.EleName,
Abundance = e.Abundence,
RawAbundance = e.RawAbundence,
AbundanceAtom = 0,
Csa = e.Csa,
Csit = e.Csit,
Temperature = _temperature,
ElectronDensity = _electronDensity
});
}
_lastElem = elem;
return 0;
}
// =================================================================
// specNameLst
// =================================================================
private static List<ElementCount> SpecNameLst(List<SpecData> specLst)
{
// 用 SortedDictionary 保证迭代顺序与 C++ std::map 一致
var count = new SortedDictionary<string, int>();
foreach (var s in specLst)
{
count.TryGetValue(s.EleName, out var c);
count[s.EleName] = c + 1;
}
var list = new List<ElementCount>(count.Count);
foreach (var kv in count)
list.Add(new ElementCount { EleName = kv.Key, Count = kv.Value });
return list;
}
// =================================================================
// averageTemperElect
// =================================================================
private void AverageTemperElect(List<SpecData> specLst, List<ElementCount> specName)
{
// ===== P0 优化:收集每个元素的 (T, R², 有效线数),R²·n 加权平均 =====
var elemTemps = new List<(double T, double R2, int N)>();
// count1 与 C++ 一致:每处理完一个元素重置为 0
int count1 = 0;
const int casee = 1;
var spect = new List<SpecData>();
foreach (var item in specName)
{
if (item.Count < 2) continue;
spect.Clear();
for (int j = 0; j < item.Count; j++)
{
while (true)
{
if (count1 >= specLst.Count) break; // 防御:C++ 里没有但加安全
if (specLst[count1].EleName == item.EleName)
{
spect.Add(specLst[count1]);
count1++;
break;
}
count1++;
}
}
CalculateElementTempne(spect, item, casee);
// _temperature / _lastRsq 已由 CalculateElementTempne 更新
double rsqNow = _lastRsq;
double tempNow = _temperature;
// 统一有效性判定:R² ≥ 0.3,温度 ∈ [3000, 25000]K
if (rsqNow >= 0.3 && tempNow >= 3000 && tempNow <= 25000)
{
elemTemps.Add((tempNow, rsqNow, item.Count));
}
count1 = 0;
}
if (elemTemps.Count == 0)
{
_temperature = 10000.0;
_electronDensity = 1.0e17;
return;
}
// ===== R² · n 加权平均(取代旧的等权 + Al 50/50 折中)=====
double sumW = 0, sumWT = 0;
foreach (var (T, R2, N) in elemTemps)
{
// 权重 = R² 贡献 + 有效谱线数贡献
double w = Math.Max(0.0, R2) * Math.Max(1, N);
sumW += w;
sumWT += w * T;
}
_temperature = sumW > 1e-12 ? sumWT / sumW : 10000.0;
// 简化 Saha:Ne ≈ 1e17·(T/1e4)^1.5
_electronDensity = 1.0e17 * Math.Pow(_temperature / 10000.0, 1.5);
// 物理范围钳位(从 [8500, 12000] 放宽到 [5000, 20000])
if (_temperature > 20000.0) _temperature = 20000.0;
if (_temperature < 5000.0) _temperature = 5000.0;
if (_electronDensity > 5.0e17) _electronDensity = 5.0e17;
if (_electronDensity < 1.0e16) _electronDensity = 1.0e16;
// 物理范围钳位
if (_temperature > 20000.0) _temperature = 20000.0;
if (_temperature < 5000.0) _temperature = 5000.0;
if (_electronDensity > 1.0e19) _electronDensity = 1.0e19;
if (_electronDensity < 1.0e15) _electronDensity = 1.0e15;
// 强制温度覆盖(若启用)
if (_forcedTemperature > 0)
{
_temperature = _forcedTemperature;
_electronDensity = 1.0e17 * Math.Pow(_temperature / 10000.0, 1.5);
}
}
// =================================================================
// calculateElementTempne — 单元素 Boltzmann 拟合 + Saha Ne
// =================================================================
private void CalculateElementTempne(List<SpecData> fixedLst, ElementCount specName, int casee)
{
const double Kb = 8.61738573e-5;
// 分原子线 / 离子线
var atomLines = new List<SpecData>();
var ionLines = new List<SpecData>();
foreach (var ln in fixedLst)
{
if (ln.Ionization == 0) atomLines.Add(ln);
else if (ln.Ionization == 1) ionLines.Add(ln);
}
// 读取电离能
double EiIon = 0.0;
var eis = LoadIonizationEnergies();
if (eis.TryGetValue(specName.EleName, out var eiVal)) EiIon = eiVal;
FitBoltzmann(atomLines, out double T_a, out double bsa_fit, out double R2_a, out int n_a, out double ekRa);
FitBoltzmann(ionLines, out double T_i, out double bsi_fit, out double R2_i, out int n_i, out double ekRi);
// 决策
const double minEkRange_a = 1.5;
const double minEkRange_i = 2.0;
const int minLines_a = 3;
const int minLines_i = 4;
bool ok_a = T_a > 5000 && T_a < 20000 && R2_a > 0.5 && ekRa >= minEkRange_a && n_a >= minLines_a;
bool ok_i = T_i > 5000 && T_i < 20000 && R2_i > 0.5 && ekRi >= minEkRange_i && n_i >= minLines_i;
double weight_a = ok_a ? R2_a * n_a * (ekRa + 0.1) : 0;
double weight_i = ok_i ? R2_i * n_i * (ekRi + 0.1) : 0;
double T_final, R2_final;
if (ok_a && ok_i)
{
T_final = (weight_a * T_a + weight_i * T_i) / (weight_a + weight_i);
R2_final = (weight_a * R2_a + weight_i * R2_i) / (weight_a + weight_i);
}
else if (ok_a) { T_final = T_a; R2_final = R2_a; }
else if (ok_i) { T_final = T_i; R2_final = R2_i; }
else
{
int n = fixedLst.Count;
T_final = 12000.0;
R2_final = n >= 3 ? 0.15 : 0.1;
if (T_final < 5000 || T_final > 25000) T_final = 12000;
}
// ===== Ne 计算 =====
double Ne_final;
if (ok_a && ok_i && EiIon > 0)
{
double u0 = CalculateU(specName.EleName, T_final, 0);
double u1 = CalculateU(specName.EleName, T_final, 1);
if (u0 <= 0 || u1 <= 0) u0 = u1 = 1.0;
double arg = bsa_fit - bsi_fit - EiIon / (Kb * T_final);
if (arg > 40) arg = 40;
if (arg < -40) arg = -40;
Ne_final = 4.83e15 * Math.Sqrt(Math.Pow(T_final, 3)) * (u1 / u0) * Math.Exp(arg);
if (Ne_final < 1e15) Ne_final = 1e15;
if (Ne_final > 1e19) Ne_final = 1e19;
}
else
{
Ne_final = 1.0e17 * Math.Pow(T_final / 10000.0, 1.5);
}
_temperature = T_final;
_electronDensity = Ne_final;
_lastRsq = R2_final;
}
// =================================================================
// fitBoltzmann — 4 轮 MAD 剔除 + 线性回归
// =================================================================
private static void FitBoltzmann(
List<SpecData> lines,
out double T_out, out double bs_out, out double R2_out,
out int n_out, out double ekRange_out)
{
int n = lines.Count;
if (n < 2)
{
T_out = 0; bs_out = 0; R2_out = 0; n_out = n; ekRange_out = 0;
return;
}
var xx = new double[n];
var yy = new double[n];
double ekMin = 1e9, ekMax = -1e9;
for (int k = 0; k < n; ++k)
{
yy[k] = Math.Log(lines[k].Intensity * lines[k].WaveLength * 1e7
/ (lines[k].Statis * lines[k].TransPro));
xx[k] = lines[k].UpperLevel;
if (xx[k] < ekMin) ekMin = xx[k];
if (xx[k] > ekMax) ekMax = xx[k];
}
ekRange_out = ekMax - ekMin;
var valid = new bool[n];
for (int k = 0; k < n; ++k) valid[k] = true;
double best_slope = 0, best_intercept = 0, best_R2 = 0;
for (int it = 0; it < 4; ++it)
{
double sx = 0, sx2 = 0, sy = 0, sxy = 0;
int nv = 0;
for (int k = 0; k < n; ++k)
{
if (!valid[k]) continue;
sx += xx[k]; sx2 += xx[k] * xx[k];
sy += yy[k]; sxy += xx[k] * yy[k]; nv++;
}
if (nv < 2) break;
double d = nv * sx2 - sx * sx;
if (Math.Abs(d) < 1e-12) break;
double slope = (nv * sxy - sx * sy) / d;
double intercept = (sy - slope * sx) / nv;
// 残差中位数 + MAD
var resid = new List<double>(nv);
for (int k = 0; k < n; ++k)
if (valid[k]) resid.Add(yy[k] - (slope * xx[k] + intercept));
resid.Sort();
int m = resid.Count;
double median_r = (m % 2 == 1) ? resid[m / 2]
: 0.5 * (resid[m / 2 - 1] + resid[m / 2]);
var absdev = new List<double>(m);
foreach (double r in resid) absdev.Add(Math.Abs(r - median_r));
absdev.Sort();
double mad = (m % 2 == 1) ? absdev[m / 2]
: 0.5 * (absdev[m / 2 - 1] + absdev[m / 2]);
if (mad < 0.1) mad = 0.1;
double thr = 2.0 * mad;
// 剔除(前 3 条不动,保守)
int removed = 0, remaining = 0;
for (int k = 0; k < n; ++k)
{
if (!valid[k]) continue;
double r = yy[k] - (slope * xx[k] + intercept);
if (Math.Abs(r - median_r) > thr && remaining > 2)
{
valid[k] = false; removed++;
}
else remaining++;
}
best_slope = slope;
best_intercept = intercept;
// R²
double meany = sy / nv;
double ss_tot = 0, ss_res = 0;
for (int k = 0; k < n; ++k)
{
if (!valid[k]) continue;
ss_tot += Math.Pow(yy[k] - meany, 2);
ss_res += Math.Pow(yy[k] - (slope * xx[k] + intercept), 2);
}
best_R2 = ss_tot > 1e-12 ? 1 - ss_res / ss_tot : 0;
if (removed == 0) break;
}
if (best_slope >= 0)
{
T_out = 0; bs_out = 0; R2_out = 0; n_out = n;
return;
}
T_out = -1 / best_slope * 11604.45; // eV → K
bs_out = best_intercept;
R2_out = best_R2;
int nv_final = 0;
foreach (bool v in valid) if (v) nv_final++;
n_out = nv_final;
}
}
}
@@ -0,0 +1,382 @@
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
{
private List<ElementData> CalculateConcentration(
List<SpecData> tempneLst, List<ElementCount> elementNameLst)
{
const double Kb = 8.61738573e-5;
var elementLst = new List<ElementData>();
// ===== 第一步:残差自吸检测(P1 扩展:同时覆盖原子线 + 离子线)=====
var elementAtomLines = new Dictionary<string, List<SpecData>>();
var elementIonLines = new Dictionary<string, List<SpecData>>();
foreach (var s in tempneLst)
{
if (s.Ionization == 0)
{
if (!elementAtomLines.TryGetValue(s.EleName, out var list))
{ list = new List<SpecData>(); elementAtomLines[s.EleName] = list; }
list.Add(s);
}
else if (s.Ionization == 1)
{
if (!elementIonLines.TryGetValue(s.EleName, out var list))
{ list = new List<SpecData>(); elementIonLines[s.EleName] = list; }
list.Add(s);
}
}
var residualSelfAbsorbed = new Dictionary<string, HashSet<int>>();
// —— 原子线自吸 ——
foreach (var kv in elementAtomLines)
MarkResidualSelfAbsorbed(kv.Value, tempneLst, residualSelfAbsorbed);
// —— 离子线自吸(机制相同,离子线也会共振自吸)——
foreach (var kv in elementIonLines)
MarkResidualSelfAbsorbed(kv.Value, tempneLst, residualSelfAbsorbed);
// ===== 第二步:峰竞争检查(Cu/Sr 串色保护)=====
int nCuLines = 0, nSrLines = 0;
double cuMaxInt = 0, srMaxInt = 0, caMaxIonInt = 0;
for (int j = 0; j < tempneLst.Count; j++)
{
var s = tempneLst[j];
if (s.EleName == "Cu") { nCuLines++; if (s.Intensity > cuMaxInt) cuMaxInt = s.Intensity; }
if (s.EleName == "Sr") { nSrLines++; if (s.Intensity > srMaxInt) srMaxInt = s.Intensity; }
if (s.EleName == "Ca" && s.Ionization == 1 && s.Intensity > caMaxIonInt)
caMaxIonInt = s.Intensity;
}
var misMatchedLine = new bool[tempneLst.Count];
// Cu 串色:仅当 Cu 无其他线且共振线 > Al 最强 150% 时标记
{
double alMaxInt = 0, cuResInt = 0;
int cuNonResLines = 0;
for (int j = 0; j < tempneLst.Count; j++)
{
var s = tempneLst[j];
if (s.EleName == "Al" && s.Intensity > alMaxInt) alMaxInt = s.Intensity;
if (s.EleName == "Cu" && s.Ionization == 0)
{
double wl = s.WaveLength;
if (Math.Abs(wl - 324.75) < 0.5 || Math.Abs(wl - 327.40) < 0.5)
{ if (s.Intensity > cuResInt) cuResInt = s.Intensity; }
else cuNonResLines++;
}
}
if (cuNonResLines == 0 && alMaxInt > 0 && cuResInt > alMaxInt * 1.5)
{
for (int j = 0; j < tempneLst.Count; j++)
{
var s = tempneLst[j];
if (s.EleName == "Cu" && s.Ionization == 0)
{
double wl = s.WaveLength;
if (Math.Abs(wl - 324.75) < 0.5 || Math.Abs(wl - 327.40) < 0.5)
misMatchedLine[j] = true;
}
}
}
}
// Sr 串色:Ca 强线 > 15 倍时,全部 Sr 线标记
bool srSuspect = (caMaxIonInt > 0 && caMaxIonInt > srMaxInt * 15.0) || nSrLines == 0;
if (srSuspect)
{
for (int j = 0; j < tempneLst.Count; j++)
if (tempneLst[j].EleName == "Sr") misMatchedLine[j] = true;
}
// ===== 第三步:统一 Saha-Boltzmann 浓度计算 =====
var atomicWeightsMap = LoadAtomicWeights();
var ionizationEnergiesMap = LoadIonizationEnergies();
// 全局最强线(自吸判断参考)
double majorLineIntensity = 0;
for (int j = 0; j < tempneLst.Count; j++)
if (!misMatchedLine[j] && tempneLst[j].Intensity > majorLineIntensity)
majorLineIntensity = tempneLst[j].Intensity;
// 各元素最大强度
var elemMaxIntensity = new Dictionary<string, double>();
for (int j = 0; j < tempneLst.Count; j++)
{
if (misMatchedLine[j]) continue;
string en = tempneLst[j].EleName;
double cur = tempneLst[j].Intensity;
if (!elemMaxIntensity.TryGetValue(en, out var mx) || cur > mx)
elemMaxIntensity[en] = cur;
}
// calcNumberDensity 局部函数(captures _temperature)
double CalcNumberDensity(List<(double Ek, double LnIGA)> lines, double U)
{
if (lines.Count < 1 || U <= 0 || _temperature <= 0) return 0;
var bsArr = new List<double>();
foreach (var p in lines)
{
double bs = p.LnIGA + p.Ek / (Kb * _temperature);
if (bs > -50 && bs < 50) bsArr.Add(bs);
}
if (bsArr.Count == 0) return 0;
// ===== P1: MAD 剔除离群 bs(与 FitBoltzmann 同样的鲁棒策略,减少迭代次数到 3 轮)=====
var work = bsArr;
for (int iter = 0; iter < 3; ++iter)
{
work.Sort();
int m = work.Count;
if (m < 2) break;
double med = work[m / 2];
var ad = new List<double>(m);
foreach (double b in work) ad.Add(Math.Abs(b - med));
ad.Sort();
double mad = ad[ad.Count / 2];
if (mad < 0.1) mad = 0.1;
double thr = 2.5 * mad;
var filt = new List<double>();
foreach (double b in work) if (Math.Abs(b - med) < thr) filt.Add(b);
if (filt.Count >= 2 && filt.Count < m) work = filt;
else break;
}
// ===== P1: MAD 剔除后用均值(取代旧的中位数)=====
// 物理上所有合法点的 bs = ln(N/U) 应当一致;MAD 剔除去除自吸/噪声离群后,
// 均值比中位数利用了更多统计信息,且随谱线数增加快速收敛
double bsSum = 0;
foreach (double b in work) bsSum += b;
double bsMean = bsSum / work.Count;
double N = U * Math.Exp(bsMean);
return (N > 0 && N < 1e25) ? N : 0;
}
// 遍历每个元素
foreach (var item in elementNameLst)
{
string elemName = item.EleName;
var ed = new ElementData { EleName = elemName };
elementLst.Add(ed);
var atomLines = new List<(double Ek, double LnIGA)>();
var ionLines = new List<(double Ek, double LnIGA)>();
var atomLinesAll = new List<(double Ek, double LnIGA)>();
var ionLinesAll = new List<(double Ek, double LnIGA)>();
elemMaxIntensity.TryGetValue(elemName, out var elemMaxInt);
for (int j = 0; j < tempneLst.Count; j++)
{
if (misMatchedLine[j]) continue;
if (tempneLst[j].EleName != elemName) continue;
var s = tempneLst[j];
double Aki = s.TransPro, Ek = s.UpperLevel, g = s.Statis, wl = s.WaveLength;
double intensity = s.Intensity;
// 物理过滤:Aki 下限 + Ek 上限
if (Aki < 1.0e7) continue;
bool isLight = elemName == "C" || elemName == "B" || elemName == "N" || elemName == "O";
if (s.Ionization == 0)
{
if (isLight) { if (Ek > 11.0) continue; }
else { if (Ek > 5.5) continue; }
}
else
{
if (Ek > 8.0) continue;
}
double lnArg = intensity * wl / (Aki * g);
if (lnArg <= 0) continue;
double lnIGA = Math.Log(lnArg);
// 硬自吸判定
bool residualSA = residualSelfAbsorbed.TryGetValue(elemName, out var saSet) &&
saSet.Contains(j);
bool selfAbs = residualSA || IsSelfAbsorbedLine(elemName, wl, s.Ionization,
intensity, majorLineIntensity);
if (s.Ionization == 0)
{
atomLinesAll.Add((Ek, lnIGA));
if (!selfAbs) atomLines.Add((Ek, lnIGA));
}
else if (s.Ionization == 1)
{
ionLinesAll.Add((Ek, lnIGA));
if (!selfAbs) ionLines.Add((Ek, lnIGA));
}
}
// 全自吸退化
if (atomLines.Count == 0 && atomLinesAll.Count > 0) atomLines = atomLinesAll;
if (ionLines.Count == 0 && ionLinesAll.Count > 0) ionLines = ionLinesAll;
double u0 = CalculateU(elemName, _temperature, 0);
double u1 = CalculateU(elemName, _temperature, 1);
double Ei = ionizationEnergiesMap.TryGetValue(elemName, out var ev) ? ev : 0;
// Saha 因子
double sahaFactor = 0;
if (Ei > 0 && _temperature > 0 && _electronDensity > 0 && u0 > 0)
{
double arg = -Ei / (Kb * _temperature);
if (arg < -700) arg = -700;
if (arg > 700) arg = 700;
sahaFactor = 4.83e15 * Math.Sqrt(Math.Pow(_temperature, 3)) / _electronDensity
* (u1 / u0) * Math.Exp(arg);
if (double.IsNaN(sahaFactor) || double.IsInfinity(sahaFactor)) sahaFactor = 0;
}
double csa = 0, csit = 0;
int nAtom = atomLines.Count;
int nIon = ionLines.Count;
if (nAtom >= 1)
{
if (u0 > 0) csa = CalcNumberDensity(atomLines, u0);
}
else if (nIon >= 3 && sahaFactor > 0 && u1 > 0)
{
double N_ion = CalcNumberDensity(ionLines, u1);
if (N_ion > 0) { csit = N_ion; csa = csit / sahaFactor; }
}
// 用 Saha 反推 csit(如果还没填)
if (csit <= 0 && sahaFactor > 0 && csa > 0)
csit = csa * sahaFactor;
// 校准因子(当前全为 1.0)
double calibFactor = 1.0;
csa *= calibFactor;
csit *= calibFactor;
if (double.IsNaN(csa) || csa < 0) csa = 0;
if (double.IsNaN(csit) || csit < 0) csit = 0;
ed.Csa = csa;
ed.Csit = csit;
ed.Bsa = (csa > 0 && u0 > 0) ? Math.Log(csa / u0) : 0;
ed.Bsi = (csit > 0 && u1 > 0) ? Math.Log(csit / u1) : 0;
ed.AtomNum = nAtom;
ed.IonNum = nIon;
}
// ===== 归一化到重量百分比 =====
double sumWeighted = 0;
var weightProps = new double[elementLst.Count];
for (int i = 0; i < elementLst.Count; i++)
{
string elemName = elementLst[i].EleName;
double atomicWeight = atomicWeightsMap.TryGetValue(elemName, out var aw) ? aw : 1.0;
double effectiveCsa = elementLst[i].Csa;
bool isIonDominated = elementLst[i].Csit > elementLst[i].Csa * 3.0 && elementLst[i].Csit > 0;
if (isIonDominated || (elementLst[i].AtomNum == 0 && elementLst[i].Csit > 0))
effectiveCsa = elementLst[i].Csa + elementLst[i].Csit;
if (effectiveCsa <= 0) weightProps[i] = 0;
else
{
weightProps[i] = effectiveCsa * atomicWeight;
sumWeighted += weightProps[i];
}
}
if (sumWeighted <= 0) sumWeighted = 1.0;
for (int i = 0; i < elementLst.Count; i++)
{
elementLst[i].RawAbundence = weightProps[i] / sumWeighted * 100.0;
elementLst[i].Abundence = elementLst[i].RawAbundence;
}
// ===== P0 移除:地质硬编码系数校正 =====
// 原代码(2025-11-16 前):对含 Si/Al/Ca/Mg/K 且非合金样品,按硬编码系数对各元素乘 0.005~2.0 的修正因子。
// 这些系数仅对特定地质样品集(如硅酸盐岩石)经验拟合,破坏 CF-LIBS 无标样特性,
// 导致钢铁、陶瓷、有机物等其他样品类型的定量结果严重失真。
// 应用专属校正应通过 EnableCalibration + calibration_factors.txt 传入,保持此处物理无偏。
// ===== 标样线性校正(可选)=====
if (!_enableCalibration) return elementLst;
string calibFile = GetPath("calibration_factors.txt");
if (!File.Exists(calibFile)) return elementLst;
var linCalib = new Dictionary<string, (double A, double B)>();
foreach (var raw in File.ReadLines(calibFile))
{
if (string.IsNullOrWhiteSpace(raw) || raw[0] == '#') continue;
var parts = raw.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 3) continue;
string elem = parts[0];
var dllVals = new List<double>();
var stdVals = new List<double>();
for (int k = 1; k + 1 < parts.Length; k += 2)
{
if (double.TryParse(parts[k], NumberStyles.Float, CultureInfo.InvariantCulture, out var dv) &&
double.TryParse(parts[k + 1], NumberStyles.Float, CultureInfo.InvariantCulture, out var sv))
{
dllVals.Add(dv);
stdVals.Add(sv);
}
}
if (dllVals.Count < 1) continue;
double a, b;
if (dllVals.Count >= 2)
{
double sum_x = 0, sum_y = 0, sum_xy = 0, sum_xx = 0;
int nn = dllVals.Count;
for (int k = 0; k < nn; k++)
{
sum_x += dllVals[k]; sum_y += stdVals[k];
sum_xy += dllVals[k] * stdVals[k];
sum_xx += dllVals[k] * dllVals[k];
}
double denom = nn * sum_xx - sum_x * sum_x;
if (Math.Abs(denom) > 1e-12)
{
a = (nn * sum_xy - sum_x * sum_y) / denom;
b = (sum_y - a * sum_x) / nn;
}
else { a = 0; b = sum_y / nn; }
}
else
{
if (Math.Abs(dllVals[0]) > 1e-12) { a = stdVals[0] / dllVals[0]; b = 0; }
else { a = 0; b = stdVals[0]; }
}
linCalib[elem] = (a, b);
}
double sumCal = 0;
for (int i = 0; i < elementLst.Count; i++)
{
if (linCalib.TryGetValue(elementLst[i].EleName, out var lin))
{
double cal = lin.A * elementLst[i].Abundence + lin.B;
elementLst[i].Abundence = cal > 0 ? cal : 0;
}
sumCal += elementLst[i].Abundence;
}
if (sumCal > 0)
for (int i = 0; i < elementLst.Count; i++)
elementLst[i].Abundence = elementLst[i].Abundence / sumCal * 100;
return elementLst;
}
}
}
@@ -0,0 +1,330 @@
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
{
// ===== 经验配分函数表(T=10000K 参考值 + 温度系数)=====
private static readonly Dictionary<string, double> ExpUI_a = new Dictionary<string, double>();
private static readonly Dictionary<string, double> ExpUI_b = new Dictionary<string, double>();
private static readonly Dictionary<string, double> ExpUI_c = new Dictionary<string, double>();
private static readonly Dictionary<string, double> ExpUII_a = new Dictionary<string, double>();
private static readonly Dictionary<string, double> ExpUII_b = new Dictionary<string, double>();
private static readonly Dictionary<string, double> ExpUII_c = new Dictionary<string, double>();
static CfLibsIdentifier()
{
ExpUI_a["Al"] = 5.85; ExpUI_b["Al"] = 0.10; ExpUI_c["Al"] = 0.000;
ExpUI_a["Cu"] = 1.97; ExpUI_b["Cu"] = 0.02; ExpUI_c["Cu"] = 0.000;
ExpUI_a["Fe"] = 26.4; ExpUI_b["Fe"] = 0.50; ExpUI_c["Fe"] = 0.020;
ExpUI_a["Mg"] = 1.10; ExpUI_b["Mg"] = 0.00; ExpUI_c["Mg"] = 0.000;
ExpUI_a["Si"] = 9.45; ExpUI_b["Si"] = 0.30; ExpUI_c["Si"] = 0.010;
ExpUI_a["Ca"] = 1.32; ExpUI_b["Ca"] = 0.01; ExpUI_c["Ca"] = 0.000;
ExpUI_a["Mn"] = 6.20; ExpUI_b["Mn"] = 0.15; ExpUI_c["Mn"] = 0.005;
ExpUI_a["Zn"] = 1.05; ExpUI_b["Zn"] = 0.00; ExpUI_c["Zn"] = 0.000;
ExpUI_a["Ni"] = 28.5; ExpUI_b["Ni"] = 0.50; ExpUI_c["Ni"] = 0.020;
ExpUI_a["Ti"] = 21.5; ExpUI_b["Ti"] = 0.50; ExpUI_c["Ti"] = 0.020;
ExpUI_a["Cr"] = 9.30; ExpUI_b["Cr"] = 0.20; ExpUI_c["Cr"] = 0.005;
ExpUI_a["Pb"] = 1.90; ExpUI_b["Pb"] = 0.02; ExpUI_c["Pb"] = 0.000;
ExpUI_a["Sn"] = 2.40; ExpUI_b["Sn"] = 0.05; ExpUI_c["Sn"] = 0.000;
ExpUI_a["Na"] = 2.05; ExpUI_b["Na"] = 0.00; ExpUI_c["Na"] = 0.000;
ExpUI_a["K"] = 2.10; ExpUI_b["K"] = 0.00; ExpUI_c["K"] = 0.000;
ExpUI_a["Sr"] = 1.55; ExpUI_b["Sr"] = 0.02; ExpUI_c["Sr"] = 0.000;
ExpUI_a["Zr"] = 25.0; ExpUI_b["Zr"] = 0.50; ExpUI_c["Zr"] = 0.020;
ExpUI_a["Sb"] = 4.60; ExpUI_b["Sb"] = 0.05; ExpUI_c["Sb"] = 0.000;
ExpUI_a["Be"] = 1.05; ExpUI_b["Be"] = 0.00; ExpUI_c["Be"] = 0.000;
ExpUI_a["C"] = 9.30; ExpUI_b["C"] = 0.10; ExpUI_c["C"] = 0.000;
ExpUII_a["Al"] = 1.00; ExpUII_b["Al"] = 0.00; ExpUII_c["Al"] = 0.000;
ExpUII_a["Cu"] = 1.10; ExpUII_b["Cu"] = 0.00; ExpUII_c["Cu"] = 0.000;
ExpUII_a["Fe"] = 31.5; ExpUII_b["Fe"] = 0.60; ExpUII_c["Fe"] = 0.020;
ExpUII_a["Mg"] = 2.05; ExpUII_b["Mg"] = 0.02; ExpUII_c["Mg"] = 0.000;
ExpUII_a["Si"] = 9.20; ExpUII_b["Si"] = 0.20; ExpUII_c["Si"] = 0.005;
ExpUII_a["Ca"] = 1.85; ExpUII_b["Ca"] = 0.02; ExpUII_c["Ca"] = 0.000;
ExpUII_a["Mn"] = 7.20; ExpUII_b["Mn"] = 0.15; ExpUII_c["Mn"] = 0.005;
ExpUII_a["Zn"] = 2.00; ExpUII_b["Zn"] = 0.02; ExpUII_c["Zn"] = 0.000;
ExpUII_a["Ni"] = 32.0; ExpUII_b["Ni"] = 0.60; ExpUII_c["Ni"] = 0.020;
ExpUII_a["Ti"] = 31.5; ExpUII_b["Ti"] = 0.70; ExpUII_c["Ti"] = 0.020;
ExpUII_a["Cr"] = 11.5; ExpUII_b["Cr"] = 0.20; ExpUII_c["Cr"] = 0.005;
ExpUII_a["Pb"] = 2.40; ExpUII_b["Pb"] = 0.02; ExpUII_c["Pb"] = 0.000;
ExpUII_a["Sn"] = 3.20; ExpUII_b["Sn"] = 0.05; ExpUII_c["Sn"] = 0.000;
ExpUII_a["Na"] = 1.00; ExpUII_b["Na"] = 0.00; ExpUII_c["Na"] = 0.000;
ExpUII_a["K"] = 1.00; ExpUII_b["K"] = 0.00; ExpUII_c["K"] = 0.000;
ExpUII_a["Sr"] = 2.10; ExpUII_b["Sr"] = 0.02; ExpUII_c["Sr"] = 0.000;
ExpUII_a["Zr"] = 28.0; ExpUII_b["Zr"] = 0.50; ExpUII_c["Zr"] = 0.020;
ExpUII_a["Sb"] = 5.00; ExpUII_b["Sb"] = 0.05; ExpUII_c["Sb"] = 0.000;
ExpUII_a["Be"] = 1.05; ExpUII_b["Be"] = 0.00; ExpUII_c["Be"] = 0.000;
ExpUII_a["C"] = 5.95; ExpUII_b["C"] = 0.05; ExpUII_c["C"] = 0.000;
}
// =================================================================
// calculateU
// =================================================================
private double CalculateU(string element, double temperature, int ionization)
{
double Tk = temperature / 1000.0;
if (ionization == 0)
{
if (ExpUI_a.TryGetValue(element, out var a) &&
ExpUI_b.TryGetValue(element, out var b) &&
ExpUI_c.TryGetValue(element, out var c))
return a + b * Tk + c * Tk * Tk;
}
else
{
if (ExpUII_a.TryGetValue(element, out var a) &&
ExpUII_b.TryGetValue(element, out var b) &&
ExpUII_c.TryGetValue(element, out var c))
return a + b * Tk + c * Tk * Tk;
}
// 兜底:从 db/*I.dat 或 *II.dat 读
string file = GetPath(element + (ionization == 0 ? "I.dat" : "II.dat"));
if (!File.Exists(file)) return 0;
var gew = new List<double>();
var gei = new List<double>();
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 g) &&
double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var e))
{ gew.Add(g); gei.Add(e); }
}
const double Kb = 8.61738573e-5;
double U = 0;
for (int j = 0; j < gew.Count; j++)
U += (2.0 * gew[j] + 1.0) * Math.Exp(-gei[j] / (Kb * temperature));
return U;
}
// =================================================================
// isSelfAbsorbedLine — 硬编码共振线表
// =================================================================
private static bool IsSelfAbsorbedLine(string elem, double wavelength, int ionization,
double lineIntensity, double majorLineIntensity)
{
if (ionization != 0) return false;
// 痕量元素不标记(<参考线 5%)
if (majorLineIntensity > 0 && lineIntensity < 0.05 * majorLineIntensity)
return false;
if (elem == "Al")
{
if (Math.Abs(wavelength - 394.40) < 0.8 || Math.Abs(wavelength - 396.15) < 0.8) return true;
if (Math.Abs(wavelength - 308.22) < 0.5 || Math.Abs(wavelength - 309.27) < 0.5)
if (majorLineIntensity > 0 && lineIntensity > 0.30 * majorLineIntensity) return true;
}
if (elem == "Ca")
{
if (Math.Abs(wavelength - 422.67) < 0.8 || Math.Abs(wavelength - 430.25) < 0.8) return true;
if (Math.Abs(wavelength - 442.54) < 0.8) return true;
if (Math.Abs(wavelength - 393.37) < 0.8 || Math.Abs(wavelength - 396.85) < 0.8) return true;
}
if (elem == "Na")
{
if (Math.Abs(wavelength - 589.23) < 0.5 || Math.Abs(wavelength - 589.86) < 0.5) return true;
}
if (elem == "Mg")
{
if (Math.Abs(wavelength - 285.26) < 0.5) return true;
if (Math.Abs(wavelength - 279.53) < 0.5 || Math.Abs(wavelength - 280.25) < 0.5) return true;
}
if (elem == "K")
{
if (Math.Abs(wavelength - 766.5) < 0.5 || Math.Abs(wavelength - 769.9) < 0.5) return true;
}
if (elem == "Pb")
{
if (Math.Abs(wavelength - 368.34) < 0.8 || Math.Abs(wavelength - 405.78) < 0.8) return true;
}
if (elem == "Ni")
{
if (Math.Abs(wavelength - 341.48) < 0.5) return true;
}
return false;
}
// =================================================================
// detectSelfAbsorptionByResiduals
// =================================================================
private List<int> DetectSelfAbsorptionByResiduals(
List<SpecData> atomLines,
out List<double> bsValues,
out List<double> residuals,
out double rmse)
{
var result = new List<int>();
bsValues = new List<double>();
residuals = new List<double>();
rmse = 0;
if (atomLines.Count < 3) return result;
const double Kb = 8.61738573e-5;
double invKt = 1.0 / (Kb * _temperature);
foreach (var line in atomLines)
{
double arg = line.Intensity * line.WaveLength / (line.Statis * line.TransPro);
bsValues.Add(arg <= 0 ? 0 : Math.Log(arg) + line.UpperLevel * invKt);
}
double sum_x = 0, sum_x2 = 0, sum_y = 0, sum_xy = 0;
int n = 0;
for (int i = 0; i < atomLines.Count; i++)
{
if (bsValues[i] == 0) continue;
sum_x += atomLines[i].UpperLevel;
sum_x2 += atomLines[i].UpperLevel * atomLines[i].UpperLevel;
sum_y += bsValues[i];
sum_xy += atomLines[i].UpperLevel * bsValues[i];
n++;
}
if (n < 3) return result;
double denom = n * sum_x2 - sum_x * sum_x;
if (Math.Abs(denom) < 1e-12) return result;
double slope = (n * sum_xy - sum_x * sum_y) / denom;
double intercept = (sum_y - slope * sum_x) / n;
double sum_res2 = 0;
for (int i = 0; i < atomLines.Count; i++)
{
if (bsValues[i] == 0) { residuals.Add(0); continue; }
double fitted = slope * atomLines[i].UpperLevel + intercept;
double res = bsValues[i] - fitted;
residuals.Add(res);
sum_res2 += res * res;
}
rmse = Math.Sqrt(sum_res2 / n);
double threshold = -2.0 * rmse;
for (int i = 0; i < residuals.Count; i++)
if (residuals[i] < threshold && residuals[i] < 0)
result.Add(i);
return result;
}
// =================================================================
// MarkResidualSelfAbsorbed — DetectSelfAbsorptionByResiduals + 全局索引回映射
// =================================================================
private void MarkResidualSelfAbsorbed(
List<SpecData> subset,
List<SpecData> fullList,
Dictionary<string, HashSet<int>> residualSelfAbsorbed)
{
var saIdx = DetectSelfAbsorptionByResiduals(subset, out _, out _, out _);
foreach (int localIdx in saIdx)
{
if (localIdx < 0 || localIdx >= subset.Count) continue;
var sa = subset[localIdx];
// 全局回映射
for (int j = 0; j < fullList.Count; j++)
{
if (fullList[j].EleName == sa.EleName &&
fullList[j].Ionization == sa.Ionization &&
Math.Abs(fullList[j].WaveLength - sa.WaveLength) < 0.01 &&
Math.Abs(fullList[j].Intensity - sa.Intensity) < 0.01)
{
if (!residualSelfAbsorbed.TryGetValue(sa.EleName, out var set))
{
set = new HashSet<int>();
residualSelfAbsorbed[sa.EleName] = set;
}
set.Add(j);
break;
}
}
}
}
// =================================================================
// 数据加载(懒缓存)
// =================================================================
private Dictionary<string, double> LoadIonizationEnergies()
{
if (_ionizationEnergies != null) return _ionizationEnergies;
_ionizationEnergies = new Dictionary<string, double>();
string file = GetPath("ionization energy");
if (!File.Exists(file)) return _ionizationEnergies;
foreach (var raw in File.ReadLines(file))
{
var parts = raw.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) continue;
if (double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var v))
_ionizationEnergies[parts[0]] = v;
}
return _ionizationEnergies;
}
private Dictionary<string, double> LoadAtomicWeights()
{
if (_atomicWeights != null) return _atomicWeights;
_atomicWeights = new Dictionary<string, double>();
string file = GetPath("atomic weight");
if (!File.Exists(file)) return _atomicWeights;
foreach (var raw in File.ReadLines(file))
{
var parts = raw.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) continue;
if (double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var v))
_atomicWeights[parts[0]] = v;
}
return _atomicWeights;
}
// ===== 备用:Saha / CS 法(保持对外一致)=====
private double Saha(string element, double temperature, double electronDensity, double csa)
{
double Ei = LoadIonizationEnergies().TryGetValue(element, out var v) ? v : 0;
if (Ei <= 0 || electronDensity <= 0 || temperature <= 0) return 0;
double u0 = CalculateU(element, temperature, 0);
double u1 = CalculateU(element, temperature, 1);
if (u0 <= 0 || u1 <= 0) return 0;
const double Kb = 8.6173303e-5;
double expArg = -Ei / (Kb * temperature);
if (expArg < -700) return 0;
if (expArg > 700) expArg = 700;
double csit = 4.83e15 * Math.Sqrt(Math.Pow(temperature, 3)) / electronDensity
* (u1 / u0) * Math.Exp(expArg) * csa;
if (double.IsNaN(csit) || csit < 0 || csit > 1e20) return 0;
return csit;
}
private double CalculateConcentrationByIntercept(
double inten, double transpro, double upplevel, double statis,
double waveLength, double temperature)
{
const double Kb = 8.61738573e-5;
if (transpro <= 0 || statis <= 0 || temperature <= 0 || inten <= 0 || waveLength <= 0) return 0;
double arg = inten * waveLength / (transpro * statis);
if (arg <= 0) return 0;
return Math.Log(arg) + upplevel / (Kb * temperature);
}
private double CalculateConcentrationByCS(
string element, double temperature, int ionization,
double electronDensity, double bs)
{
if (bs == 0 || electronDensity <= 0 || temperature <= 0) return 0;
if (bs > 200.0) bs = 200.0;
if (bs < -200.0) return 0;
double u = CalculateU(element, temperature, ionization);
if (u <= 0) return 0;
double cs = u * Math.Exp(bs);
if (double.IsNaN(cs) || cs > 1e20) return 0;
return cs;
}
}
}
@@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CfLibs
{
// ==================== 对外数据结构 ====================
public class SpectrumPoint
{
public double Wavelength;
public double Intensity;
}
public class RawSpectrum
{
public List<SpectrumPoint> Points = new List<SpectrumPoint>();
}
public class MatchedLine
{
public string Element; //元素名称
public double WavelengthSource; //原始测量波长(nm):原始光谱中实际找到的谱峰位置,用于回溯/按波长取强度
public double Wavelength; //波长(nm):定性时匹配到的谱线库(如 NIST)波长
public double Intensity; //强度
public double TransProb; //跃迁概率 A (s^-1)
public double UpperLevel; //上能级 Ek (eV)
public double StatWeight; //统计权重 g
public int Ionization; //电离状态: 0=原子线(I), 1=离子线(II)
}
public class SpectralLines
{
public List<MatchedLine> Lines = new List<MatchedLine>();
}
// ==================== 内部数据结构 ====================
internal class ElementLines
{
public string Element; //元素名称
public int Ionization; //电离状态: 0=原子线(I), 1=离子线(II)
public List<double> Wavelengths = new List<double>();
}
internal class DetectedPeak
{
public double Wavelength;
public double Intensity;
public double Snr;
}
internal class MatchResult
{
public string Element;
public int Ionization;
public int MatchedLines;
public int TotalLines;
public double Confidence;
public List<double> MatchedWavelengths = new List<double>();
public string SpeciesLabel => Element + (Ionization == 0 ? " I" : " II");
}
internal class NistLine
{
public string Element;
public double Wavelength;
public double Intensity;
public double TransProb;
public double UpperLevel;
public double StatWeight;
public int Ionization;
public bool HasFullParams;
}
internal class SpecData
{
public string EleName;
public double WavelengthSource; //原始测量波长(谱峰位置)
public double WaveLength; //匹配到的谱线库波长
public double Intensity;
public double TransPro;
public double UpperLevel;
public double Statis;
public int Ionization;
}
internal class FixData
{
public double Wavelength;
public double Fix;
}
internal class DedupEntry
{
public SpecData Sd;
public double Dist;
}
// ==================== 对外的定量结果 ====================
/// <summary>单个元素的定量结果</summary>
public class ElementResult
{
public string Element; // 元素名称
public double Abundance; // 最终重量百分比(可能含标样校正)
public double RawAbundance; // 校正前重量百分比
public double AbundanceAtom; // 原子数百分比(原C++固定为0)
public double Csa; // 原子态浓度 cm^-3
public double Csit; // 离子态浓度(Saha 修正后)cm^-3
public double Temperature; // 该元素对应温度 K
public double ElectronDensity; // 该元素对应电子密度 cm^-3
}
/// <summary>定量分析完整结果</summary>
public class Result
{
public List<ElementResult> Elements = new List<ElementResult>();
public double Temperature;
public double ElectronDensity;
public int Status;
public string ErrorMsg = "";
}
// ==================== 内部数据结构 ====================
internal class ElementCount
{
public string EleName;
public int Count;
}
internal class ElementData
{
public string EleName;
public int AtomNum;
public int IonNum;
public int AtomNumCS;
public int IonNumCS;
public double Bsa;
public double Bsi;
public double Csa;
public double Csit;
public double Abundence;
public double RawAbundence;
}
}
@@ -0,0 +1,251 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CfLibs
{
/// <summary>
/// 光谱 CSV 加载器(对应 C++ 的 readCsvSpectrumAuto 家族)
/// 自动识别 长格式 / 宽格式 / 无表头宽格式
/// </summary>
public static class SpectrumLoader
{
/// <summary>简短别名,等价于 LoadSpectrumFromCsv</summary>
public static RawSpectrum LoadCsv(string filePath)
=> LoadSpectrumFromCsv(filePath);
public static RawSpectrum LoadSpectrumFromCsv(string filePath)
{
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
throw new FileNotFoundException("光谱文件不存在: " + filePath);
// 1. 读第 1 行做格式探测(与 C++ 的 header 启发式一致)
string firstLine;
using (var reader = new StreamReader(filePath))
{
firstLine = reader.ReadLine();
}
if (string.IsNullOrEmpty(firstLine)) return new RawSpectrum();
int commaCount = 0;
foreach (char c in firstLine) if (c == ',') commaCount++;
char c0 = firstLine[0];
bool firstIsDigit = char.IsDigit(c0) || c0 == '.' || c0 == '-' || c0 == '+';
bool looksWide = commaCount >= 99 && !firstIsDigit;
// 2. 宽格式优先
if (looksWide)
{
var wide = ReadWideFormatCsv(filePath);
if (wide != null && wide.Points.Count > 0) return wide;
// 失败 → 回退长格式
}
// 3. 长格式
return ReadLongFormatCsv(filePath);
}
// =====================================================================
// 长格式:波长,强度(也支持 Tab/空格分隔)
// =====================================================================
private static RawSpectrum ReadLongFormatCsv(string filePath)
{
var spectrum = new RawSpectrum();
using (var reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.Trim('\r', '\n', ' ', '\t');
if (line.Length == 0) continue;
char c0 = line[0];
if (!(char.IsDigit(c0) || c0 == '-' || c0 == '+' || c0 == '.')) continue;
double wl = 0, intensity = 0;
int comma = line.IndexOf(',');
int tab = line.IndexOf('\t');
int sep = comma >= 0 ? comma : tab;
bool ok = false;
if (sep >= 0)
{
ok = double.TryParse(line.Substring(0, sep),
NumberStyles.Float, CultureInfo.InvariantCulture, out wl)
&& double.TryParse(line.Substring(sep + 1),
NumberStyles.Float, CultureInfo.InvariantCulture, out intensity);
}
else
{
var parts = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 2)
{
ok = double.TryParse(parts[0],
NumberStyles.Float, CultureInfo.InvariantCulture, out wl)
&& double.TryParse(parts[1],
NumberStyles.Float, CultureInfo.InvariantCulture, out intensity);
}
}
if (!ok) continue;
spectrum.Points.Add(new SpectrumPoint { Wavelength = wl, Intensity = intensity });
}
}
return spectrum;
}
// =====================================================================
// 宽格式:表头 = 波长列;每行 = 一张光谱(多行平均后输出单张平均光谱)
// =====================================================================
private static RawSpectrum ReadWideFormatCsv(string filePath)
{
var spectrum = new RawSpectrum();
using (var reader = new StreamReader(filePath))
{
string header = reader.ReadLine();
if (header == null) return spectrum;
header = header.TrimEnd('\r', '\n');
if (header.Length == 0) return spectrum;
var headerCols = header.Split(',');
if (headerCols.Length < 10) return spectrum;
// 扫描表头,提取能解析为波长(nm) 的列
var wavelengths = new List<double>();
int firstWlCol = -1;
for (int i = 0; i < headerCols.Length; i++)
{
string h = headerCols[i].Trim();
if (h.Length == 0) continue;
// 去 BOM
if (h.Length >= 3 &&
(byte)h[0] == 0xEF && (byte)h[1] == 0xBB && (byte)h[2] == 0xBF)
h = h.Substring(3);
if (double.TryParse(h, NumberStyles.Float, CultureInfo.InvariantCulture, out var v)
&& v > 50.0 && v < 20000.0)
{
if (firstWlCol < 0) firstWlCol = i;
wavelengths.Add(v);
}
}
// 波长列不足 50 → 不是标准宽格式,走"无表头宽格式"分支
if (wavelengths.Count < 50)
return ReadWideFormatNoHeader(filePath);
int nWl = wavelengths.Count;
var sumIntensity = new double[nWl];
int validRows = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.TrimEnd('\r', '\n');
if (line.Length == 0) continue;
char c0 = line[0];
if (!(char.IsDigit(c0) || c0 == '-' || c0 == '+' || c0 == '.')) continue;
var cells = line.Split(',');
if (cells.Length < firstWlCol + nWl) continue;
for (int i = 0; i < nWl; ++i)
{
double.TryParse(cells[firstWlCol + i],
NumberStyles.Float, CultureInfo.InvariantCulture, out var val);
sumIntensity[i] += val;
}
validRows++;
}
if (validRows <= 0 || nWl <= 0) return spectrum;
double invN = 1.0 / validRows;
spectrum.Points.Capacity = nWl;
for (int i = 0; i < nWl; ++i)
{
spectrum.Points.Add(new SpectrumPoint
{
Wavelength = wavelengths[i],
Intensity = sumIntensity[i] * invN
});
}
}
return spectrum;
}
// =====================================================================
// 宽格式变体(表头无波长):前 4 行是 X/Y 元数据;
// 从第 5 行起每行:第 1 列 = 波长,后面 N 列 = 空间强度
// =====================================================================
private static RawSpectrum ReadWideFormatNoHeader(string filePath)
{
var spectrum = new RawSpectrum();
using (var reader = new StreamReader(filePath))
{
// 跳过 4 行元数据
for (int i = 0; i < 4; i++)
if (reader.ReadLine() == null) return spectrum;
var wlList = new List<double>();
var intList = new List<double>();
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.TrimEnd('\r', '\n');
if (line.Length == 0) continue;
char c0 = line[0];
if (!(char.IsDigit(c0) || c0 == '-' || c0 == '+' || c0 == '.')) continue;
var cells = line.Split(',');
if (cells.Length < 2) continue;
if (!double.TryParse(cells[0], NumberStyles.Float,
CultureInfo.InvariantCulture, out var wl))
continue;
if (wl < 50.0 || wl > 20000.0) continue;
wlList.Add(wl);
double sumInt = 0;
int cnt = 0;
for (int i = 1; i < cells.Length; i++)
{
if (double.TryParse(cells[i], NumberStyles.Float,
CultureInfo.InvariantCulture, out var v))
{
sumInt += v;
cnt++;
}
}
intList.Add(cnt > 0 ? sumInt / cnt : 0);
}
if (wlList.Count >= 50)
{
spectrum.Points.Capacity = wlList.Count;
for (int i = 0; i < wlList.Count; i++)
{
spectrum.Points.Add(new SpectrumPoint
{
Wavelength = wlList[i],
Intensity = intList[i]
});
}
}
}
return spectrum;
}
}
}