using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CfLibs { /// /// 光谱 CSV 加载器(对应 C++ 的 readCsvSpectrumAuto 家族) /// 自动识别 长格式 / 宽格式 / 无表头宽格式 /// public static class SpectrumLoader { /// 简短别名,等价于 LoadSpectrumFromCsv 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(); 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(); var intList = new List(); 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; } } }