Files
2026-11-19 16:42:26 +08:00

383 lines
17 KiB
C#
Raw Permalink 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 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;
}
}
}