-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2335 lines (2140 loc) · 88.2 KB
/
Copy pathmain.py
File metadata and controls
2335 lines (2140 loc) · 88.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Auto-merged single-file MaixPy app from local modules.
# Source modules: soft_i2c_gpio.py, as7341_driver.py, spectrometer_ui.py, as7341_spectrometer_maixcam2.py
import math
try:
import socket
except Exception:
import usocket as socket
try:
import json
except Exception:
try:
import ujson as json
except Exception:
json = None
# ===== soft_i2c_gpio.py =====
try:
from maix import err, gpio, pinmap, time
except Exception:
err = None
gpio = None
pinmap = None
time = None
class SoftI2CError(Exception):
pass
class SoftI2C:
"""Small GPIO bit-banged I2C master for MaixPy.
The MaixCAM2 pins used in this project, B20/B19, are SPI pins on the
connector diagram, so hardware I2C is not assumed. Both lines are driven as
open-drain outputs and released high for ACK/read phases.
"""
def __init__(self, scl_pin="B20", sda_pin="B19", freq=80000):
if gpio is None or pinmap is None or time is None:
raise SoftI2CError("This module must run inside MaixPy")
self.scl_pin = scl_pin
self.sda_pin = sda_pin
self.freq = max(10000, min(150000, int(freq)))
self.delay_us = max(2, int(500000 // self.freq))
self.scl_name = self._setup_gpio_pin(scl_pin)
self.sda_name = self._setup_gpio_pin(sda_pin)
self.scl = gpio.GPIO(self.scl_name, gpio.Mode.OUT_OD, gpio.Pull.PULL_UP)
self.sda = gpio.GPIO(self.sda_name, gpio.Mode.OUT_OD, gpio.Pull.PULL_UP)
self.release()
def _setup_gpio_pin(self, pin):
names = self._candidate_gpio_names(pin)
last_error = None
for name in names:
try:
result = pinmap.set_pin_function(pin, name)
if err is not None and result is not None:
err.check_raise(result, "set pin failed")
return name
except Exception as exc:
last_error = exc
if last_error:
raise SoftI2CError("set pin function failed: %s -> %s" % (pin, names))
return pin
def _candidate_gpio_names(self, pin):
if pin.startswith("GPIO"):
return [pin]
bank = pin[0]
num = pin[1:]
names = []
if bank in ("A", "B", "C", "D") and num:
names.append("GPIO%s%s" % (bank, num))
names.append(pin)
return names
def _sleep(self):
time.sleep_us(self.delay_us)
def _set_scl(self, value):
self.scl.value(1 if value else 0)
def _set_sda(self, value):
self.sda.value(1 if value else 0)
def _read_scl(self):
return 1 if self.scl.value() else 0
def _read_sda(self):
return 1 if self.sda.value() else 0
def release(self):
self._set_sda(1)
self._set_scl(1)
self._sleep()
def _clock_high(self):
self._set_scl(1)
timeout = 500
while not self._read_scl() and timeout > 0:
time.sleep_us(1)
timeout -= 1
if timeout <= 0:
raise SoftI2CError("SCL held low")
self._sleep()
def start(self):
self._set_sda(1)
self._clock_high()
self._set_sda(0)
self._sleep()
self._set_scl(0)
self._sleep()
def stop(self):
self._set_sda(0)
self._sleep()
self._clock_high()
self._set_sda(1)
self._sleep()
def write_byte(self, value):
value &= 0xFF
for bit in range(7, -1, -1):
self._set_sda((value >> bit) & 1)
self._sleep()
self._clock_high()
self._set_scl(0)
self._sleep()
self._set_sda(1)
self._sleep()
self._clock_high()
ack = self._read_sda() == 0
self._set_scl(0)
self._sleep()
return ack
def read_byte(self, ack=True):
value = 0
self._set_sda(1)
for _ in range(8):
value <<= 1
self._clock_high()
if self._read_sda():
value |= 1
self._set_scl(0)
self._sleep()
self._set_sda(0 if ack else 1)
self._sleep()
self._clock_high()
self._set_scl(0)
self._set_sda(1)
self._sleep()
return value
def writeto(self, address, data):
self.start()
try:
if not self.write_byte((address << 1) | 0):
raise SoftI2CError("I2C address 0x%02X did not ACK write" % address)
for value in data:
if not self.write_byte(value):
raise SoftI2CError("I2C data byte did not ACK")
finally:
self.stop()
def readfrom(self, address, length):
self.start()
try:
if not self.write_byte((address << 1) | 1):
raise SoftI2CError("I2C address 0x%02X did not ACK read" % address)
out = []
for index in range(length):
out.append(self.read_byte(ack=index < length - 1))
return out
finally:
self.stop()
def write_reg(self, address, reg, values):
if isinstance(values, int):
values = [values]
self.writeto(address, [reg & 0xFF] + [v & 0xFF for v in values])
def read_reg(self, address, reg, length=1):
self.start()
try:
if not self.write_byte((address << 1) | 0):
raise SoftI2CError("I2C address 0x%02X did not ACK register write" % address)
if not self.write_byte(reg & 0xFF):
raise SoftI2CError("I2C register 0x%02X did not ACK" % reg)
self.start()
if not self.write_byte((address << 1) | 1):
raise SoftI2CError("I2C address 0x%02X did not ACK register read" % address)
out = []
for index in range(length):
out.append(self.read_byte(ack=index < length - 1))
return out
finally:
self.stop()
def scan(self, start=0x08, end=0x78):
found = []
for address in range(start, end):
try:
self.start()
if self.write_byte((address << 1) | 0):
found.append(address)
except Exception:
pass
finally:
self.stop()
return found
# ===== as7341_driver.py =====
try:
from maix import time
except Exception:
time = None
class AS7341Error(Exception):
pass
def _make_nm_grid(start, end, step):
count = int(round((float(end) - float(start)) / float(step))) + 1
return [round(float(start) + i * float(step), 1) for i in range(count)]
class AS7341:
ADDRESS = 0x39
REG_CONFIG = 0x70
REG_STAT = 0x71
REG_ENABLE = 0x80
REG_ATIME = 0x81
REG_ID = 0x92
REG_STATUS = 0x93
REG_ASTATUS = 0x94
REG_CH0_DATA = 0x95
REG_STATUS2 = 0xA3
REG_CFG0 = 0xA9
REG_CFG1 = 0xAA
REG_CFG6 = 0xAF
REG_CFG8 = 0xB1
REG_ASTEP_L = 0xCA
REG_ASTEP_H = 0xCB
REG_AZ_CONFIG = 0xD6
ENABLE_PON = 0x01
ENABLE_SP_EN = 0x02
ENABLE_SMUXEN = 0x10
GAIN_STEPS = [
(0, 0.5),
(1, 1),
(2, 2),
(3, 4),
(4, 8),
(5, 16),
(6, 32),
(7, 64),
(8, 128),
(9, 256),
(10, 512),
]
CHANNELS = [
("F1", 415),
("F2", 445),
("F3", 480),
("F4", 515),
("F5", 555),
("F6", 590),
("F7", 630),
("F8", 680),
("Clear", 0),
("NIR", 910),
]
SPECTRAL_BANDS = [
(415, 26, 55),
(445, 30, 110),
(480, 36, 210),
(515, 39, 390),
(555, 39, 590),
(590, 40, 840),
(630, 50, 1350),
(680, 52, 1070),
]
CLEAR_BAND = (560, 420, 1750)
NIR_BAND = (910, 90, 112)
GRID_STEP_NM = 0.1
RESPONSE_EPS = 1e-7
INVERSE_ITERATIONS = 10
SMOOTH_RADIUS_NM = 1.2
SMOOTH_BLEND = 0.55
SUPPORT_PRIOR_STRENGTH = 0.18
SUPPORT_PRIOR_FLOOR = 0.06
PEAK_SUPPORT_MIN = 0.12
OVERLAP_BRIDGE_STRENGTH = 0.0
UW_CM2_TO_W_M2 = 0.01
LUX_OUTPUT_CALIBRATION = 0.5
CLEAR_LUX_CALIBRATION = 6.83
REF_VISIBLE_EE_UW_CM2 = 107.67
REF_VISIBLE_INTEGRATION_MS = 27.8
REF_NIR_EE_UW_CM2 = 98.0
REF_NIR_INTEGRATION_MS = 100.0
REF_NIR_GAIN_RATIO_64X = 2.0
NIR_940_RESPONSIVITY_COUNTS = 5135.0
OPTICAL_GAIN_RATIOS_64X = [0.008, 0.016, 0.032, 0.065, 0.125, 0.25, 0.5, 1.0, 2.0, 3.95, 7.75]
CHANNEL_IRRADIANCE_CALIBRATION = (0.077272, 0.336348, 0.225688, 0.370326, 0.515721, 0.684158, 1.0, 0.83031, 1.0, 1.0)
SPECTRUM_GRID = _make_nm_grid(380.0, 780.0, GRID_STEP_NM)
IR_GRID = _make_nm_grid(760.0, 1000.0, GRID_STEP_NM)
_VISIBLE_MODEL_CACHE = None
_CLEAR_ROW_CACHE = None
_IR_SHAPE_CACHE = None
_PHOTOPIC_WEIGHT_CACHE = None
LOW_SMUX = [
(0x00, 0x30),
(0x01, 0x01),
(0x02, 0x00),
(0x03, 0x00),
(0x04, 0x00),
(0x05, 0x42),
(0x06, 0x00),
(0x07, 0x00),
(0x08, 0x50),
(0x09, 0x00),
(0x0A, 0x00),
(0x0B, 0x00),
(0x0C, 0x20),
(0x0D, 0x04),
(0x0E, 0x00),
(0x0F, 0x30),
(0x10, 0x01),
(0x11, 0x50),
(0x12, 0x00),
(0x13, 0x06),
]
HIGH_SMUX = [
(0x00, 0x00),
(0x01, 0x00),
(0x02, 0x00),
(0x03, 0x40),
(0x04, 0x02),
(0x05, 0x00),
(0x06, 0x10),
(0x07, 0x03),
(0x08, 0x50),
(0x09, 0x10),
(0x0A, 0x03),
(0x0B, 0x00),
(0x0C, 0x00),
(0x0D, 0x00),
(0x0E, 0x24),
(0x0F, 0x00),
(0x10, 0x00),
(0x11, 0x50),
(0x12, 0x00),
(0x13, 0x06),
]
def __init__(self, bus, address=ADDRESS):
self.bus = bus
self.address = address
self.atime = 29
self.astep = 599
self.gain_index = 8
self.dark = [0] * len(self.CHANNELS)
self.last_sample = None
def begin(self):
device_id = self.read8(self.REG_ID)
if ((device_id >> 2) & 0x3F) != 0x09:
raise AS7341Error("AS7341 not found, ID register=0x%02X" % device_id)
self.write8(self.REG_ENABLE, self.ENABLE_PON)
self.sleep_ms(5)
self.write_low8(self.REG_CONFIG, 0x00)
self.set_integration(50)
self.set_gain_index(self.gain_index)
self.write8(self.REG_AZ_CONFIG, 0xFF)
self.write8(self.REG_CFG8, 0x00)
self.clear_status()
return True
def sleep_ms(self, ms):
if time:
time.sleep_ms(int(ms))
def ticks_ms(self):
if time:
return time.ticks_ms()
return 0
def write8(self, reg, value):
self.bus.write_reg(self.address, reg, value & 0xFF)
def read8(self, reg):
return self.bus.read_reg(self.address, reg, 1)[0]
def read_block(self, reg, length):
return self.bus.read_reg(self.address, reg, length)
def write16(self, reg, value):
self.bus.write_reg(self.address, reg, [value & 0xFF, (value >> 8) & 0xFF])
def _set_low_register_bank(self, enabled):
cfg0 = self.read8(self.REG_CFG0)
if enabled:
cfg0 |= 0x10
else:
cfg0 &= ~0x10
self.write8(self.REG_CFG0, cfg0)
def write_low8(self, reg, value):
self._set_low_register_bank(True)
try:
self.write8(reg, value)
finally:
self._set_low_register_bank(False)
def read_low8(self, reg):
self._set_low_register_bank(True)
try:
return self.read8(reg)
finally:
self._set_low_register_bank(False)
def clear_status(self):
try:
status = self.read8(self.REG_STATUS)
if status:
self.write8(self.REG_STATUS, status)
except SoftI2CError:
raise
except Exception:
pass
def set_gain_index(self, index):
index = max(0, min(len(self.GAIN_STEPS) - 1, int(index)))
self.gain_index = index
self.write8(self.REG_CFG1, self.GAIN_STEPS[index][0])
def gain_value(self):
return self.GAIN_STEPS[self.gain_index][1]
def optical_gain_ratio_64x(self):
if self.gain_index < len(self.OPTICAL_GAIN_RATIOS_64X):
return self.OPTICAL_GAIN_RATIOS_64X[self.gain_index]
return max(0.001, float(self.gain_value()) / 64.0)
def set_integration_registers(self, atime, astep):
atime = max(0, min(255, int(atime)))
astep = max(1, min(65534, int(astep)))
self.atime = atime
self.astep = astep
self.write8(self.REG_ATIME, atime)
self.write16(self.REG_ASTEP_L, astep)
def set_integration(self, integration_ms):
integration_ms = max(5, min(1000, int(integration_ms)))
astep = 599
atime = int((integration_ms * 1000.0) / ((astep + 1) * 2.78) - 1)
if atime > 255:
atime = 255
astep = int((integration_ms * 1000.0) / ((atime + 1) * 2.78) - 1)
self.set_integration_registers(atime, astep)
def integration_ms(self):
return (self.atime + 1) * (self.astep + 1) * 0.00278
def adc_full_scale(self):
return min(65535, (self.atime + 1) * (self.astep + 1))
def _set_sp_en(self, enabled):
value = self.read8(self.REG_ENABLE)
if enabled:
value |= self.ENABLE_SP_EN | self.ENABLE_PON
else:
value &= ~self.ENABLE_SP_EN
value |= self.ENABLE_PON
self.write8(self.REG_ENABLE, value)
def _write_smux(self, table):
self._set_sp_en(False)
self.write8(self.REG_CFG0, 0x00)
for reg, value in table:
self.write8(reg, value)
self.write8(self.REG_CFG6, 0x10)
value = self.read8(self.REG_ENABLE)
self.write8(self.REG_ENABLE, (value | self.ENABLE_SMUXEN | self.ENABLE_PON) & ~self.ENABLE_SP_EN)
start = self.ticks_ms()
while self.read8(self.REG_ENABLE) & self.ENABLE_SMUXEN:
if self.ticks_ms() - start > 250:
raise AS7341Error("SMUX command timeout")
self.sleep_ms(1)
def _read_adc_once(self, table):
self._write_smux(table)
self.clear_status()
self._set_sp_en(True)
timeout = max(250, int(self.integration_ms() + 80))
start = self.ticks_ms()
while True:
status2 = self.read8(self.REG_STATUS2)
if status2 & 0x40:
break
if self.ticks_ms() - start > timeout:
self._set_sp_en(False)
raise AS7341Error("spectral data timeout")
self.sleep_ms(1)
raw = self.read_block(self.REG_ASTATUS, 13)
self._set_sp_en(False)
values = []
for index in range(6):
lo = raw[1 + index * 2]
hi = raw[2 + index * 2]
values.append(lo | (hi << 8))
return raw[0], values
def read_raw(self):
status_low, low = self._read_adc_once(self.LOW_SMUX)
status_high, high = self._read_adc_once(self.HIGH_SMUX)
values = [
low[0],
low[1],
low[2],
low[3],
high[0],
high[1],
high[2],
high[3],
int((low[4] + high[4]) / 2),
int((low[5] + high[5]) / 2),
]
sample = {
"raw": values,
"status_low": status_low,
"status_high": status_high,
"saturated": bool((status_low | status_high) & 0x80),
"gain": self.gain_value(),
"gain_index": self.gain_index,
"integration_ms": self.integration_ms(),
"full_scale": self.adc_full_scale(),
}
sample["corrected"] = self.apply_dark(values)
sample["normalized"] = self.normalize(sample["corrected"])
sample["basic_counts"] = self.basic_counts(sample["corrected"])
sample["datasheet_irradiance_uW_cm2"] = self.irradiance_uW_cm2(sample["corrected"], calibrated=False)
sample["irradiance_uW_cm2"] = self.apply_irradiance_calibration(sample["datasheet_irradiance_uW_cm2"])
sample["spectrum"] = self.reconstruct_spectrum(sample["corrected"], sample["irradiance_uW_cm2"])
sample["peak"] = self.peak_channel(sample["corrected"])
self.last_sample = sample
return sample
def apply_dark(self, values):
return [max(0, int(v) - int(d)) for v, d in zip(values, self.dark)]
def normalize(self, values):
max_value = max(max(values), 1)
return [v / max_value for v in values]
def basic_counts(self, corrected):
exposure_scale = self._visible_exposure_scale()
return [max(0.0, float(value)) / exposure_scale for value in corrected]
def irradiance_uW_cm2(self, corrected, calibrated=True):
out = []
for index, value in enumerate(corrected):
out.append(self._channel_irradiance_uW_cm2(index, value))
if calibrated:
return self.apply_irradiance_calibration(out)
return out
def apply_irradiance_calibration(self, values):
out = []
for index, value in enumerate(values):
factor = self.CHANNEL_IRRADIANCE_CALIBRATION[index] if index < len(self.CHANNEL_IRRADIANCE_CALIBRATION) else 1.0
out.append(max(0.0, float(value)) * factor)
return out
def _visible_exposure_scale(self):
return max(
1e-9,
self.optical_gain_ratio_64x() * self.integration_ms() / self.REF_VISIBLE_INTEGRATION_MS,
)
def _channel_irradiance_uW_cm2(self, index, corrected_value):
corrected_value = max(0.0, float(corrected_value))
if index < 8:
reference_counts = float(self.SPECTRAL_BANDS[index][2])
exposure_scale = self._visible_exposure_scale()
return corrected_value * self.REF_VISIBLE_EE_UW_CM2 / max(1e-12, reference_counts * exposure_scale)
if index == 8:
reference_counts = float(self.CLEAR_BAND[2])
exposure_scale = self._visible_exposure_scale()
return corrected_value * self.REF_VISIBLE_EE_UW_CM2 / max(1e-12, reference_counts * exposure_scale)
if index == 9:
exposure_scale = (
self.optical_gain_ratio_64x()
/ self.REF_NIR_GAIN_RATIO_64X
* self.integration_ms()
/ self.REF_NIR_INTEGRATION_MS
)
return corrected_value * self.REF_NIR_EE_UW_CM2 / max(1e-12, self.NIR_940_RESPONSIVITY_COUNTS * exposure_scale)
return 0.0
def peak_channel(self, values):
visible = values[:8]
index = visible.index(max(visible)) if visible else 0
name, wavelength = self.CHANNELS[index]
return {"name": name, "wavelength": wavelength, "value": visible[index]}
def reconstruct_spectrum(self, corrected, irradiance=None):
grid = self.SPECTRUM_GRID
bands = self.SPECTRAL_BANDS
if irradiance is None:
irradiance = self.irradiance_uW_cm2(corrected)
measured = [irradiance[i] for i in range(8)]
exposure = self._visible_exposure_scale()
y = [max(0.0, float(v)) for v in measured]
if max(y) <= 0:
empty = self._empty_spectrum(grid)
lux_est, clear_lux_signal = self._estimate_lux_from_clear(corrected, irradiance)
empty["lux_est"] = lux_est
empty["clear_lux_signal"] = clear_lux_signal
empty["clear_irradiance_uW_cm2"] = clear_lux_signal
empty["lux_source"] = "clear_fallback"
empty["ir"] = self._reconstruct_ir(corrected, exposure)
return empty
ycorr = list(y)
model = self._visible_model()
rows = model["rows"]
inv_denominator = model["inv_denominator"]
support_prior = model["support_prior"]
peak_support = model["peak_support"]
x = self._initial_spectrum(rows, ycorr, grid, inv_denominator, support_prior)
for _ in range(self.INVERSE_ITERATIONS):
x = self._multiplicative_update(x, rows, ycorr, inv_denominator, support_prior)
x = self._smooth_spectrum(x)
x = self._apply_overlap_bridge_prior(x, grid, bands)
x = self._apply_clear_constraint(x, irradiance[8] if len(irradiance) > 8 else 0.0, grid)
prediction = self._predict_channels(x, rows)
fit_error = self._fit_error(prediction, ycorr)
summary = self._spectrum_summary(grid, x, corrected, fit_error, exposure, peak_support, irradiance)
summary["peaks"] = self._find_spectrum_peaks(grid, summary["values"], peak_support, limit=5)
summary["photon_peaks"] = self._find_spectrum_peaks(grid, summary["photon_values"], peak_support, limit=5)
summary["ir"] = self._reconstruct_ir(corrected, exposure)
return summary
def _empty_spectrum(self, grid):
return {
"grid": list(grid),
"values": [0.0 for _ in grid],
"power": [0.0 for _ in grid],
"photon_values": [0.0 for _ in grid],
"photon_power": [0.0 for _ in grid],
"photon_integral": 0.0,
"dominant_nm": 0,
"centroid_nm": 0,
"photon_dominant_nm": 0,
"photon_centroid_nm": 0,
"lux_est": 0.0,
"clear_lux_signal": 0.0,
"clear_irradiance_uW_cm2": 0.0,
"lux_source": "spd_photopic",
"cct_est": 0,
"nir_ratio": 0.0,
"clear_ratio": 0.0,
"fit_confidence": 0.0,
"peaks": [],
"photon_peaks": [],
"ir": {
"grid": list(self.IR_GRID),
"values": [0.0 for _ in self.IR_GRID],
"power": [0.0 for _ in self.IR_GRID],
"peak_nm": 0,
"relative": 0.0,
},
}
def _response_row(self, center, fwhm, grid):
sigma = max(1.0, float(fwhm) / 2.355)
row = []
total = 0.0
for wavelength in grid:
value = math.exp(-0.5 * ((float(wavelength) - center) / sigma) ** 2)
row.append(value)
total += value
if total <= 0:
return [0.0 for _ in grid]
return [value / total for value in row]
def _visible_model(self):
cached = AS7341._VISIBLE_MODEL_CACHE
if cached:
return cached
grid = self.SPECTRUM_GRID
size = len(grid)
rows = []
denominator = [0.0] * size
for channel_index, band in enumerate(self.SPECTRAL_BANDS):
center, fwhm, _ = band
start, weights = self._sparse_response_row(center, fwhm, grid)
rows.append((start, weights))
for offset, weight in enumerate(weights):
denominator[start + offset] += weight
inv_denominator = []
for value in denominator:
inv_denominator.append(1.0 / value if value > 1e-12 else 0.0)
cached = {
"rows": rows,
"inv_denominator": inv_denominator,
"support_prior": self._support_prior(denominator),
"peak_support": self._peak_support(denominator),
}
AS7341._VISIBLE_MODEL_CACHE = cached
return cached
def _peak_support(self, denominator):
max_value = max(max(denominator), 1e-12)
return [max(0.0, min(1.0, value / max_value)) for value in denominator]
def _support_prior(self, denominator):
support = self._peak_support(denominator)
floor = self.SUPPORT_PRIOR_FLOOR
return [floor + (1.0 - floor) * (value ** 0.65) for value in support]
def _sparse_response_row(self, center, fwhm, grid, channel_index=None):
sigma = max(1.0, float(fwhm) / 2.355)
raw = []
total = 0.0
for wavelength in grid:
value = math.exp(-0.5 * ((float(wavelength) - center) / sigma) ** 2)
raw.append(value)
total += value
return self._sparsify_response_row(raw)
def _sparsify_response_row(self, raw):
total = sum(raw)
if total <= 0:
return 0, []
threshold = total * self.RESPONSE_EPS
start = 0
end = len(raw) - 1
while start <= end and raw[start] <= threshold:
start += 1
while end >= start and raw[end] <= threshold:
end -= 1
if start > end:
return 0, []
return start, [raw[index] / total for index in range(start, end + 1)]
def _initial_spectrum(self, rows, ycorr, grid, inv_denominator, support_prior):
out = [0.0] * len(grid)
for row_index, item in enumerate(rows):
start, weights = item
scale = ycorr[row_index]
if scale <= 0:
continue
for offset, weight in enumerate(weights):
out[start + offset] += weight * scale
for index, value in enumerate(out):
inv = inv_denominator[index]
out[index] = value * inv if inv > 0 else 0.0
out = self._apply_support_prior(out, support_prior)
return self._smooth_spectrum(out)
def _multiplicative_update(self, spectrum, rows, ycorr, inv_denominator, support_prior):
prediction = self._predict_channels(spectrum, rows)
numerator = [0.0] * len(spectrum)
for row_index, item in enumerate(rows):
start, weights = item
ratio = ycorr[row_index] / max(prediction[row_index], 1e-12)
if ratio <= 0:
continue
for offset, weight in enumerate(weights):
numerator[start + offset] += weight * ratio
updated = [0.0] * len(spectrum)
for index, value in enumerate(spectrum):
inv = inv_denominator[index]
factor = numerator[index] * inv if inv > 0 else 1.0
if factor <= 0 or value <= 0:
updated[index] = 0.0
else:
updated[index] = value * factor
return self._apply_support_prior(updated, support_prior)
def _apply_support_prior(self, spectrum, support_prior):
strength = self.SUPPORT_PRIOR_STRENGTH
if strength <= 0 or not support_prior:
return spectrum
keep = 1.0 - strength
return [value * (keep + strength * support_prior[index]) for index, value in enumerate(spectrum)]
def _apply_overlap_bridge_prior(self, spectrum, grid, bands):
strength = self.OVERLAP_BRIDGE_STRENGTH
if strength <= 0 or len(spectrum) != len(grid) or len(grid) < 2:
return spectrum
out = list(spectrum)
step = max(0.001, float(grid[1]) - float(grid[0]))
for index in range(len(bands) - 1):
left_nm = float(bands[index][0])
right_nm = float(bands[index + 1][0])
if right_nm <= left_nm:
continue
left_idx = int(round((left_nm - grid[0]) / step))
right_idx = int(round((right_nm - grid[0]) / step))
left_idx = max(0, min(len(out) - 1, left_idx))
right_idx = max(0, min(len(out) - 1, right_idx))
if right_idx <= left_idx + 1:
continue
left_value = max(0.0, float(out[left_idx]))
right_value = max(0.0, float(out[right_idx]))
if left_value <= 0 or right_value <= 0:
continue
for pos in range(left_idx + 1, right_idx):
mix = float(pos - left_idx) / float(right_idx - left_idx)
bridge = left_value * (1.0 - mix) + right_value * mix
floor = bridge * strength
if out[pos] < floor:
out[pos] = floor
return out
def _predict_channels(self, spectrum, rows):
prediction = []
for item in rows:
start, weights = item
total = 0.0
for offset, weight in enumerate(weights):
total += weight * spectrum[start + offset]
prediction.append(total)
return prediction
def _smooth_spectrum(self, spectrum):
if len(spectrum) < 3:
return spectrum
radius = int(round(self.SMOOTH_RADIUS_NM / max(self.GRID_STEP_NM, 0.1)))
if radius <= 1:
out = [0.0] * len(spectrum)
out[0] = spectrum[0]
for index in range(1, len(spectrum) - 1):
out[index] = 0.22 * spectrum[index - 1] + 0.56 * spectrum[index] + 0.22 * spectrum[index + 1]
out[-1] = spectrum[-1]
return out
prefix = [0.0]
total = 0.0
for value in spectrum:
total += value
prefix.append(total)
out = [0.0] * len(spectrum)
blend = self.SMOOTH_BLEND
keep = 1.0 - blend
last = len(spectrum) - 1
for index, value in enumerate(spectrum):
start = max(0, index - radius)
end = min(last, index + radius)
avg = (prefix[end + 1] - prefix[start]) / (end - start + 1)
out[index] = keep * value + blend * avg
return out
def _apply_clear_constraint(self, spectrum, clear_irradiance, grid):
clear_y = max(0.0, float(clear_irradiance))
if clear_y <= 0:
return spectrum
clear_row = self._clear_row(grid)
predicted = 0.0
for index, value in enumerate(spectrum):
predicted += clear_row[index] * value
if predicted <= 1e-12:
return spectrum
factor = clear_y / predicted
factor = max(0.55, min(1.85, factor))
return [value * factor for value in spectrum]
def _clear_row(self, grid):
cached = AS7341._CLEAR_ROW_CACHE
if cached and len(cached) == len(grid):
return cached
cached = self._response_row(self.CLEAR_BAND[0], self.CLEAR_BAND[1], grid)
AS7341._CLEAR_ROW_CACHE = cached
return cached
def _fit_error(self, prediction, ycorr):
ref = max(max(ycorr), 1e-12)
total = 0.0
for index, value in enumerate(ycorr):
total += abs(prediction[index] - value) / (abs(value) + ref * 0.05)
return total / max(1, len(ycorr))
def _spectrum_summary(self, grid, power, corrected, fit_error, exposure, peak_support=None, irradiance=None):
max_power = max(max(power), 1e-12)
values = [value / max_power for value in power]
photon_power = []
for wavelength, value in zip(grid, power):
photon_power.append(max(0.0, float(value)) * max(0.0, float(wavelength)))
max_photon = max(max(photon_power), 1e-12)
photon_values = [value / max_photon for value in photon_power]
delta_nm = abs(float(grid[1]) - float(grid[0])) if len(grid) > 1 else 1.0
photon_integral = sum(photon_power) * delta_nm
visible_pairs = [(w, p) for w, p in zip(grid, power) if w <= 780]
photon_pairs = [(w, p) for w, p in zip(grid, photon_power) if w <= 780]
visible_total = sum([p for _, p in visible_pairs])
if visible_total > 0:
centroid = sum([w * p for w, p in visible_pairs]) / visible_total
dominant_nm = 0
dominant_power = -1.0
for index, item in enumerate(visible_pairs):
wavelength, value = item
if peak_support and index < len(peak_support) and peak_support[index] < self.PEAK_SUPPORT_MIN:
continue
if value > dominant_power:
dominant_nm = wavelength
dominant_power = value
if dominant_power < 0:
dominant_nm = visible_pairs[0][0]
else:
centroid = 0
dominant_nm = 0
photon_total = sum([p for _, p in photon_pairs])
if photon_total > 0:
photon_centroid = sum([w * p for w, p in photon_pairs]) / photon_total
photon_dominant_nm = 0
photon_dominant_power = -1.0
for index, item in enumerate(photon_pairs):
wavelength, value = item
if peak_support and index < len(peak_support) and peak_support[index] < self.PEAK_SUPPORT_MIN:
continue
if value > photon_dominant_power:
photon_dominant_nm = wavelength
photon_dominant_power = value
if photon_dominant_power < 0:
photon_dominant_nm = photon_pairs[0][0]
else:
photon_centroid = 0
photon_dominant_nm = 0
blue = sum([p for w, p in visible_pairs if w < 500])
green = sum([p for w, p in visible_pairs if w >= 500 and w < 600])
red = sum([p for w, p in visible_pairs if w >= 600])
cct = 0
if blue + green + red > 0:
cct = int(6500.0 * (blue + 0.35 * green) / max(red + 0.20 * green, 1e-12))
cct = max(1500, min(15000, cct))
visible_avg = sum(corrected[:8]) / 8.0 if corrected[:8] else 0.0
nir_ratio = float(corrected[9]) / max(1.0, visible_avg)
clear_ratio = float(corrected[8]) / max(1.0, visible_avg)
confidence = max(0.0, min(1.0, 1.0 - fit_error))
lux_est, clear_lux_signal = self._estimate_lux_from_spd(grid, power, corrected, exposure, irradiance)
return {
"grid": list(grid),
"values": values,
"power": power,
"photon_values": photon_values,
"photon_power": photon_power,
"photon_integral": photon_integral,
"dominant_nm": round(float(dominant_nm), 1),
"centroid_nm": round(float(centroid), 1),
"photon_dominant_nm": round(float(photon_dominant_nm), 1),
"photon_centroid_nm": round(float(photon_centroid), 1),
"lux_est": lux_est,
"clear_lux_signal": clear_lux_signal,
"clear_irradiance_uW_cm2": clear_lux_signal,
"lux_source": "spd_photopic",
"cct_est": int(cct),
"nir_ratio": nir_ratio,
"clear_ratio": clear_ratio,
"fit_confidence": confidence,
}
def _estimate_lux_from_clear(self, corrected, irradiance=None):
clear_signal = self._clear_lux_signal(corrected, irradiance)
lux_est = clear_signal * self.CLEAR_LUX_CALIBRATION * self.LUX_OUTPUT_CALIBRATION
return max(0.0, lux_est), clear_signal
def _clear_lux_signal(self, corrected, irradiance=None):
if irradiance and len(irradiance) > 8:
return max(0.0, float(irradiance[8]))
clear_value = float(corrected[8]) if len(corrected) > 8 else 0.0
return self._channel_irradiance_uW_cm2(8, clear_value)
def _estimate_lux_from_spd(self, grid, power, corrected, exposure, irradiance=None):
clear_signal = self._clear_lux_signal(corrected, irradiance)
weights = self._photopic_weights(grid)
total = 0.0
weight_total = 0.0
for index, value in enumerate(power):
if index >= len(weights):