1use crate::atla::types::{
25 ColorRendering, Emitter, Header, LuminaireOpticalData, SpectralDistribution, SpectralUnits,
26};
27use std::collections::BTreeMap;
28use std::path::Path;
29
30#[derive(Debug, Clone, Default)]
36pub struct ReferenceMetrics {
37 pub cie_x: Option<f64>, pub cie_y: Option<f64>,
40 pub cie_z: Option<f64>,
41 pub chromaticity_x: Option<f64>,
42 pub chromaticity_y: Option<f64>,
43 pub cie1960_u: Option<f64>,
45 pub cie1960_v: Option<f64>,
46 pub cie1976_u_prime: Option<f64>,
48 pub cie1976_v_prime: Option<f64>,
49 pub cct_k: Option<f64>,
51 pub duv: Option<f64>,
52 pub dominant_wavelength_nm: Option<f64>,
53 pub peak_wavelength_nm: Option<f64>,
54 pub half_peak_width_nm: Option<f64>,
55 pub purity_pct: Option<f64>,
56 pub ra: Option<f64>,
58 pub r_special: [Option<f64>; 15], pub cqs: Option<f64>,
60 pub gai_ees: Option<f64>,
61 pub gai_bb_8: Option<f64>,
62 pub gai_bb_15: Option<f64>,
63 pub illuminance_lx: Option<f64>,
65 pub irradiance_w_m2: Option<f64>,
66 pub sp_ratio: Option<f64>,
67 pub eml: Option<f64>,
69 pub m_edi: Option<f64>,
70 pub par_w_m2: Option<f64>,
72 pub ppfd_umol_m2s: Option<f64>,
73 pub ypfd_umol_m2s: Option<f64>,
74 pub blue_light_hazard_w_m2: Option<f64>,
76 pub blue_light_risk_group: Option<String>,
77 pub sdcm: Option<f64>,
79}
80
81#[derive(Debug, Clone, Default)]
83pub struct LoadedSpd {
84 pub spd: SpectralDistribution,
85 pub reference: Option<ReferenceMetrics>,
86 pub label: String,
88}
89
90#[derive(Debug)]
92pub enum SpdLoadError {
93 Io(std::io::Error),
94 Parse(String),
95}
96
97impl std::fmt::Display for SpdLoadError {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 match self {
100 SpdLoadError::Io(e) => write!(f, "io: {e}"),
101 SpdLoadError::Parse(s) => write!(f, "parse: {s}"),
102 }
103 }
104}
105
106impl std::error::Error for SpdLoadError {}
107
108impl From<std::io::Error> for SpdLoadError {
109 fn from(e: std::io::Error) -> Self {
110 SpdLoadError::Io(e)
111 }
112}
113
114pub fn load<P: AsRef<Path>>(path: P) -> Result<LoadedSpd, SpdLoadError> {
116 let path = path.as_ref();
117 let content = std::fs::read_to_string(path)?;
118 let label = path
119 .file_stem()
120 .map(|s| s.to_string_lossy().into_owned())
121 .unwrap_or_default();
122 let mut loaded = parse(&content)?;
123 if loaded.label.is_empty() {
124 loaded.label = label;
125 }
126 Ok(loaded)
127}
128
129pub fn parse(content: &str) -> Result<LoadedSpd, SpdLoadError> {
131 if content.starts_with("1,CIE1931") || content.contains("\n1,CIE1931") {
134 return parse_signify(content);
135 }
136 let first_line = content
138 .lines()
139 .next()
140 .unwrap_or("")
141 .trim()
142 .to_ascii_lowercase();
143 if first_line.starts_with("wavelength_nm") || first_line == "wavelength,intensity" {
144 return parse_named_csv(content);
145 }
146 if content.lines().any(|l| l.trim_start().starts_with('#')) {
148 return parse_luxeon_spd(content);
149 }
150 parse_two_column(content)
152}
153
154fn parse_luxeon_spd(content: &str) -> Result<LoadedSpd, SpdLoadError> {
159 let mut label = String::new();
160 let mut pairs: Vec<(f64, f64)> = Vec::new();
161 for line in content.lines() {
162 let line = line.trim();
163 if line.is_empty() {
164 continue;
165 }
166 if let Some(rest) = line.strip_prefix('#') {
167 let r = rest.trim();
169 if label.is_empty() && !r.starts_with("Wavelength") && !r.is_empty() {
170 label = r.to_string();
171 }
172 continue;
173 }
174 let mut it = line
175 .split(|c: char| c.is_whitespace() || c == ',')
176 .filter(|s| !s.is_empty());
177 if let (Some(w), Some(v)) = (it.next(), it.next()) {
178 let (Ok(w), Ok(v)) = (w.parse::<f64>(), v.parse::<f64>()) else {
179 continue;
180 };
181 pairs.push((w, v));
182 }
183 }
184 if pairs.is_empty() {
185 return Err(SpdLoadError::Parse(
186 "Luxeon .spd: no wavelength/value rows".into(),
187 ));
188 }
189 Ok(LoadedSpd {
190 spd: build_spd(pairs),
191 reference: None,
192 label,
193 })
194}
195
196fn parse_named_csv(content: &str) -> Result<LoadedSpd, SpdLoadError> {
197 let mut pairs: Vec<(f64, f64)> = Vec::new();
198 for (i, line) in content.lines().enumerate() {
199 if i == 0 {
200 continue; }
202 let line = line.trim();
203 if line.is_empty() {
204 continue;
205 }
206 let mut it = line.split(',');
207 if let (Some(w), Some(v)) = (it.next(), it.next()) {
208 let (Ok(w), Ok(v)) = (w.trim().parse::<f64>(), v.trim().parse::<f64>()) else {
209 continue;
210 };
211 pairs.push((w, v));
212 }
213 }
214 if pairs.is_empty() {
215 return Err(SpdLoadError::Parse(
216 "named CSV: no rows after header".into(),
217 ));
218 }
219 Ok(LoadedSpd {
220 spd: build_spd(pairs),
221 reference: None,
222 label: String::new(),
223 })
224}
225
226fn parse_two_column(content: &str) -> Result<LoadedSpd, SpdLoadError> {
227 let mut pairs: Vec<(f64, f64)> = Vec::new();
228 for line in content.lines() {
229 let line = line.trim();
230 if line.is_empty() {
231 continue;
232 }
233 let mut it = line
234 .split(|c: char| c.is_whitespace() || c == ',')
235 .filter(|s| !s.is_empty());
236 if let (Some(w), Some(v)) = (it.next(), it.next()) {
237 if let (Ok(w), Ok(v)) = (w.parse::<f64>(), v.parse::<f64>()) {
238 pairs.push((w, v));
239 }
240 }
241 }
242 if pairs.is_empty() {
243 return Err(SpdLoadError::Parse(
244 "fallback two-column: no numeric rows".into(),
245 ));
246 }
247 Ok(LoadedSpd {
248 spd: build_spd(pairs),
249 reference: None,
250 label: String::new(),
251 })
252}
253
254fn parse_signify(content: &str) -> Result<LoadedSpd, SpdLoadError> {
255 let mut metrics = ReferenceMetrics::default();
256 let mut in_body = false;
257 let mut pairs: Vec<(f64, f64)> = Vec::new();
258
259 for line in content.lines() {
260 let line = line.trim_end_matches(['\r', '\n']);
261 if line.is_empty() {
262 continue;
263 }
264 if in_body {
265 let mut it = line.split(',');
266 if let (Some(w), Some(v)) = (it.next(), it.next()) {
267 if let (Ok(w), Ok(v)) = (w.trim().parse::<f64>(), v.trim().parse::<f64>()) {
268 pairs.push((w, v));
269 }
270 }
271 continue;
272 }
273 if line.eq_ignore_ascii_case("wavelength") {
275 in_body = true;
276 continue;
277 }
278 let parts: Vec<&str> = line.split(',').collect();
281 if parts.len() < 2 {
282 continue;
283 }
284 let (label, raw_val) = if parts.len() >= 3 && parts[0].trim().parse::<u32>().is_ok() {
286 (parts[1].trim(), parts[2..].join(","))
287 } else {
288 (parts[0].trim(), parts[1..].join(","))
289 };
290 assign_signify_metric(&mut metrics, label, raw_val.trim());
291 }
292 if pairs.is_empty() {
293 return Err(SpdLoadError::Parse(
294 "Signify: prelude parsed but no SPD body after `wavelength` line".into(),
295 ));
296 }
297 Ok(LoadedSpd {
298 spd: build_spd(pairs),
299 reference: Some(metrics),
300 label: String::new(),
301 })
302}
303
304fn assign_signify_metric(m: &mut ReferenceMetrics, label: &str, raw: &str) {
307 let (numeric_str, after_slash) = match raw.split_once('/') {
309 Some((a, b)) => (a.trim(), Some(b.trim())),
310 None => (raw, None),
311 };
312 let num = numeric_str.parse::<f64>().ok();
313 let l = label;
314 if l.starts_with("CIE1931 colorspace tristimulus values X") {
315 m.cie_x = num;
316 } else if l.starts_with("CIE1931 colorspace tristimulus values Y") {
317 m.cie_y = num;
318 } else if l.starts_with("CIE1931 colorspace tristimulus values Z") {
319 m.cie_z = num;
320 } else if l.starts_with("CIE1931 colorspace chromaticity coordinates x") {
321 m.chromaticity_x = num;
322 } else if l.starts_with("CIE1931 colorspace chromaticity coordinates y") {
323 m.chromaticity_y = num;
324 } else if l.starts_with("CIE1960 colorspace chromaticity coordinates u") && !l.contains('\'') {
325 m.cie1960_u = num;
326 } else if l.starts_with("CIE1960 colorspace chromaticity coordinates v") && !l.contains('\'') {
327 m.cie1960_v = num;
328 } else if l.starts_with("CIE1976 colorspace chromaticity coordinates u'") {
329 m.cie1976_u_prime = num;
330 } else if l.starts_with("CIE1976 colorspace chromaticity coordinates v'") {
331 m.cie1976_v_prime = num;
332 } else if l.starts_with("Color temperature CCT") {
333 m.cct_k = num;
334 } else if l.starts_with("Color shift Duv") {
335 m.duv = num;
336 } else if l.starts_with("Color render index Ra") {
337 m.ra = num;
338 } else if let Some(idx) = l.strip_prefix("Color render index R") {
339 if let Ok(i) = idx.parse::<usize>() {
340 if (1..=15).contains(&i) {
341 m.r_special[i - 1] = num;
342 }
343 }
344 } else if l.starts_with("Peak wavelength Lp") {
345 m.peak_wavelength_nm = num;
346 } else if l.starts_with("Half-peak width HW") {
347 m.half_peak_width_nm = num;
348 } else if l.starts_with("Dominant wavelength Ld") {
349 m.dominant_wavelength_nm = num;
350 } else if l.starts_with("Color purity Purity") {
351 m.purity_pct = num;
352 } else if l.starts_with("Light-dark vision ratio S/P") {
353 m.sp_ratio = num;
354 } else if l.starts_with("Illuminance Lux") {
355 m.illuminance_lx = num;
356 } else if l.starts_with("Irradiance Ee") {
357 m.irradiance_w_m2 = num;
358 } else if l.starts_with("Color quality scale CQS") {
359 m.cqs = num;
360 } else if l.starts_with("Gamut area index GAI_EES") {
361 m.gai_ees = num;
362 } else if l.starts_with("Gamut area index GAI_BB_8") {
363 m.gai_bb_8 = num;
364 } else if l.starts_with("Gamut area index GAI_BB_15") {
365 m.gai_bb_15 = num;
366 } else if l.starts_with("Equivalen melanopic lux EML") {
367 m.eml = num;
368 } else if l.starts_with("Melanopic equivalent daylight illuminance M_EDI") {
369 m.m_edi = num;
370 } else if l.starts_with("Photosynthetically active radiation PAR") {
371 m.par_w_m2 = num;
372 } else if l.starts_with("Photosynthetic photon flux density PPFD") {
373 m.ppfd_umol_m2s = num;
374 } else if l.starts_with("Yield photon flux density YPFD") {
375 m.ypfd_umol_m2s = num;
376 } else if l.starts_with("Blue light hazard weighted irradiance Eb") {
377 m.blue_light_hazard_w_m2 = num;
378 m.blue_light_risk_group = after_slash.map(|s| s.to_string());
379 } else if l.starts_with("Color tolerance SDCM") {
380 m.sdcm = num;
382 }
383}
384
385fn build_spd(pairs: Vec<(f64, f64)>) -> SpectralDistribution {
392 let mut acc: BTreeMap<i64, (f64, f64, usize)> = BTreeMap::new(); for (w, v) in pairs {
396 if !w.is_finite() || !v.is_finite() {
397 continue;
398 }
399 let key = (w * 1000.0).round() as i64;
400 let e = acc.entry(key).or_insert((w, 0.0, 0));
401 e.1 += v;
402 e.2 += 1;
403 }
404 let mut wavelengths = Vec::with_capacity(acc.len());
405 let mut values = Vec::with_capacity(acc.len());
406 for (_, (w, sum, n)) in acc {
407 wavelengths.push(w);
408 values.push(sum / n as f64);
409 }
410
411 let (start_wavelength, wavelength_interval) = if wavelengths.len() >= 2 {
413 let n = wavelengths.len() - 1;
414 let mean_step = (wavelengths[n] - wavelengths[0]) / n as f64;
415 let uniform = wavelengths.windows(2).all(|w| {
416 let s = w[1] - w[0];
417 (s - mean_step).abs() / mean_step.abs().max(1e-9) < 1e-3
418 });
419 if uniform {
420 (Some(wavelengths[0]), Some(mean_step))
421 } else {
422 (Some(wavelengths[0]), None)
423 }
424 } else {
425 (wavelengths.first().copied(), None)
426 };
427
428 SpectralDistribution {
429 wavelengths,
430 values,
431 units: SpectralUnits::Relative,
432 start_wavelength,
433 wavelength_interval,
434 }
435}
436
437pub fn to_atla(loaded: &LoadedSpd) -> LuminaireOpticalData {
451 let label = if loaded.label.is_empty() {
452 None
453 } else {
454 Some(loaded.label.clone())
455 };
456 let mut doc = LuminaireOpticalData {
457 header: Header {
458 description: label.clone(),
459 ..Default::default()
460 },
461 ..Default::default()
462 };
463
464 let mut emitter = Emitter {
465 description: label,
466 spectral_distribution: Some(loaded.spd.clone()),
467 quantity: 1,
468 ..Default::default()
469 };
470
471 if let Some(r) = &loaded.reference {
472 emitter.cct = r.cct_k;
473 emitter.duv = r.duv;
474 emitter.sp_ratio = r.sp_ratio;
475 if r.ra.is_some() || r.r_special[8].is_some() {
477 emitter.color_rendering = Some(ColorRendering {
478 ra: r.ra,
479 r9: r.r_special[8],
480 rf: None,
481 rg: None,
482 });
483 }
484 }
485
486 doc.emitters = vec![emitter];
487 doc
488}
489
490pub fn attach_spd(
498 doc: &mut LuminaireOpticalData,
499 spd: &SpectralDistribution,
500 emitter: Option<usize>,
501) -> usize {
502 if doc.emitters.is_empty() {
503 doc.emitters.push(Emitter {
504 spectral_distribution: Some(spd.clone()),
505 quantity: 1,
506 ..Default::default()
507 });
508 return 1;
509 }
510 match emitter {
511 Some(i) if i < doc.emitters.len() => {
512 doc.emitters[i].spectral_distribution = Some(spd.clone());
513 1
514 }
515 _ => {
516 for e in &mut doc.emitters {
517 e.spectral_distribution = Some(spd.clone());
518 }
519 doc.emitters.len()
520 }
521 }
522}
523
524pub fn get_warnings(loaded: &LoadedSpd) -> Vec<String> {
526 let mut w = vec![
527 "SPD file contains spectral data only — no photometric (intensity) distribution."
528 .to_string(),
529 "Polar/cartesian diagrams will be empty. Only the spectral diagram is available."
530 .to_string(),
531 ];
532 if loaded.spd.wavelengths.len() < 20 {
533 w.push(format!(
534 "Limited spectral resolution: only {} data points.",
535 loaded.spd.wavelengths.len()
536 ));
537 }
538 if loaded.reference.is_some() {
539 w.push(
540 "Vendor reference metrics (CCT, Duv, CRI) were parsed from the file prelude.".into(),
541 );
542 }
543 w
544}
545
546#[cfg(test)]
551mod tests {
552 use super::*;
553
554 #[test]
555 fn attach_spd_targets_emitters() {
556 let spd = parse("# t\n400\t0.5\n500\t1.0\n600\t0.5\n").unwrap().spd;
557 let mut doc = LuminaireOpticalData::default();
558 assert_eq!(attach_spd(&mut doc, &spd, None), 1);
559 assert_eq!(doc.emitters.len(), 1);
560 assert!(doc.emitters[0].spectral_distribution.is_some());
561
562 let mut doc = LuminaireOpticalData {
563 emitters: vec![Emitter::default(), Emitter::default()],
564 ..Default::default()
565 };
566 assert_eq!(attach_spd(&mut doc, &spd, Some(1)), 1);
567 assert!(doc.emitters[0].spectral_distribution.is_none());
568 assert!(doc.emitters[1].spectral_distribution.is_some());
569 assert_eq!(attach_spd(&mut doc, &spd, Some(7)), 2);
570 assert!(doc
571 .emitters
572 .iter()
573 .all(|e| e.spectral_distribution.is_some()));
574 }
575
576 #[test]
577 fn detects_luxeon_spd() {
578 let s = "# Luxeon test\n# Wavelength[nm]\tRelative_Power\n400\t0.5\n410\t0.8\n420\t1.0\n";
579 let r = parse(s).unwrap();
580 assert_eq!(r.spd.wavelengths, vec![400.0, 410.0, 420.0]);
581 assert_eq!(r.spd.values, vec![0.5, 0.8, 1.0]);
582 assert_eq!(r.spd.wavelength_interval, Some(10.0));
583 assert!(r.reference.is_none());
584 assert_eq!(r.label, "Luxeon test");
585 }
586
587 #[test]
588 fn detects_named_csv() {
589 let s = "wavelength_nm,intensity\n400.0,0.5\n401.0,0.7\n402.0,0.9\n";
590 let r = parse(s).unwrap();
591 assert_eq!(r.spd.wavelengths.len(), 3);
592 assert!((r.spd.wavelength_interval.unwrap() - 1.0).abs() < 1e-9);
593 }
594
595 #[test]
596 fn duplicate_wavelengths_are_averaged() {
597 let s = "wavelength_nm,intensity\n400.0,0.4\n400.0,0.6\n401.0,1.0\n";
598 let r = parse(s).unwrap();
599 assert_eq!(r.spd.wavelengths, vec![400.0, 401.0]);
600 assert!((r.spd.values[0] - 0.5).abs() < 1e-12);
601 }
602
603 #[test]
604 fn detects_signify_and_parses_metrics() {
605 let s = "1,CIE1931 colorspace tristimulus values X,107.88\n\
606 4,CIE1931 colorspace chromaticity coordinates x,0.4386\n\
607 5,CIE1931 colorspace chromaticity coordinates y,0.4066\n\
608 10,Color temperature CCT(K),2997\n\
609 14,Color shift Duv,0.0010\n\
610 15,Color render index Ra,85.9\n\
611 16,Color render index R1,87.0\n\
612 24,Color render index R9,47.9\n\
613 30,Color render index R15,84.5\n\
614 45,Blue light hazard weighted irradiance Eb(W/m²),0.7040/RG0\n\
615 wavelength\n\
616 340,0\n\
617 341,0.1\n\
618 342,0.2\n";
619 let r = parse(s).unwrap();
620 let ref_m = r.reference.expect("Signify reference metrics");
621 assert_eq!(ref_m.cie_x, Some(107.88));
622 assert_eq!(ref_m.chromaticity_x, Some(0.4386));
623 assert_eq!(ref_m.chromaticity_y, Some(0.4066));
624 assert_eq!(ref_m.cct_k, Some(2997.0));
625 assert_eq!(ref_m.duv, Some(0.0010));
626 assert_eq!(ref_m.ra, Some(85.9));
627 assert_eq!(ref_m.r_special[0], Some(87.0)); assert_eq!(ref_m.r_special[8], Some(47.9)); assert_eq!(ref_m.r_special[14], Some(84.5)); assert_eq!(ref_m.blue_light_hazard_w_m2, Some(0.7040));
631 assert_eq!(ref_m.blue_light_risk_group.as_deref(), Some("RG0"));
632 assert_eq!(r.spd.wavelengths, vec![340.0, 341.0, 342.0]);
633 assert_eq!(r.spd.values, vec![0.0, 0.1, 0.2]);
634 }
635
636 #[test]
637 fn to_atla_carries_spd_and_signify_metadata() {
638 let s = "1,CIE1931 colorspace tristimulus values X,107.88\n\
640 10,Color temperature CCT(K),2997\n\
641 14,Color shift Duv,0.0010\n\
642 15,Color render index Ra,85.9\n\
643 24,Color render index R9,47.9\n\
644 35,Light-dark vision ratio S/P,4.860\n\
645 wavelength\n\
646 400,0.1\n\
647 500,0.5\n\
648 600,1.0\n\
649 700,0.2\n";
650 let loaded = parse(s).unwrap();
651 let doc = to_atla(&loaded);
652 assert_eq!(doc.emitters.len(), 1);
653 let e = &doc.emitters[0];
654 assert!(
655 e.spectral_distribution.is_some(),
656 "SPD must be attached to emitter"
657 );
658 assert_eq!(e.cct, Some(2997.0));
659 assert_eq!(e.duv, Some(0.001));
660 assert_eq!(e.sp_ratio, Some(4.86));
661 let cr = e
662 .color_rendering
663 .as_ref()
664 .expect("ColorRendering populated");
665 assert_eq!(cr.ra, Some(85.9));
666 assert_eq!(cr.r9, Some(47.9));
667 assert!(e.intensity_distribution.is_none());
669 let w = get_warnings(&loaded);
671 assert!(w.iter().any(|m| m.contains("spectral data only")));
672 }
673
674 #[test]
677 fn loads_every_real_corpus_file() {
678 let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/SPDs");
679 if !std::path::Path::new(root).exists() {
680 return; }
682 let mut total = 0;
683 for sub in ["Luxeon_SPD_fixed", "luxeon_95CRI", "Youji-Nite", "Signify"] {
684 let dir = format!("{root}/{sub}");
685 let Ok(entries) = std::fs::read_dir(&dir) else {
686 continue;
687 };
688 for e in entries.flatten() {
689 let p = e.path();
690 let ok_ext = matches!(
691 p.extension().and_then(|s| s.to_str()),
692 Some("spd") | Some("csv")
693 );
694 if !ok_ext {
695 continue;
696 }
697 let r = load(&p).unwrap_or_else(|e| panic!("{}: {e}", p.display()));
698 assert!(
699 !r.spd.wavelengths.is_empty() && r.spd.values.len() == r.spd.wavelengths.len(),
700 "{}: empty or mismatched SPD",
701 p.display()
702 );
703 if sub == "Signify" {
704 let m = r
705 .reference
706 .as_ref()
707 .expect("Signify file must yield metrics");
708 assert!(m.cct_k.is_some(), "{}: missing CCT in prelude", p.display());
709 assert!(m.ra.is_some(), "{}: missing Ra in prelude", p.display());
710 }
711 total += 1;
712 }
713 }
714 assert!(total >= 20, "expected >=20 corpus files, found {total}");
715 }
716}