@photivra/engine 2.17.0 → 2.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +116 -1
- package/CITATION.cff +1 -1
- package/README.md +6 -6
- package/SECURITY.md +1 -1
- package/dist/camera/sensor-equivalence.d.ts +156 -0
- package/dist/camera/sensor-equivalence.js +208 -0
- package/dist/camera/sensor-equivalence.js.map +1 -0
- package/dist/capture/focus-control.js +2 -75
- package/dist/capture/focus-control.js.map +1 -1
- package/dist/capture/native-environment-lean.d.ts +1 -0
- package/dist/capture/native-environment-lean.js +1 -1
- package/dist/capture/native-environment-lean.js.map +1 -1
- package/dist/capture/native-environment-optical-stage.d.ts +1 -0
- package/dist/capture/native-environment-optical-stage.js +2 -5
- package/dist/capture/native-environment-optical-stage.js.map +1 -1
- package/dist/capture/native-environment-raw.js +1 -5
- package/dist/capture/native-environment-raw.js.map +1 -1
- package/dist/capture/native-environment-tabulated.d.ts +5 -0
- package/dist/capture/native-environment-tabulated.js +1 -1
- package/dist/capture/native-environment-tabulated.js.map +1 -1
- package/dist/capture/release-sequence.js +2 -47
- package/dist/capture/release-sequence.js.map +1 -1
- package/dist/color/white-balance.d.ts +2 -0
- package/dist/color/white-balance.js +3 -56
- package/dist/color/white-balance.js.map +1 -1
- package/dist/composition/image-formation-plan.d.ts +1 -0
- package/dist/composition/image-formation-plan.js +3 -49
- package/dist/composition/image-formation-plan.js.map +1 -1
- package/dist/core/evidence-provenance.js +1 -16
- package/dist/core/evidence-provenance.js.map +1 -1
- package/dist/core/record-validation.d.ts +54 -0
- package/dist/core/record-validation.js +176 -0
- package/dist/core/record-validation.js.map +1 -1
- package/dist/core/scientific-assurance.js +1 -18
- package/dist/core/scientific-assurance.js.map +1 -1
- package/dist/core/shared-helpers.d.ts +33 -0
- package/dist/core/shared-helpers.js +34 -0
- package/dist/core/shared-helpers.js.map +1 -0
- package/dist/core/spectral-composition.js +1 -36
- package/dist/core/spectral-composition.js.map +1 -1
- package/dist/core/spectral.js +1 -19
- package/dist/core/spectral.js.map +1 -1
- package/dist/core/version.d.ts +1 -1
- package/dist/core/version.js +1 -1
- package/dist/core/version.js.map +1 -1
- package/dist/equipment/exposure-capabilities.d.ts +1 -0
- package/dist/equipment/exposure-capabilities.js +2 -36
- package/dist/equipment/exposure-capabilities.js.map +1 -1
- package/dist/equipment/ideal-lens.d.ts +25 -0
- package/dist/equipment/ideal-lens.js +21 -0
- package/dist/equipment/ideal-lens.js.map +1 -0
- package/dist/equipment/iso-capabilities.js +2 -49
- package/dist/equipment/iso-capabilities.js.map +1 -1
- package/dist/equipment/metering-capabilities.js +1 -26
- package/dist/equipment/metering-capabilities.js.map +1 -1
- package/dist/equipment/release-capabilities.js +1 -53
- package/dist/equipment/release-capabilities.js.map +1 -1
- package/dist/exposure/auto-iso-slowest-shutter.js +1 -7
- package/dist/exposure/auto-iso-slowest-shutter.js.map +1 -1
- package/dist/exposure/exposure-duration-control.js +1 -16
- package/dist/exposure/exposure-duration-control.js.map +1 -1
- package/dist/exposure/exposure-mode-resolver.js +1 -17
- package/dist/exposure/exposure-mode-resolver.js.map +1 -1
- package/dist/exposure/filtered-exposure-time.d.ts +93 -0
- package/dist/exposure/filtered-exposure-time.js +129 -0
- package/dist/exposure/filtered-exposure-time.js.map +1 -0
- package/dist/exposure/flash-ttl.d.ts +1 -0
- package/dist/exposure/flash-ttl.js +1 -1
- package/dist/exposure/flash-ttl.js.map +1 -1
- package/dist/exposure/flash.js +1 -49
- package/dist/exposure/flash.js.map +1 -1
- package/dist/exposure/metering-scene-radiance.js +1 -25
- package/dist/exposure/metering-scene-radiance.js.map +1 -1
- package/dist/exposure/metering-target.js +1 -30
- package/dist/exposure/metering-target.js.map +1 -1
- package/dist/exposure/metering-temporal.js +1 -8
- package/dist/exposure/metering-temporal.js.map +1 -1
- package/dist/exposure/metering.js +1 -72
- package/dist/exposure/metering.js.map +1 -1
- package/dist/exposure/program-line.js +1 -45
- package/dist/exposure/program-line.js.map +1 -1
- package/dist/facade/catalogue-lens-signal.d.ts +94 -0
- package/dist/facade/catalogue-lens-signal.js +362 -0
- package/dist/facade/catalogue-lens-signal.js.map +1 -0
- package/dist/facade/defocus-image-space-provider.js +5 -2
- package/dist/facade/defocus-image-space-provider.js.map +1 -1
- package/dist/facade/develop-joined-parts.d.ts +29 -0
- package/dist/facade/develop-joined-parts.js +33 -0
- package/dist/facade/develop-joined-parts.js.map +1 -0
- package/dist/facade/display-view-lens-signal.d.ts +32 -1
- package/dist/facade/display-view-lens-signal.js +85 -10
- package/dist/facade/display-view-lens-signal.js.map +1 -1
- package/dist/facade/expected-signal-setup.d.ts +8 -0
- package/dist/facade/expected-signal-setup.js +7 -0
- package/dist/facade/expected-signal-setup.js.map +1 -1
- package/dist/facade/expected-signal.d.ts +5 -0
- package/dist/facade/expected-signal.js +5 -1
- package/dist/facade/expected-signal.js.map +1 -1
- package/dist/facade/generic-lens-capture.d.ts +5 -2
- package/dist/facade/generic-lens-capture.js +5 -2
- package/dist/facade/generic-lens-capture.js.map +1 -1
- package/dist/facade/simulate-capture.d.ts +67 -8
- package/dist/facade/simulate-capture.js +262 -126
- package/dist/facade/simulate-capture.js.map +1 -1
- package/dist/facade/simulate-display-view.js +1 -1
- package/dist/facade/simulate-display-view.js.map +1 -1
- package/dist/gpu/chart-composite-gpu.js +1 -3
- package/dist/gpu/chart-composite-gpu.js.map +1 -1
- package/dist/gpu/chart-radiance-gpu.js +1 -5
- package/dist/gpu/chart-radiance-gpu.js.map +1 -1
- package/dist/gpu/display-view-quality-gpu.d.ts +13 -1
- package/dist/gpu/display-view-quality-gpu.js +4 -8
- package/dist/gpu/display-view-quality-gpu.js.map +1 -1
- package/dist/gpu/display-view-speed-gpu.js +3 -25
- package/dist/gpu/display-view-speed-gpu.js.map +1 -1
- package/dist/gpu/sensor-stage-gpu.js +1 -5
- package/dist/gpu/sensor-stage-gpu.js.map +1 -1
- package/dist/gpu/webgpu-runtime.d.ts +2 -0
- package/dist/gpu/webgpu-runtime.js +3 -0
- package/dist/gpu/webgpu-runtime.js.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/motion/camera-rotation.js +1 -6
- package/dist/motion/camera-rotation.js.map +1 -1
- package/dist/motion/capture-rotation-inverse-mapping.d.ts +12 -0
- package/dist/motion/capture-rotation-inverse-mapping.js +2 -2
- package/dist/motion/capture-rotation-inverse-mapping.js.map +1 -1
- package/dist/motion/capture-rotation-temporal-quadrature.d.ts +1 -0
- package/dist/motion/capture-rotation-temporal-quadrature.js +1 -1
- package/dist/motion/capture-rotation-temporal-quadrature.js.map +1 -1
- package/dist/motion/capture-rotation-trajectory.js +2 -17
- package/dist/motion/capture-rotation-trajectory.js.map +1 -1
- package/dist/motion/capture-translation-parallax-temporal-quadrature.d.ts +1 -0
- package/dist/motion/capture-translation-parallax-temporal-quadrature.js +3 -14
- package/dist/motion/capture-translation-parallax-temporal-quadrature.js.map +1 -1
- package/dist/motion/extended-object-projection.js +5 -40
- package/dist/motion/extended-object-projection.js.map +1 -1
- package/dist/optics/atmospheric-haze.js +1 -7
- package/dist/optics/atmospheric-haze.js.map +1 -1
- package/dist/optics/brown-conrady-distortion.js +1 -7
- package/dist/optics/brown-conrady-distortion.js.map +1 -1
- package/dist/optics/complex-pupil-psf.d.ts +1 -0
- package/dist/optics/complex-pupil-psf.js +2 -84
- package/dist/optics/complex-pupil-psf.js.map +1 -1
- package/dist/optics/focus-state.js +1 -11
- package/dist/optics/focus-state.js.map +1 -1
- package/dist/optics/front-of-lens-filter.d.ts +5 -0
- package/dist/optics/front-of-lens-filter.js +3 -65
- package/dist/optics/front-of-lens-filter.js.map +1 -1
- package/dist/optics/generic-nd-filter-presets.d.ts +12 -0
- package/dist/optics/generic-nd-filter-presets.js +48 -0
- package/dist/optics/generic-nd-filter-presets.js.map +1 -0
- package/dist/optics/illumination-vignetting.js +1 -6
- package/dist/optics/illumination-vignetting.js.map +1 -1
- package/dist/optics/lens-psf-profile.d.ts +4 -1
- package/dist/optics/lens-psf-profile.js +12 -111
- package/dist/optics/lens-psf-profile.js.map +1 -1
- package/dist/optics/longitudinal-chromatic-aberration.js +1 -7
- package/dist/optics/longitudinal-chromatic-aberration.js.map +1 -1
- package/dist/optics/pupil-vignetting.js +1 -7
- package/dist/optics/pupil-vignetting.js.map +1 -1
- package/dist/optics/radial-distortion.js +1 -6
- package/dist/optics/radial-distortion.js.map +1 -1
- package/dist/optics/scene-to-sensor-irradiance.js +4 -96
- package/dist/optics/scene-to-sensor-irradiance.js.map +1 -1
- package/dist/optics/stray-light.d.ts +1 -0
- package/dist/optics/stray-light.js +1 -1
- package/dist/optics/stray-light.js.map +1 -1
- package/dist/optics/zernike-wavefront.js +1 -7
- package/dist/optics/zernike-wavefront.js.map +1 -1
- package/dist/output/capture-geometry.js +1 -8
- package/dist/output/capture-geometry.js.map +1 -1
- package/dist/output/developed-lens-corrections.d.ts +62 -0
- package/dist/output/developed-lens-corrections.js +135 -0
- package/dist/output/developed-lens-corrections.js.map +1 -0
- package/dist/output/generic-lens-corrections.d.ts +2 -6
- package/dist/output/generic-lens-corrections.js +3 -6
- package/dist/output/generic-lens-corrections.js.map +1 -1
- package/dist/output/geometric-transforms.js +1 -4
- package/dist/output/geometric-transforms.js.map +1 -1
- package/dist/output/native-capture-sdr.d.ts +2 -2
- package/dist/output/native-capture-sdr.js +3 -2
- package/dist/output/native-capture-sdr.js.map +1 -1
- package/dist/processing/development-detail.d.ts +29 -0
- package/dist/processing/development-detail.js +128 -107
- package/dist/processing/development-detail.js.map +1 -1
- package/dist/schema/illumination-temporal.js +3 -72
- package/dist/schema/illumination-temporal.js.map +1 -1
- package/dist/schema/illumination.d.ts +1 -0
- package/dist/schema/illumination.js +2 -65
- package/dist/schema/illumination.js.map +1 -1
- package/dist/schema/scene-radiance-temporal.js +2 -14
- package/dist/schema/scene-radiance-temporal.js.map +1 -1
- package/dist/schema/scene-radiance.js +2 -60
- package/dist/schema/scene-radiance.js.map +1 -1
- package/dist/schema/validation.d.ts +2 -0
- package/dist/schema/validation.js +2 -17
- package/dist/schema/validation.js.map +1 -1
- package/dist/sensor/accumulated-charge.js +2 -59
- package/dist/sensor/accumulated-charge.js.map +1 -1
- package/dist/sensor/architecture.js +1 -16
- package/dist/sensor/architecture.js.map +1 -1
- package/dist/sensor/camera-saturation-capacity.d.ts +1 -0
- package/dist/sensor/camera-saturation-capacity.js +3 -55
- package/dist/sensor/camera-saturation-capacity.js.map +1 -1
- package/dist/sensor/capture-color-sampling-binding.js +1 -26
- package/dist/sensor/capture-color-sampling-binding.js.map +1 -1
- package/dist/sensor/capture-mode-timing.js +1 -39
- package/dist/sensor/capture-mode-timing.js.map +1 -1
- package/dist/sensor/capture-mode.js +1 -23
- package/dist/sensor/capture-mode.js.map +1 -1
- package/dist/sensor/color-sampling.js +1 -26
- package/dist/sensor/color-sampling.js.map +1 -1
- package/dist/sensor/constant-rate-temporal-integration.js +2 -46
- package/dist/sensor/constant-rate-temporal-integration.js.map +1 -1
- package/dist/sensor/dark-current.js +2 -45
- package/dist/sensor/dark-current.js.map +1 -1
- package/dist/sensor/eqe-electron-rate.js +2 -35
- package/dist/sensor/eqe-electron-rate.js.map +1 -1
- package/dist/sensor/exposure-window.d.ts +5 -0
- package/dist/sensor/exposure-window.js +7 -22
- package/dist/sensor/exposure-window.js.map +1 -1
- package/dist/sensor/iso-gain.js +1 -7
- package/dist/sensor/iso-gain.js.map +1 -1
- package/dist/sensor/iso-signal-chain.js +1 -43
- package/dist/sensor/iso-signal-chain.js.map +1 -1
- package/dist/sensor/optical-stack.js +1 -25
- package/dist/sensor/optical-stack.js.map +1 -1
- package/dist/sensor/photon-energy.js +1 -26
- package/dist/sensor/photon-energy.js.map +1 -1
- package/dist/sensor/physical-charge-capacity.js +3 -77
- package/dist/sensor/physical-charge-capacity.js.map +1 -1
- package/dist/sensor/radiometry-readiness.js +2 -23
- package/dist/sensor/radiometry-readiness.js.map +1 -1
- package/dist/sensor/raw-readout.d.ts +3 -0
- package/dist/sensor/raw-readout.js +4 -66
- package/dist/sensor/raw-readout.js.map +1 -1
- package/dist/sensor/raw-reconstruction.js +2 -64
- package/dist/sensor/raw-reconstruction.js.map +1 -1
- package/dist/sensor/readout-exposure-linkage.js +1 -9
- package/dist/sensor/readout-exposure-linkage.js.map +1 -1
- package/dist/sensor/readout-timing.js +3 -57
- package/dist/sensor/readout-timing.js.map +1 -1
- package/dist/sensor/response-application-compatibility.d.ts +2 -0
- package/dist/sensor/response-application-compatibility.js +3 -29
- package/dist/sensor/response-application-compatibility.js.map +1 -1
- package/dist/sensor/response-operating-range.d.ts +1 -0
- package/dist/sensor/response-operating-range.js +3 -79
- package/dist/sensor/response-operating-range.js.map +1 -1
- package/dist/sensor/responsivity-photocurrent.js +4 -108
- package/dist/sensor/responsivity-photocurrent.js.map +1 -1
- package/dist/sensor/sampling-aperture.js +1 -25
- package/dist/sensor/sampling-aperture.js.map +1 -1
- package/dist/sensor/spatial-sample-reduction.js +2 -19
- package/dist/sensor/spatial-sample-reduction.js.map +1 -1
- package/dist/sensor/spatial-sampling-quadrature.js +1 -3
- package/dist/sensor/spatial-sampling-quadrature.js.map +1 -1
- package/dist/sensor/spatio-spectral-reduction.js +1 -18
- package/dist/sensor/spatio-spectral-reduction.js.map +1 -1
- package/dist/sensor/spectral-coverage.d.ts +10 -1
- package/dist/sensor/spectral-coverage.js +1 -1
- package/dist/sensor/spectral-coverage.js.map +1 -1
- package/dist/sensor/spectral-quadrature.js +2 -35
- package/dist/sensor/spectral-quadrature.js.map +1 -1
- package/dist/sensor/spectral-response.js +1 -47
- package/dist/sensor/spectral-response.js.map +1 -1
- package/dist/stabilization/camera-shake.js +1 -6
- package/dist/stabilization/camera-shake.js.map +1 -1
- package/dist/stabilization/system.js +2 -80
- package/dist/stabilization/system.js.map +1 -1
- package/docs/AGENT_GUIDE.md +4 -0
- package/docs/API_REFERENCE.md +69 -2
- package/docs/QUICK_START.md +136 -6
- package/docs/USAGE.md +89 -3
- package/docs/api/camera-sensor-equivalence.md +209 -0
- package/docs/api/core-version.md +1 -1
- package/docs/api/equipment-ideal-lens.md +26 -0
- package/docs/api/exports.json +118 -3
- package/docs/api/exposure-filtered-exposure-time.md +105 -0
- package/docs/api/facade-develop-joined-parts.md +32 -0
- package/docs/api/facade-simulate-capture.md +62 -8
- package/docs/api/optics-generic-nd-filter-presets.md +34 -0
- package/docs/api/optics-lens-psf-profile.md +3 -1
- package/docs/api/output-developed-lens-corrections.md +12 -0
- package/docs/api/output-generic-lens-corrections.md +0 -9
- package/llms.txt +3 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"raw-readout.js","sourceRoot":"","sources":["../../src/sensor/raw-readout.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EACL,mBAAmB,EAEpB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EACL,iBAAiB,EAGlB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AACpE,OAAO,EACL,gCAAgC,EAChC,iCAAiC,EACjC,4BAA4B,EAE7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAUpE,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACrF,OAAO,EACL,8BAA8B,EAC9B,mCAAmC,EAGpC,MAAM,0BAA0B,CAAC;AAIlC,MAAM,CAAC,MAAM,6CAA6C,GACxD,OAAgB,CAAC;AACnB,MAAM,CAAC,MAAM,gDAAgD,GAC3D,OAAgB,CAAC;AAgXnB,SAAS,aAAa,CACpB,KAAc,EACd,IAAY,EACZ,WAAqC;IAErC,IACE,OAAO,KAA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aACX,GAAG,CAAC,QAAQ;QACjB,cAAc,EACZ,OAAO,CAAC,cAAc;QACxB,qBAAqB,EACnB,OAAO,CAAC,MAAM;aACX,GAAG;aACH,qBAAqB;QAC1B,OAAO;QACP,wBAAwB,EACtB,SAAS;YACT,OAAO,CAAC,MAAM;iBACX,GAAG;iBACH,qBAAqB;QAC1B,qBAAqB,EACnB,SAAS,GAAG,CAAC;QACf,WAAW,EACT,uBAAuB;QACzB,yBAAyB,EACvB,kBAAkB;QACpB,0BAA0B,EACxB,mBAAmB;aAChB,IAAI,CACH,CAAC,SAAS,EAAE,EAAE,CACZ,SAAS;aACN,YAAY;YACf,CAAC,CACJ;QACL,qBAAqB,EACnB,IAAI;QACN,sBAAsB,EACpB,IAAI;QACN,oBAAoB,EAClB,IAAI;QACN,oBAAoB,EAClB,KAAK;QACP,8BAA8B,EAC5B,IAAI;KACP,EACD,oCAAoC,EACpC,OAAO,EACP;QACE,2NAA2N;QAC3N,uPAAuP;QACvP,gOAAgO;QAChO,0XAA0X;QAC1X,sGAAsG;QACtG,4HAA4H;KAC7H,CACF,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * RAW readout: turns the expected charge in a sensor site into a RAW code, with shot noise, read\n * noise and the ADC (analogue-to-digital converter).\n *\n * The steps, in order:\n * 1. expected charge;\n * 2. separately seeded random photo and dark draws (Poisson shot noise);\n * 3. signed electronic read noise;\n * 4. the upper pre-ADC clipping threshold;\n * 5. the black pedestal (offset);\n * 6. ADC quantization, rounding to nearest with ties up;\n * 7. limits on the unsigned code.\n *\n * Values below black stay signed until the final code clamp. Physical storage saturation, pre-ADC\n * clipping and digital clipping are reported separately. The ISO setting never invents a conversion\n * regime; regimes are declared.\n * @see docs/SENSOR_RAW_PRODUCER.md for equations, coordinate/unit conventions, blockers and support\n * limits.\n */\n\nimport {\n approximationResult,\n type CalculationResult\n} from \"../core/calculation-result.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport {\n parseEvidenceList,\n type EvidenceBackedFact,\n type EvidenceProvenance\n} from \"../core/evidence-provenance.js\";\nimport { InvalidScientificInputError } from \"../core/validation.js\";\nimport {\n createDeterministicUniformStream,\n sampleDeterministicStandardNormal,\n samplePortableStandardNormal,\n type DeterministicUniformStream\n} from \"./stochastic-seed.js\";\nimport { portableExp, portableLog } from \"../core/portable-math.js\";\nimport type {\n SensorPhotoAccumulatedChargeComposition as SensorAccumulatedChargeComposition\n} from \"./accumulated-charge.js\";\nimport type {\n SensorPhysicalChargeCapacityAssessment\n} from \"./physical-charge-capacity.js\";\nimport type {\n SensorSpectralResponseScientificStatus\n} from \"./spectral-response.js\";\nimport { requireInputKeys, rejectUnknownFields } from \"../core/record-validation.js\";\nimport {\n evaluateParsedFixedPatternSite,\n parseSensorFixedPatternNoiseProfile,\n type SensorFixedPatternNoiseProfile,\n type SensorFixedPatternSiteValues\n} from \"./fixed-pattern-noise.js\";\n\ntype UnknownRecord = Record<string, unknown>;\n\nexport const SENSOR_CHARGE_SAMPLING_PROFILE_SCHEMA_VERSION =\n \"0.1.0\" as const;\nexport const SENSOR_READOUT_CONVERSION_PROFILE_SCHEMA_VERSION =\n \"0.1.0\" as const;\n\nexport type SensorAdditionalChargeSamplingModel =\n | \"poisson\"\n | \"deterministic-expected-electron-equivalent\";\n\nexport interface SensorAdditionalChargeSamplingPolicy {\n componentId: string;\n model:\n SensorAdditionalChargeSamplingModel;\n}\n\nexport interface SensorChargeSamplingProfile {\n schemaVersion:\n typeof SENSOR_CHARGE_SAMPLING_PROFILE_SCHEMA_VERSION;\n profileId: string;\n completenessProfileId: string;\n scientificStatus: \"approximation\";\n photoShotNoiseModel: \"poisson\";\n darkShotNoiseModel: \"poisson\";\n additionalComponentPolicies:\n readonly SensorAdditionalChargeSamplingPolicy[];\n evidence:\n readonly EvidenceProvenance[];\n limitations: readonly string[];\n}\n\nexport interface SimulateSensorChargeRealizationInput {\n accumulatedCharge:\n SensorAccumulatedChargeComposition;\n samplingProfile:\n SensorChargeSamplingProfile;\n seedUint32: number;\n /**\n * Optional fixed-pattern noise for this sensor. PRNU (photo-response non-uniformity) scales the\n * photo Poisson mean; DSNU (dark-signal non-uniformity) and hot pixels scale the dark Poisson mean.\n * If omitted, the result is exactly the uniform population model.\n */\n fixedPatternNoise?:\n SensorFixedPatternNoiseProfile;\n}\n\nexport interface SensorChargeRealization {\n samplingProfileId: string;\n completenessProfileId: string;\n colorSamplingProfileId: string;\n channelId: string;\n site: {\n x: number;\n y: number;\n };\n bindingId: string;\n seedUint32: number;\n photoExpectedElectronCount: number;\n photoRealizedElectronCount: number;\n darkExpectedElectronCount: number;\n darkRealizedElectronCount: number;\n /** Fixed-pattern profile applied to this realization, or null for the uniform population model. */\n fixedPatternNoiseProfileId:\n string | null;\n /** PRNU gain applied to the photo expectation (exactly 1 without a fixed pattern). */\n photoResponseGainFactor: number;\n /** DSNU/hot-pixel factor applied to the dark expectation (exactly 1 without a fixed pattern). */\n darkCurrentFactor: number;\n hotPixel: boolean;\n /** Poisson means actually sampled: expectation × the site's fixed-pattern factor. */\n photoSampledMeanElectronCount: number;\n darkSampledMeanElectronCount: number;\n additionalComponents:\n readonly {\n componentId: string;\n expectedElectronCount: number;\n realizedElectronEquivalentCount:\n number;\n model:\n SensorAdditionalChargeSamplingModel;\n }[];\n totalExpectedStoredElectronCount:\n number;\n totalRealizedStoredElectronEquivalentCount:\n number;\n photoShotNoiseApplied: true;\n darkShotNoiseApplied: true;\n electronicReadNoiseApplied: false;\n physicalSaturationApplied: false;\n bloomingModeled: false;\n conversionGainApplied: false;\n adcQuantizationApplied: false;\n rawCodeValueProduced: false;\n stochasticModel:\n \"independent-poisson-photo-dark-explicit-additional-policy\";\n deterministicSeededRealization:\n true;\n}\n\n/**\n * Optional ADC integral non-linearity (INL): an offset in code units (LSB, least significant bit),\n * piecewise linear in the ideal continuous ADC input code, added before quantization. The points must\n * start at code 0 and end at the ADC maximum code. If omitted, the ADC is ideal and uniform.\n */\nexport interface SensorAdcIntegralNonLinearity {\n kind: \"piecewise-linear-code-offset\";\n knots: readonly { code: number; offsetCodes: number }[];\n evidence: readonly EvidenceProvenance[];\n}\n\n/**\n * Optional record of how one regime's ISO gain was derived (the exposure index of CIPA DC-004,\n * relative to the base exposure index). The readout equations still use\n * systemConversionGainElectronsPerCode (analog, before the ADC) and adc.digitalGain (after the ADC).\n * This record must agree with them and never replaces them.\n */\nexport interface SensorReadoutExposureIndexGain {\n exposureIndex: number;\n baseExposureIndex: number;\n /** Analog (pre-ADC) gain relative to the base-exposure-index regime. */\n analogGain: number;\n /** Post-ADC digital gain; equals adc.digitalGain (1 when omitted). */\n digitalGain: number;\n conversionGainMode:\n | \"single-conversion-gain\"\n | \"low-conversion-gain\"\n | \"high-conversion-gain\";\n evidence: readonly EvidenceProvenance[];\n}\n\nexport interface SensorElectronicReadNoiseComponent {\n componentId: string;\n rmsElectrons:\n EvidenceBackedFact<number>;\n evidence:\n readonly EvidenceProvenance[];\n}\n\n/**\n * One explicitly selected electronic conversion regime. It has a sourced number of\n * electrons per code, an upper pre-ADC threshold in electron equivalents, separate\n * read-noise components (RMS electrons) and an unsigned ADC coding policy. The black\n * pedestal and digital saturation are in code units. The regime does not guess its\n * hardware mechanism, is not chosen from ISO automatically, and does not replace\n * physical storage capacity.\n */\nexport interface SensorReadoutConversionRegime {\n regimeId: string;\n scientificStatus:\n SensorSpectralResponseScientificStatus;\n systemConversionGainElectronsPerCode:\n EvidenceBackedFact<number>;\n preAdcSaturationElectronEquivalent:\n EvidenceBackedFact<number>;\n readNoiseComponents:\n readonly SensorElectronicReadNoiseComponent[];\n adc: {\n bitDepth: number;\n blackLevelCode: number;\n digitalSaturationCode: number;\n transfer:\n \"uniform-round-half-up\";\n /**\n * Optional post-ADC digital gain (>= 1) applied about the black level:\n * code = roundHalfUp((adcCode - black) * digitalGain + black). Omission means 1.\n */\n digitalGain?: number;\n integralNonLinearity?:\n SensorAdcIntegralNonLinearity;\n };\n exposureIndexGain?:\n SensorReadoutExposureIndexGain;\n evidence:\n readonly EvidenceProvenance[];\n limitations: readonly string[];\n}\n\nexport interface SensorReadoutConversionProfile {\n schemaVersion:\n typeof SENSOR_READOUT_CONVERSION_PROFILE_SCHEMA_VERSION;\n profileId: string;\n colorSamplingProfileId: string;\n channelId: string;\n regimes:\n readonly SensorReadoutConversionRegime[];\n regimeSelectionOwnedBy:\n \"explicit-upstream-camera-state-not-inferred-from-iso\";\n evidence:\n readonly EvidenceProvenance[];\n}\n\nexport interface ResolveSensorReadoutRegimeInput {\n profile:\n SensorReadoutConversionProfile;\n regimeId: string;\n}\n\nexport interface ResolvedSensorReadoutRegime {\n profileId: string;\n colorSamplingProfileId: string;\n channelId: string;\n regime:\n SensorReadoutConversionRegime;\n regimeSelectionOwnedBy:\n \"explicit-upstream-camera-state-not-inferred-from-iso\";\n adcMaximumCode: number;\n combinedReadNoiseRmsElectrons:\n number;\n}\n\nexport interface CalculateExpectedSensorReadoutInput {\n accumulatedCharge:\n SensorAccumulatedChargeComposition;\n physicalCapacityAssessment:\n SensorPhysicalChargeCapacityAssessment;\n readoutProfile:\n SensorReadoutConversionProfile;\n regimeId: string;\n}\n\nexport interface SensorExpectedReadoutSignal {\n readoutProfileId: string;\n regimeId: string;\n completenessProfileId: string;\n capacityProfileId: string;\n colorSamplingProfileId: string;\n channelId: string;\n site: {\n x: number;\n y: number;\n };\n bindingId: string;\n expectedStoredElectronCount:\n number;\n expectedStoredChargeBelowOrAtPhysicalCapacity:\n true;\n expectedElectronEquivalentAfterPreAdcSaturation:\n number;\n preAdcSaturationAppliedToExpectation:\n boolean;\n systemConversionGainElectronsPerCode:\n number;\n expectedCodeBeforeBlackOffset:\n number;\n blackLevelCode: number;\n /** Continuous ADC input code including any declared INL offset. */\n expectedCodeBeforeQuantization:\n number;\n adcIntegralNonLinearityOffsetCodes:\n number;\n digitalGain: number;\n /** Continuous code after post-ADC digital gain about black (equals the ADC input without one). */\n expectedCodeAfterDigitalGain:\n number;\n adcBitDepth: number;\n adcMaximumCode: number;\n digitalSaturationCode: number;\n expectedDigitalSaturation:\n boolean;\n electronicReadNoiseMeanElectrons:\n 0;\n electronicReadNoiseRmsElectrons:\n number;\n electronicReadNoiseSampled: false;\n adcQuantizationApplied: false;\n rawCodeValueProduced: false;\n isoUsedToInferRegime: false;\n}\n\nexport interface SimulateSensorRawCodeInput {\n chargeRealization:\n SensorChargeRealization;\n physicalCapacityAssessment:\n SensorPhysicalChargeCapacityAssessment;\n readoutProfile:\n SensorReadoutConversionProfile;\n regimeId: string;\n readNoiseSeedUint32: number;\n /**\n * Optional fixed pattern; must be the same profile used for the charge realization. Its static\n * row/column offsets are added with read noise before the pre-ADC threshold.\n */\n fixedPatternNoise?:\n SensorFixedPatternNoiseProfile;\n}\n\nexport interface SensorRawCodeSample {\n readoutProfileId: string;\n regimeId: string;\n samplingProfileId: string;\n completenessProfileId: string;\n capacityProfileId: string;\n colorSamplingProfileId: string;\n channelId: string;\n site: {\n x: number;\n y: number;\n };\n bindingId: string;\n chargeSeedUint32: number;\n readNoiseSeedUint32: number;\n realizedStoredElectronEquivalentCountBeforePhysicalCapacity:\n number;\n physicalChargeCapacityElectrons:\n number;\n electronEquivalentAfterPhysicalScalarSaturation:\n number;\n physicalScalarSaturationApplied:\n boolean;\n overflowElectronEquivalentDiagnostic:\n number;\n bloomingModeled: false;\n electronicReadNoiseComponents:\n readonly {\n componentId: string;\n rmsElectrons: number;\n sampledElectrons: number;\n }[];\n totalElectronicReadNoiseElectrons:\n number;\n /** Fixed-pattern profile applied at readout, or null. */\n fixedPatternNoiseProfileId:\n string | null;\n /** Static fixed-pattern row + column offset in input-referred electrons (0 without a pattern). */\n fixedPatternReadoutOffsetElectrons:\n number;\n electronEquivalentAfterReadNoise:\n number;\n preAdcSaturationElectronEquivalent:\n number;\n /** Signed electronic signal after the upper (pre-ADC) clip, before conversion and the black pedestal. */\n electronEquivalentAfterPreAdcSaturation:\n number;\n preAdcSaturationApplied:\n boolean;\n systemConversionGainElectronsPerCode:\n number;\n blackLevelCode: number;\n /** Continuous ADC input code including any declared integral non-linearity offset. */\n codeBeforeQuantization:\n number;\n /** INL offset added before quantization (0 for an ideal ADC). */\n adcIntegralNonLinearityOffsetCodes:\n number;\n /** ADC output after quantization and the ADC code-range limit, before digital gain. */\n adcCodeBeforeDigitalGain:\n number;\n /** Post-ADC digital gain (1 when the regime declares none). */\n digitalGain: number;\n quantizedCodeBeforeDigitalClamp:\n number;\n adcBitDepth: number;\n adcMaximumCode: number;\n digitalSaturationCode: number;\n rawCode: number;\n digitalSaturationApplied:\n boolean;\n lowerCodeClampApplied:\n boolean;\n adcTransfer:\n \"uniform-round-half-up\";\n physicalSaturationApplied: boolean;\n electronicReadNoiseApplied:\n boolean;\n conversionGainApplied: true;\n adcQuantizationApplied: true;\n rawCodeValueProduced: true;\n isoUsedToInferRegime: false;\n deterministicSeededRealization:\n true;\n}\n\nfunction requireRecord(\n value: unknown,\n path: string,\n allowedKeys: readonly string[] | null\n): UnknownRecord {\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value)\n ) {\n throw new InvalidConfigurationError(\n path + \" must be an object.\"\n );\n }\n if (allowedKeys !== null) rejectUnknownFields(value, allowedKeys, path);\n return value as UnknownRecord;\n}\n\nfunction requireNonEmptyString(\n value: unknown,\n path: string\n): string {\n if (\n typeof value !== \"string\" ||\n value.trim().length === 0\n ) {\n throw new InvalidConfigurationError(\n path + \" must be a non-empty string.\"\n );\n }\n return value.trim();\n}\n\nfunction requireFinite(\n value: unknown,\n path: string\n): number {\n if (\n typeof value !== \"number\" ||\n !Number.isFinite(value)\n ) {\n throw new InvalidConfigurationError(\n path + \" must be finite.\"\n );\n }\n return value;\n}\n\nfunction requireNonNegativeFinite(\n value: unknown,\n path: string\n): number {\n const parsed =\n requireFinite(value, path);\n if (parsed < 0) {\n throw new InvalidConfigurationError(\n path +\n \" must be greater than or equal to zero.\"\n );\n }\n return parsed;\n}\n\nfunction requirePositiveFinite(\n value: unknown,\n path: string\n): number {\n const parsed =\n requireFinite(value, path);\n if (parsed <= 0) {\n throw new InvalidConfigurationError(\n path +\n \" must be greater than zero.\"\n );\n }\n return parsed;\n}\n\nfunction requireUint32(\n value: unknown,\n path: string\n): number {\n if (\n typeof value !== \"number\" ||\n !Number.isSafeInteger(value) ||\n value < 0 ||\n value > 0xffff_ffff\n ) {\n throw new InvalidScientificInputError(\n path +\n \" must be an unsigned 32-bit integer.\"\n );\n }\n return value;\n}\n\nfunction requireSafeInteger(\n value: unknown,\n path: string\n): number {\n if (\n typeof value !== \"number\" ||\n !Number.isSafeInteger(value)\n ) {\n throw new InvalidConfigurationError(\n path + \" must be a safe integer.\"\n );\n }\n return value;\n}\n\nfunction parseLimitations(\n value: unknown,\n path: string\n): readonly string[] {\n if (!Array.isArray(value)) {\n throw new InvalidConfigurationError(\n path + \" must be an array.\"\n );\n }\n const parsed =\n value.map((entry, index) =>\n requireNonEmptyString(\n entry,\n path +\n \"[\" +\n index +\n \"]\"\n )\n );\n if (\n new Set(parsed).size !==\n parsed.length\n ) {\n throw new InvalidConfigurationError(\n path +\n \" must not contain duplicates.\"\n );\n }\n return parsed;\n}\n\nfunction parsePositiveFact(\n value: unknown,\n path: string\n): EvidenceBackedFact<number> {\n const record =\n requireRecord(value, path, [\"value\", \"evidence\"]);\n return {\n value:\n requirePositiveFinite(\n record.value,\n path + \".value\"\n ),\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n )\n };\n}\n\nfunction parseNonNegativeFact(\n value: unknown,\n path: string\n): EvidenceBackedFact<number> {\n const record =\n requireRecord(value, path, [\"value\", \"evidence\"]);\n return {\n value:\n requireNonNegativeFinite(\n record.value,\n path + \".value\"\n ),\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n )\n };\n}\n\n/**\n * Validates untrusted input and returns it as a normalized, typed value. Unknown enum values,\n * missing required fields and inconsistent scientific data are rejected.\n *\n * The profile sets how expected charge is sampled into random photo and dark counts.\n * @param value - Untrusted data. TypeScript types alone are not validation.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function parseSensorChargeSamplingProfile(\n value: unknown\n): SensorChargeSamplingProfile {\n const record =\n requireRecord(\n value,\n \"sensorChargeSamplingProfile\", [\"schemaVersion\", \"scientificStatus\", \"photoShotNoiseModel\", \"darkShotNoiseModel\", \"additionalComponentPolicies\", \"profileId\", \"completenessProfileId\", \"evidence\", \"limitations\"]\n );\n\n if (\n record.schemaVersion !==\n SENSOR_CHARGE_SAMPLING_PROFILE_SCHEMA_VERSION\n ) {\n throw new InvalidConfigurationError(\n 'sensorChargeSamplingProfile.schemaVersion must be \"' +\n SENSOR_CHARGE_SAMPLING_PROFILE_SCHEMA_VERSION +\n '\".'\n );\n }\n if (\n record.scientificStatus !==\n \"approximation\"\n ) {\n throw new InvalidConfigurationError(\n 'sensorChargeSamplingProfile.scientificStatus must be \"approximation\".'\n );\n }\n if (\n record.photoShotNoiseModel !==\n \"poisson\" ||\n record.darkShotNoiseModel !==\n \"poisson\"\n ) {\n throw new InvalidConfigurationError(\n \"sensorChargeSamplingProfile photo/dark shot-noise models must be Poisson.\"\n );\n }\n if (\n !Array.isArray(\n record.additionalComponentPolicies\n )\n ) {\n throw new InvalidConfigurationError(\n \"sensorChargeSamplingProfile.additionalComponentPolicies must be an array.\"\n );\n }\n\n const additionalComponentPolicies =\n record.additionalComponentPolicies.map(\n (entry, index) => {\n const path =\n \"sensorChargeSamplingProfile.additionalComponentPolicies[\" +\n index +\n \"]\";\n const policy =\n requireRecord(\n entry,\n path, [\"model\", \"componentId\"]\n );\n if (\n policy.model !==\n \"poisson\" &&\n policy.model !==\n \"deterministic-expected-electron-equivalent\"\n ) {\n throw new InvalidConfigurationError(\n path +\n \".model is invalid.\"\n );\n }\n return {\n componentId:\n requireNonEmptyString(\n policy.componentId,\n path +\n \".componentId\"\n ),\n model:\n policy.model\n } as SensorAdditionalChargeSamplingPolicy;\n }\n );\n\n const ids =\n additionalComponentPolicies.map(\n (policy) =>\n policy.componentId\n );\n if (\n new Set(ids).size !==\n ids.length\n ) {\n throw new InvalidConfigurationError(\n \"sensorChargeSamplingProfile.additionalComponentPolicies must not contain duplicate componentId values.\"\n );\n }\n\n return {\n schemaVersion:\n SENSOR_CHARGE_SAMPLING_PROFILE_SCHEMA_VERSION,\n profileId:\n requireNonEmptyString(\n record.profileId,\n \"sensorChargeSamplingProfile.profileId\"\n ),\n completenessProfileId:\n requireNonEmptyString(\n record.completenessProfileId,\n \"sensorChargeSamplingProfile.completenessProfileId\"\n ),\n scientificStatus:\n \"approximation\",\n photoShotNoiseModel:\n \"poisson\",\n darkShotNoiseModel:\n \"poisson\",\n additionalComponentPolicies,\n evidence:\n parseEvidenceList(\n record.evidence,\n \"sensorChargeSamplingProfile.evidence\"\n ),\n limitations:\n parseLimitations(\n record.limitations,\n \"sensorChargeSamplingProfile.limitations\"\n )\n };\n}\n\nfunction parseStatus(\n value: unknown,\n path: string\n): SensorSpectralResponseScientificStatus {\n if (\n value !== \"calibrated\" &&\n value !== \"approximation\"\n ) {\n throw new InvalidConfigurationError(\n path + \" is invalid.\"\n );\n }\n return value;\n}\n\nfunction parseReadNoiseComponent(\n value: unknown,\n path: string\n): SensorElectronicReadNoiseComponent {\n const record =\n requireRecord(value, path, [\"componentId\", \"rmsElectrons\", \"evidence\"]);\n return {\n componentId:\n requireNonEmptyString(\n record.componentId,\n path + \".componentId\"\n ),\n rmsElectrons:\n parseNonNegativeFact(\n record.rmsElectrons,\n path + \".rmsElectrons\"\n ),\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n )\n };\n}\n\nfunction parseIntegralNonLinearity(\n value: unknown,\n path: string,\n adcMaximumCode: number\n): SensorAdcIntegralNonLinearity {\n const record =\n requireRecord(value, path, [\"kind\", \"knots\", \"evidence\"]);\n if (\n record.kind !==\n \"piecewise-linear-code-offset\"\n ) {\n throw new InvalidConfigurationError(\n path +\n '.kind must be \"piecewise-linear-code-offset\".'\n );\n }\n if (\n !Array.isArray(record.knots) ||\n record.knots.length < 2 ||\n record.knots.length > 4096\n ) {\n throw new InvalidConfigurationError(\n path +\n \".knots must contain 2 through 4096 knots.\"\n );\n }\n const knots =\n record.knots.map(\n (entry: unknown, index: number) => {\n const knot =\n requireRecord(\n entry,\n path + \".knots[\" + index + \"]\", [\"code\", \"offsetCodes\"]\n );\n return {\n code: requireFinite(\n knot.code,\n path + \".knots[\" + index + \"].code\"\n ),\n offsetCodes: requireFinite(\n knot.offsetCodes,\n path + \".knots[\" + index + \"].offsetCodes\"\n )\n };\n }\n );\n if (\n knots[0]!.code !== 0 ||\n knots[knots.length - 1]!.code !==\n adcMaximumCode ||\n knots.some(\n (knot, index) =>\n index > 0 &&\n knot.code <=\n knots[index - 1]!.code\n ) ||\n knots.some(\n (knot) =>\n Math.abs(knot.offsetCodes) >\n adcMaximumCode\n )\n ) {\n throw new InvalidConfigurationError(\n path +\n \".knots must strictly increase from code 0 to the ADC maximum code with bounded offsets.\"\n );\n }\n return {\n kind:\n \"piecewise-linear-code-offset\",\n knots,\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n )\n };\n}\n\nfunction parseExposureIndexGain(\n value: unknown,\n path: string,\n adcDigitalGain: number\n): SensorReadoutExposureIndexGain {\n const record =\n requireRecord(value, path, [\"exposureIndex\", \"baseExposureIndex\", \"analogGain\", \"digitalGain\", \"conversionGainMode\", \"evidence\"]);\n const exposureIndex =\n requirePositiveFinite(\n record.exposureIndex,\n path + \".exposureIndex\"\n );\n const baseExposureIndex =\n requirePositiveFinite(\n record.baseExposureIndex,\n path + \".baseExposureIndex\"\n );\n const analogGain =\n requirePositiveFinite(\n record.analogGain,\n path + \".analogGain\"\n );\n const digitalGain =\n requirePositiveFinite(\n record.digitalGain,\n path + \".digitalGain\"\n );\n const mode =\n record.conversionGainMode;\n if (\n mode !== \"single-conversion-gain\" &&\n mode !== \"low-conversion-gain\" &&\n mode !== \"high-conversion-gain\"\n ) {\n throw new InvalidConfigurationError(\n path +\n \".conversionGainMode is invalid.\"\n );\n }\n const ratio =\n exposureIndex /\n baseExposureIndex;\n if (\n digitalGain !==\n adcDigitalGain ||\n Math.abs(\n analogGain * digitalGain -\n ratio\n ) >\n 1e-12 * ratio\n ) {\n throw new InvalidConfigurationError(\n path +\n \" must satisfy analogGain x digitalGain = exposureIndex / baseExposureIndex and digitalGain = adc.digitalGain.\"\n );\n }\n return {\n exposureIndex,\n baseExposureIndex,\n analogGain,\n digitalGain,\n conversionGainMode: mode,\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n )\n };\n}\n\nfunction parseRegime(\n value: unknown,\n path: string\n): SensorReadoutConversionRegime {\n const record =\n requireRecord(value, path, [\"adc\", \"readNoiseComponents\", \"systemConversionGainElectronsPerCode\", \"exposureIndexGain\", \"regimeId\", \"scientificStatus\", \"preAdcSaturationElectronEquivalent\", \"evidence\", \"limitations\"]);\n const adc =\n requireRecord(\n record.adc,\n path + \".adc\", [\"bitDepth\", \"blackLevelCode\", \"digitalSaturationCode\", \"transfer\", \"digitalGain\", \"integralNonLinearity\"]\n );\n const bitDepth =\n requireSafeInteger(\n adc.bitDepth,\n path + \".adc.bitDepth\"\n );\n if (\n bitDepth < 1 ||\n bitDepth > 30\n ) {\n throw new InvalidConfigurationError(\n path +\n \".adc.bitDepth must be from 1 through 30.\"\n );\n }\n const adcMaximumCode =\n 2 ** bitDepth - 1;\n const blackLevelCode =\n requireSafeInteger(\n adc.blackLevelCode,\n path + \".adc.blackLevelCode\"\n );\n const digitalSaturationCode =\n requireSafeInteger(\n adc.digitalSaturationCode,\n path +\n \".adc.digitalSaturationCode\"\n );\n\n if (\n blackLevelCode < 0 ||\n blackLevelCode >\n adcMaximumCode\n ) {\n throw new InvalidConfigurationError(\n path +\n \".adc.blackLevelCode must lie inside the unsigned ADC code range.\"\n );\n }\n if (\n digitalSaturationCode <=\n blackLevelCode ||\n digitalSaturationCode >\n adcMaximumCode\n ) {\n throw new InvalidConfigurationError(\n path +\n \".adc.digitalSaturationCode must be greater than blackLevelCode and at most the ADC maximum code.\"\n );\n }\n if (\n adc.transfer !==\n \"uniform-round-half-up\"\n ) {\n throw new InvalidConfigurationError(\n path +\n '.adc.transfer must be \"uniform-round-half-up\".'\n );\n }\n if (\n !Array.isArray(\n record.readNoiseComponents\n )\n ) {\n throw new InvalidConfigurationError(\n path +\n \".readNoiseComponents must be an array.\"\n );\n }\n const readNoiseComponents =\n record.readNoiseComponents.map(\n (entry, index) =>\n parseReadNoiseComponent(\n entry,\n path +\n \".readNoiseComponents[\" +\n index +\n \"]\"\n )\n );\n const componentIds =\n readNoiseComponents.map(\n (entry) =>\n entry.componentId\n );\n if (\n new Set(componentIds).size !==\n componentIds.length\n ) {\n throw new InvalidConfigurationError(\n path +\n \".readNoiseComponents must not contain duplicate componentId values.\"\n );\n }\n\n const digitalGain =\n adc.digitalGain === undefined\n ? undefined\n : requireFinite(\n adc.digitalGain,\n path + \".adc.digitalGain\"\n );\n if (\n digitalGain !== undefined &&\n (digitalGain < 1 ||\n digitalGain > 65536)\n ) {\n throw new InvalidConfigurationError(\n path +\n \".adc.digitalGain must be from 1 through 65536.\"\n );\n }\n const integralNonLinearity =\n adc.integralNonLinearity === undefined\n ? undefined\n : parseIntegralNonLinearity(\n adc.integralNonLinearity,\n path + \".adc.integralNonLinearity\",\n adcMaximumCode\n );\n const systemConversionGainElectronsPerCode =\n parsePositiveFact(\n record\n .systemConversionGainElectronsPerCode,\n path +\n \".systemConversionGainElectronsPerCode\"\n );\n const exposureIndexGain =\n record.exposureIndexGain === undefined\n ? undefined\n : parseExposureIndexGain(\n record.exposureIndexGain,\n path + \".exposureIndexGain\",\n digitalGain ?? 1\n );\n\n return {\n regimeId:\n requireNonEmptyString(\n record.regimeId,\n path + \".regimeId\"\n ),\n scientificStatus:\n parseStatus(\n record.scientificStatus,\n path +\n \".scientificStatus\"\n ),\n systemConversionGainElectronsPerCode,\n preAdcSaturationElectronEquivalent:\n parsePositiveFact(\n record\n .preAdcSaturationElectronEquivalent,\n path +\n \".preAdcSaturationElectronEquivalent\"\n ),\n readNoiseComponents,\n adc: {\n bitDepth,\n blackLevelCode,\n digitalSaturationCode,\n transfer:\n \"uniform-round-half-up\",\n ...(digitalGain === undefined\n ? {}\n : { digitalGain }),\n ...(integralNonLinearity === undefined\n ? {}\n : { integralNonLinearity })\n },\n ...(exposureIndexGain === undefined\n ? {}\n : { exposureIndexGain }),\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n ),\n limitations:\n parseLimitations(\n record.limitations,\n path + \".limitations\"\n )\n };\n}\n\n/**\n * Validates untrusted input and returns it as a normalized, typed value. Unknown enum values,\n * missing required fields and inconsistent scientific data are rejected.\n *\n * The profile lists the declared conversion regimes. ISO never invents a regime.\n * @param value - Untrusted data. TypeScript types alone are not validation.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function parseSensorReadoutConversionProfile(\n value: unknown\n): SensorReadoutConversionProfile {\n const record =\n requireRecord(\n value,\n \"sensorReadoutConversionProfile\", [\"schemaVersion\", \"regimeSelectionOwnedBy\", \"regimes\", \"profileId\", \"colorSamplingProfileId\", \"channelId\", \"evidence\"]\n );\n if (\n record.schemaVersion !==\n SENSOR_READOUT_CONVERSION_PROFILE_SCHEMA_VERSION\n ) {\n throw new InvalidConfigurationError(\n 'sensorReadoutConversionProfile.schemaVersion must be \"' +\n SENSOR_READOUT_CONVERSION_PROFILE_SCHEMA_VERSION +\n '\".'\n );\n }\n if (\n record.regimeSelectionOwnedBy !==\n \"explicit-upstream-camera-state-not-inferred-from-iso\"\n ) {\n throw new InvalidConfigurationError(\n 'sensorReadoutConversionProfile.regimeSelectionOwnedBy must be \"explicit-upstream-camera-state-not-inferred-from-iso\".'\n );\n }\n if (\n !Array.isArray(\n record.regimes\n ) ||\n record.regimes.length === 0\n ) {\n throw new InvalidConfigurationError(\n \"sensorReadoutConversionProfile.regimes must be a non-empty array.\"\n );\n }\n const regimes =\n record.regimes.map(\n (entry, index) =>\n parseRegime(\n entry,\n \"sensorReadoutConversionProfile.regimes[\" +\n index +\n \"]\"\n )\n );\n const ids =\n regimes.map(\n (regime) =>\n regime.regimeId\n );\n if (\n new Set(ids).size !==\n ids.length\n ) {\n throw new InvalidConfigurationError(\n \"sensorReadoutConversionProfile.regimes must not contain duplicate regimeId values.\"\n );\n }\n\n return {\n schemaVersion:\n SENSOR_READOUT_CONVERSION_PROFILE_SCHEMA_VERSION,\n profileId:\n requireNonEmptyString(\n record.profileId,\n \"sensorReadoutConversionProfile.profileId\"\n ),\n colorSamplingProfileId:\n requireNonEmptyString(\n record.colorSamplingProfileId,\n \"sensorReadoutConversionProfile.colorSamplingProfileId\"\n ),\n channelId:\n requireNonEmptyString(\n record.channelId,\n \"sensorReadoutConversionProfile.channelId\"\n ),\n regimes,\n regimeSelectionOwnedBy:\n \"explicit-upstream-camera-state-not-inferred-from-iso\",\n evidence:\n parseEvidenceList(\n record.evidence,\n \"sensorReadoutConversionProfile.evidence\"\n )\n };\n}\n\n/**\n * Selects a declared readout regime and checks it against the exact channel and profile identity.\n * The regime is never inferred from ISO.\n * @param input - The input; see `ResolveSensorReadoutRegimeInput` for its fields, units and coordinates.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function resolveSensorReadoutRegime(\n input:\n ResolveSensorReadoutRegimeInput\n): ResolvedSensorReadoutRegime {\n requireInputKeys(input, \"resolveSensorReadoutRegime\", [\"profile\", \"regimeId\"]);\n const profile =\n parseSensorReadoutConversionProfile(\n input.profile\n );\n if (\n typeof input.regimeId !==\n \"string\" ||\n input.regimeId.trim().length ===\n 0\n ) {\n throw new InvalidConfigurationError(\n \"regimeId must be a non-empty string.\"\n );\n }\n const regimeId =\n input.regimeId.trim();\n const regime =\n profile.regimes.find(\n (entry) =>\n entry.regimeId === regimeId\n );\n if (regime === undefined) {\n throw new InvalidScientificInputError(\n \"regimeId is not declared by the sensor readout conversion profile.\"\n );\n }\n const combinedReadNoiseRmsElectrons =\n Math.sqrt(\n regime.readNoiseComponents.reduce(\n (sum, component) =>\n sum +\n component\n .rmsElectrons.value *\n component\n .rmsElectrons.value,\n 0\n )\n );\n\n return {\n profileId:\n profile.profileId,\n colorSamplingProfileId:\n profile.colorSamplingProfileId,\n channelId:\n profile.channelId,\n regime,\n regimeSelectionOwnedBy:\n profile\n .regimeSelectionOwnedBy,\n adcMaximumCode:\n 2 **\n regime.adc.bitDepth -\n 1,\n combinedReadNoiseRmsElectrons\n };\n}\n\nfunction validateChargeIdentity(\n charge:\n SensorAccumulatedChargeComposition,\n capacity:\n SensorPhysicalChargeCapacityAssessment,\n readout:\n ResolvedSensorReadoutRegime\n): true {\n if (\n charge.completenessProfileId !==\n capacity\n .completenessProfileId ||\n charge.colorSamplingProfileId !==\n capacity\n .colorSamplingProfileId ||\n charge.channelId !==\n capacity.channelId ||\n charge.site.x !==\n capacity.site.x ||\n charge.site.y !==\n capacity.site.y ||\n charge.bindingId !==\n capacity.bindingId\n ) {\n throw new InvalidScientificInputError(\n \"Physical capacity assessment identity must match the accumulated charge.\"\n );\n }\n // The assessment copies the complete expected stored-electron total exactly from the charge it\n // assessed. So the match must be exact: an assessment made for any other charge is out of date.\n if (\n charge\n .totalExpectedStoredElectronCount !==\n capacity\n .totalExpectedStoredElectronCount\n ) {\n throw new InvalidScientificInputError(\n \"Physical capacity assessment must be computed for the supplied accumulated charge; its total expected stored electrons differ.\"\n );\n }\n if (\n readout\n .colorSamplingProfileId !==\n charge.colorSamplingProfileId ||\n readout.channelId !==\n charge.channelId\n ) {\n throw new InvalidScientificInputError(\n \"Sensor readout profile color/channel identity must match the accumulated charge.\"\n );\n }\n const belowOrAtCapacity =\n capacity\n .totalExpectedStoredElectronCount <=\n capacity\n .physicalChargeCapacityElectrons;\n if (\n capacity\n .expectedChargeCapacityStatus ===\n \"above-capacity\" ||\n !belowOrAtCapacity\n ) {\n throw new InvalidScientificInputError(\n \"Expected stored charge above physical capacity cannot enter linear expected readout; the actual post-saturation stored charge is not defined by the upstream assessment.\"\n );\n }\n if (\n charge.saturationAssessed !==\n false ||\n charge.adcQuantizationApplied !==\n false ||\n charge.rawCodeValueProduced !==\n false\n ) {\n throw new InvalidScientificInputError(\n \"Sensor readout requires the unmodified accumulated-charge result.\"\n );\n }\n return belowOrAtCapacity;\n}\n\nfunction additionalPolicyMap(\n profile:\n SensorChargeSamplingProfile,\n charge:\n SensorAccumulatedChargeComposition\n): ReadonlyMap<\n string,\n SensorAdditionalChargeSamplingPolicy\n> {\n if (\n profile.completenessProfileId !==\n charge.completenessProfileId\n ) {\n throw new InvalidScientificInputError(\n \"Charge sampling profile completenessProfileId must match the accumulated charge.\"\n );\n }\n\n const chargeIds =\n charge.additionalComponents.map(\n (component) =>\n component.componentId\n ).sort();\n const policyIds =\n profile\n .additionalComponentPolicies\n .map(\n (policy) =>\n policy.componentId\n )\n .sort();\n\n if (\n chargeIds.length !==\n policyIds.length ||\n chargeIds.some(\n (id, index) =>\n id !== policyIds[index]\n )\n ) {\n throw new InvalidScientificInputError(\n \"Charge sampling profile must declare exactly one policy for every accumulated additional-charge component.\"\n );\n }\n\n return new Map(\n profile.additionalComponentPolicies.map(\n (policy) => [\n policy.componentId,\n policy\n ] as const\n )\n );\n}\n\ntype DeterministicRandom = DeterministicUniformStream;\n\nfunction createRandom(\n seedUint32: number\n): DeterministicRandom {\n return createDeterministicUniformStream(seedUint32);\n}\n\n/**\n * log(n!) for n < 256: entry n is ln 2 + ln 3 + … + ln n, summed in that order, so each entry\n * is bit-identical to summing the logarithms on demand (the partial sums of one loop).\n */\nconst SMALL_LOG_FACTORIALS = ((): Float64Array => {\n const table = new Float64Array(256);\n let sum = 0;\n for (let value = 2; value < 256; value += 1) {\n sum += Math.log(value);\n table[value] = sum;\n }\n return table;\n})();\n\n/**\n * Computes log(n!) without forming the factorial, which would overflow. Small counts\n * sum the logarithms directly (read from a table of the same partial sums). Larger counts\n * use Stirling's formula with the correction terms 1/(12n) - 1/(360n³). This is internal\n * to the Poisson rejection sampler; it is not a claim about physical accuracy or uncertainty.\n */\nfunction logFactorial(\n n: number\n): number {\n if (n < 2) {\n return 0;\n }\n if (n < 256) {\n return SMALL_LOG_FACTORIALS[n]!;\n }\n\n const inverse = 1 / n;\n const inverseCubed =\n inverse * inverse * inverse;\n return (\n (n + 0.5) * Math.log(n) -\n n +\n 0.5 *\n Math.log(\n 2 * Math.PI\n ) +\n inverse / 12 -\n inverseCubed / 360\n );\n}\n\n/** Means at or above this use the continuity-corrected normal approximation. */\nconst POISSON_NORMAL_APPROXIMATION_MINIMUM_MEAN =\n 1e9;\n\n/**\n * Draws a nonnegative integer from a Poisson distribution with the given mean.\n *\n * - Mean 0 returns exactly 0.\n * - Mean below 30: multiply uniform random numbers until the product drops below e^(−mean).\n * - Mean from 30 to below 1e9: Hörmann's (1993) PTRS transformed rejection, comparing log\n * probabilities to avoid overflow.\n * - Mean of 1e9 and above: a continuity-corrected normal approximation, because the log terms lose\n * precision there.\n *\n * The same mean and random stream reproduce the same draw. Increasing the mean does not guarantee\n * that each individual draw increases. Exported internally for the lean native executor, which must\n * draw exactly as simulateSensorChargeRealization does; not exported from the package.\n */\nexport function samplePoisson(\n mean: number,\n random:\n DeterministicRandom\n): number {\n if (\n !Number.isFinite(mean) ||\n mean < 0\n ) {\n throw new InvalidScientificInputError(\n \"Poisson mean must be finite and nonnegative.\"\n );\n }\n if (mean === 0) {\n return 0;\n }\n\n if (\n mean >=\n POISSON_NORMAL_APPROXIMATION_MINIMUM_MEAN\n ) {\n // Above 1e9 the log-probability terms of the rejection test reach about 1e10 and cancel badly\n // (variance/mean is 1.012 at 1e14). Here the continuity-corrected normal approximation has a\n // relative skewness error of 1/sqrt(mean) <= 3.2e-5 (Poisson skewness 1/sqrt(mean): NIST/SEMATECH\n // e-Handbook of Statistical Methods, sec. 1.3.6.6.19, free; normal approximation with continuity\n // correction: SOCR, University of Michigan, free. Also see: Johnson, Kemp & Kotz, Univariate\n // Discrete Distributions, 3rd ed., section 4.4).\n return Math.max(\n 0,\n Math.floor(\n mean +\n Math.sqrt(mean) *\n sampleStandardNormal(\n random\n ) +\n 0.5\n )\n );\n }\n\n if (mean < 30) {\n const threshold =\n Math.exp(-mean);\n let product = 1;\n let count = 0;\n do {\n count += 1;\n product *=\n random.next();\n } while (\n product > threshold\n );\n return count - 1;\n }\n\n const sqrtMean =\n Math.sqrt(mean);\n const b =\n 0.931 +\n 2.53 * sqrtMean;\n const a =\n -0.059 +\n 0.02483 * b;\n const inverseAlpha =\n 1.1239 +\n 1.1328 /\n (b - 3.4);\n const vR =\n 0.9277 -\n 3.6224 /\n (b - 2);\n\n for (;;) {\n const u =\n random.next() - 0.5;\n const v =\n random.next();\n const uS =\n 0.5 - Math.abs(u);\n if (uS <= 0) {\n continue;\n }\n const k =\n Math.floor(\n (2 * a / uS + b) *\n u +\n mean +\n 0.43\n );\n\n if (\n uS >= 0.07 &&\n v <= vR &&\n k >= 0\n ) {\n return k;\n }\n if (\n k < 0 ||\n (\n uS < 0.013 &&\n v > uS\n )\n ) {\n continue;\n }\n\n const lhs =\n Math.log(\n v *\n inverseAlpha /\n (a /\n (uS * uS) +\n b)\n );\n const rhs =\n -mean +\n k * Math.log(mean) -\n logFactorial(k);\n\n if (lhs <= rhs) {\n return k;\n }\n }\n}\n\n/** log(n!) as `logFactorial` computes it, with the portable logarithm (`portableLog`) in place of Math.log. */\nlet portableSmallLogFactorials: Float64Array | undefined;\nfunction portableLogFactorial(n: number): number {\n if (n < 2) return 0;\n if (n < 256) {\n if (!portableSmallLogFactorials) {\n const table = new Float64Array(256);\n let sum = 0;\n for (let value = 2; value < 256; value += 1) { sum += portableLog(value); table[value] = sum; }\n portableSmallLogFactorials = table;\n }\n return portableSmallLogFactorials[n]!;\n }\n const inverse = 1 / n, inverseCubed = inverse * inverse * inverse;\n // 0.5·ln(2π), as logFactorial forms it; computed on first use, so a bundle without the portable sampler need not evaluate it.\n portableHalfLogTwoPi ??= 0.5 * portableLog(2 * Math.PI);\n return (n + 0.5) * portableLog(n) - n + portableHalfLogTwoPi + inverse / 12 - inverseCubed / 360;\n}\nlet portableHalfLogTwoPi: number | undefined;\n\n/**\n * Internal (not exported from the package): `samplePoisson` for one fixed mean, with the per-mean constants (e^(−mean),\n * the PTRS constants and ln mean) computed once. Each draw takes the same branch, reads the same random values and\n * forms every value with the same expressions as `samplePoisson(mean, random)`, so the draws are identical; it is for\n * callers that draw many times with one mean (the display view's AHD correction).\n *\n * With `portable` true, every exponential, logarithm and normal draw uses the engine's portable functions\n * (`portableExp`, `portableLog`, `samplePortableStandardNormal`) instead of Math.exp, Math.log and the Box–Muller of\n * Math.log/Math.cos, so the draws are the same in every JavaScript engine; they then equal `samplePoisson`'s except\n * where a comparison falls within the last-bit difference of those functions. The display view uses this form.\n */\nexport function createPoissonSampler(\n mean: number,\n portable = false\n): (random: DeterministicRandom) => number {\n if (\n !Number.isFinite(mean) ||\n mean < 0\n ) {\n throw new InvalidScientificInputError(\n \"Poisson mean must be finite and nonnegative.\"\n );\n }\n if (mean === 0) {\n return () => 0;\n }\n const exp = portable ? portableExp : Math.exp, log = portable ? portableLog : Math.log;\n const logFactorialOf = portable ? portableLogFactorial : logFactorial;\n if (\n mean >=\n POISSON_NORMAL_APPROXIMATION_MINIMUM_MEAN\n ) {\n if (!portable) return (random) => samplePoisson(mean, random);\n const sqrtMean = Math.sqrt(mean);\n return (random) => Math.max(0, Math.floor(mean + sqrtMean * samplePortableStandardNormal(random) + 0.5));\n }\n if (mean < 30) {\n const threshold =\n exp(-mean);\n return (random) => {\n let product = 1;\n let count = 0;\n do {\n count += 1;\n product *=\n random.next();\n } while (\n product > threshold\n );\n return count - 1;\n };\n }\n const sqrtMean =\n Math.sqrt(mean);\n const b =\n 0.931 +\n 2.53 * sqrtMean;\n const a =\n -0.059 +\n 0.02483 * b;\n const inverseAlpha =\n 1.1239 +\n 1.1328 /\n (b - 3.4);\n const vR =\n 0.9277 -\n 3.6224 /\n (b - 2);\n const logMean =\n log(mean);\n return (random) => {\n for (;;) {\n const u =\n random.next() - 0.5;\n const v =\n random.next();\n const uS =\n 0.5 - Math.abs(u);\n if (uS <= 0) {\n continue;\n }\n const k =\n Math.floor(\n (2 * a / uS + b) *\n u +\n mean +\n 0.43\n );\n if (\n uS >= 0.07 &&\n v <= vR &&\n k >= 0\n ) {\n return k;\n }\n if (\n k < 0 ||\n (\n uS < 0.013 &&\n v > uS\n )\n ) {\n continue;\n }\n const lhs =\n log(\n v *\n inverseAlpha /\n (a /\n (uS * uS) +\n b)\n );\n const rhs =\n -mean +\n k * logMean -\n logFactorialOf(k);\n if (lhs <= rhs) {\n return k;\n }\n }\n };\n}\n\n/**\n * Internal (not exported from the package): draws `count` Poisson samples of one mean from one seeded\n * stream, exactly as the charge realization does. Used by the sampler's distribution tests.\n */\nexport function samplePoissonStreamForValidation(\n mean: number,\n seedUint32: number,\n count: number\n): number[] {\n const random =\n createRandom(seedUint32);\n return Array.from(\n { length: count },\n () =>\n samplePoisson(\n mean,\n random\n )\n );\n}\n\n/**\n * Internal (not exported from the package): draws `count` standard normal values from one seeded\n * stream, exactly as the read-noise path does. Used by the sampler's distribution tests.\n */\nexport function sampleStandardNormalStreamForValidation(\n seedUint32: number,\n count: number\n): number[] {\n const random =\n createRandom(seedUint32);\n return Array.from(\n { length: count },\n () =>\n sampleStandardNormal(\n random\n )\n );\n}\n\nfunction sampleStandardNormal(\n random:\n DeterministicRandom\n): number {\n return sampleDeterministicStandardNormal(random);\n}\n\n/**\n * Draws deterministic, separately seeded Poisson counts for photo and dark charge, and applies the\n * declared policies for additional components, starting from the expected accumulated charge.\n *\n * This is steps 1–2 of the readout order (see the module notes). Physical storage saturation is\n * reported separately from later clipping.\n * @param input - The input; see `SimulateSensorChargeRealizationInput` for its fields, units and coordinates.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function simulateSensorChargeRealization(\n input:\n SimulateSensorChargeRealizationInput\n): CalculationResult<SensorChargeRealization> {\n requireInputKeys(input, \"simulateSensorChargeRealization\", [\"accumulatedCharge\", \"samplingProfile\", \"seedUint32\", \"fixedPatternNoise\"]);\n const profile =\n parseSensorChargeSamplingProfile(\n input.samplingProfile\n );\n const seed =\n requireUint32(\n input.seedUint32,\n \"seedUint32\"\n );\n const charge =\n input.accumulatedCharge;\n\n if (\n charge.accumulatedChargeCompleteness !==\n \"complete-for-physical-storage-capacity-assessment\" ||\n charge.saturationAssessed !==\n false ||\n charge.adcQuantizationApplied !==\n false ||\n charge.rawCodeValueProduced !==\n false\n ) {\n throw new InvalidScientificInputError(\n \"Charge realization requires a complete unsaturated pre-readout accumulated-charge result.\"\n );\n }\n\n const policies =\n additionalPolicyMap(\n profile,\n charge\n );\n const pattern =\n input.fixedPatternNoise === undefined\n ? null\n : fixedPatternAtSite(\n parseSensorFixedPatternNoiseProfile(\n input.fixedPatternNoise\n ),\n charge\n .colorSamplingProfileId,\n charge.site\n );\n const photoGain =\n pattern === null\n ? 1\n : pattern\n .photoResponseGainFactor;\n const darkFactor =\n pattern === null\n ? 1\n : pattern.darkCurrentFactor;\n const photoMean =\n pattern === null\n ? charge\n .photoExpectedElectronCount\n : charge\n .photoExpectedElectronCount *\n photoGain;\n const darkMean =\n pattern === null\n ? charge\n .darkExpectedElectronCount\n : charge\n .darkExpectedElectronCount *\n darkFactor;\n const random =\n createRandom(seed);\n const photoRealized =\n samplePoisson(\n photoMean,\n random\n );\n const darkRealized =\n samplePoisson(\n darkMean,\n random\n );\n\n const additionalComponents =\n charge.additionalComponents.map(\n (component) => {\n const policy =\n policies.get(\n component.componentId\n )!;\n const realized =\n policy.model ===\n \"poisson\"\n ? samplePoisson(\n component\n .expectedElectronCount,\n random\n )\n : component\n .expectedElectronCount;\n return {\n componentId:\n component.componentId,\n expectedElectronCount:\n component\n .expectedElectronCount,\n realizedElectronEquivalentCount:\n realized,\n model:\n policy.model\n };\n }\n );\n\n const additionalRealized =\n additionalComponents.reduce(\n (sum, component) =>\n sum +\n component\n .realizedElectronEquivalentCount,\n 0\n );\n const totalRealized =\n photoRealized +\n darkRealized +\n additionalRealized;\n\n if (\n !Number.isFinite(\n totalRealized\n ) ||\n totalRealized < 0\n ) {\n throw new InvalidScientificInputError(\n \"Realized stored charge must remain finite and nonnegative.\"\n );\n }\n\n return approximationResult(\n {\n samplingProfileId:\n profile.profileId,\n completenessProfileId:\n charge\n .completenessProfileId,\n colorSamplingProfileId:\n charge\n .colorSamplingProfileId,\n channelId:\n charge.channelId,\n site: {\n ...charge.site\n },\n bindingId:\n charge.bindingId,\n seedUint32:\n seed,\n photoExpectedElectronCount:\n charge\n .photoExpectedElectronCount,\n photoRealizedElectronCount:\n photoRealized,\n darkExpectedElectronCount:\n charge\n .darkExpectedElectronCount,\n darkRealizedElectronCount:\n darkRealized,\n fixedPatternNoiseProfileId:\n pattern === null\n ? null\n : pattern.profileId,\n photoResponseGainFactor:\n photoGain,\n darkCurrentFactor:\n darkFactor,\n hotPixel:\n pattern?.hotPixel ?? false,\n photoSampledMeanElectronCount:\n photoMean,\n darkSampledMeanElectronCount:\n darkMean,\n additionalComponents,\n totalExpectedStoredElectronCount:\n charge\n .totalExpectedStoredElectronCount,\n totalRealizedStoredElectronEquivalentCount:\n totalRealized,\n photoShotNoiseApplied:\n true,\n darkShotNoiseApplied:\n true,\n electronicReadNoiseApplied:\n false,\n physicalSaturationApplied:\n false,\n bloomingModeled: false,\n conversionGainApplied:\n false,\n adcQuantizationApplied:\n false,\n rawCodeValueProduced:\n false,\n stochasticModel:\n \"independent-poisson-photo-dark-explicit-additional-policy\",\n deterministicSeededRealization:\n true\n },\n \"sensor-charge-stochastic-realization\",\n \"3.0.0\",\n [\n \"An optional explicit fixed-pattern profile multiplies the photo Poisson mean by the site's PRNU gain and the dark Poisson mean by its DSNU/hot-pixel factor; without one the uniform population expectation is sampled. Fixed-pattern values are deterministic per sensor instance and colour-sampling site.\",\n \"Poisson means of 1e9 electrons and above use a continuity-corrected normal approximation.\",\n \"Photo-generated and dark-generated electron counts are sampled independently from Poisson distributions using an explicit deterministic seed.\",\n \"Each additional stored-charge component uses its explicitly declared Poisson or deterministic electron-equivalent policy; Photivra does not infer defect/leakage statistics from the component name.\",\n \"This is a pre-saturation, pre-electronic-read-noise charge realization and remains separate from expectation-value calculations.\",\n \"The seeded PRNG is a deterministic simulation mechanism and is not cryptographically secure; its seed is scrambled by the MurmurHash3 fmix32 finalizer so nearby seeds give unrelated streams.\"\n ]\n );\n}\n\nfunction fixedPatternAtSite(\n profile:\n SensorFixedPatternNoiseProfile,\n colorSamplingProfileId: string,\n site: { x: number; y: number }\n): SensorFixedPatternSiteValues {\n if (\n profile.colorSamplingProfileId !==\n colorSamplingProfileId\n ) {\n throw new InvalidScientificInputError(\n \"Fixed-pattern noise profile colour-sampling identity must match the charge.\"\n );\n }\n return evaluateParsedFixedPatternSite(\n profile,\n site\n );\n}\n\nfunction fixedPatternForRealization(\n value:\n SensorFixedPatternNoiseProfile | undefined,\n charge:\n SensorChargeRealization\n): SensorFixedPatternSiteValues | null {\n if (value === undefined) {\n if (\n charge.fixedPatternNoiseProfileId !==\n null &&\n charge.fixedPatternNoiseProfileId !==\n undefined\n ) {\n throw new InvalidScientificInputError(\n \"A charge realization with a fixed pattern requires the same fixed-pattern profile at readout.\"\n );\n }\n return null;\n }\n const profile =\n parseSensorFixedPatternNoiseProfile(\n value\n );\n if (\n charge.fixedPatternNoiseProfileId !==\n profile.profileId\n ) {\n throw new InvalidScientificInputError(\n \"Readout fixed-pattern profile must be the profile used for the charge realization.\"\n );\n }\n return fixedPatternAtSite(\n profile,\n charge.colorSamplingProfileId,\n charge.site\n );\n}\n\nfunction validateCapacityAgainstRealization(\n charge:\n SensorChargeRealization,\n capacity:\n SensorPhysicalChargeCapacityAssessment,\n readout:\n ResolvedSensorReadoutRegime\n): void {\n if (\n charge.completenessProfileId !==\n capacity\n .completenessProfileId ||\n charge.colorSamplingProfileId !==\n capacity\n .colorSamplingProfileId ||\n charge.channelId !==\n capacity.channelId ||\n charge.site.x !==\n capacity.site.x ||\n charge.site.y !==\n capacity.site.y ||\n charge.bindingId !==\n capacity.bindingId\n ) {\n throw new InvalidScientificInputError(\n \"Physical capacity assessment identity must match the charge realization.\"\n );\n }\n if (\n charge\n .totalExpectedStoredElectronCount !==\n capacity\n .totalExpectedStoredElectronCount\n ) {\n throw new InvalidScientificInputError(\n \"Physical capacity assessment must be computed for the charge behind the realization; its total expected stored electrons differ.\"\n );\n }\n if (\n readout\n .colorSamplingProfileId !==\n charge.colorSamplingProfileId ||\n readout.channelId !==\n charge.channelId\n ) {\n throw new InvalidScientificInputError(\n \"Sensor readout profile color/channel identity must match the charge realization.\"\n );\n }\n}\n\n/**\n * Maps the expected charge through the declared gain, offset and readout limits, with no random\n * sampling. Each kind of clipping (physical storage, pre-ADC, digital) is reported separately.\n * @param input - The input; see `CalculateExpectedSensorReadoutInput` for its fields, units and coordinates.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function calculateExpectedSensorReadout(\n input:\n CalculateExpectedSensorReadoutInput\n): CalculationResult<SensorExpectedReadoutSignal> {\n requireInputKeys(input, \"calculateExpectedSensorReadout\", [\"accumulatedCharge\", \"physicalCapacityAssessment\", \"readoutProfile\", \"regimeId\"]);\n const readout =\n resolveSensorReadoutRegime({\n profile:\n input.readoutProfile,\n regimeId:\n input.regimeId\n });\n const expectedStoredChargeBelowOrAtPhysicalCapacity =\n validateChargeIdentity(\n input.accumulatedCharge,\n input\n .physicalCapacityAssessment,\n readout\n );\n\n const expected =\n input.accumulatedCharge\n .totalExpectedStoredElectronCount;\n const threshold =\n readout.regime\n .preAdcSaturationElectronEquivalent\n .value;\n const afterPreAdc =\n Math.min(\n expected,\n threshold\n );\n const codeSignal =\n afterPreAdc /\n readout.regime\n .systemConversionGainElectronsPerCode\n .value;\n const inlOffset =\n integralNonLinearityOffset(\n readout.regime.adc\n .integralNonLinearity,\n codeSignal +\n readout.regime\n .adc.blackLevelCode\n );\n const codeBeforeQuantization =\n codeSignal +\n readout.regime\n .adc.blackLevelCode +\n inlOffset;\n const digitalGain =\n readout.regime.adc\n .digitalGain ?? 1;\n const codeAfterDigitalGain =\n readout.regime.adc\n .digitalGain === undefined\n ? codeBeforeQuantization\n : (Math.min(\n codeBeforeQuantization,\n readout.adcMaximumCode\n ) -\n readout.regime.adc\n .blackLevelCode) *\n digitalGain +\n readout.regime.adc\n .blackLevelCode;\n\n return approximationResult(\n {\n readoutProfileId:\n readout.profileId,\n regimeId:\n readout.regime\n .regimeId,\n completenessProfileId:\n input.accumulatedCharge\n .completenessProfileId,\n capacityProfileId:\n input\n .physicalCapacityAssessment\n .capacityProfileId,\n colorSamplingProfileId:\n input.accumulatedCharge\n .colorSamplingProfileId,\n channelId:\n input.accumulatedCharge\n .channelId,\n site: {\n ...input\n .accumulatedCharge\n .site\n },\n bindingId:\n input.accumulatedCharge\n .bindingId,\n expectedStoredElectronCount:\n expected,\n expectedStoredChargeBelowOrAtPhysicalCapacity,\n expectedElectronEquivalentAfterPreAdcSaturation:\n afterPreAdc,\n preAdcSaturationAppliedToExpectation:\n afterPreAdc < expected,\n systemConversionGainElectronsPerCode:\n readout.regime\n .systemConversionGainElectronsPerCode\n .value,\n expectedCodeBeforeBlackOffset:\n codeSignal,\n blackLevelCode:\n readout.regime\n .adc.blackLevelCode,\n expectedCodeBeforeQuantization:\n codeBeforeQuantization,\n adcIntegralNonLinearityOffsetCodes:\n inlOffset,\n digitalGain,\n expectedCodeAfterDigitalGain:\n codeAfterDigitalGain,\n adcBitDepth:\n readout.regime\n .adc.bitDepth,\n adcMaximumCode:\n readout.adcMaximumCode,\n digitalSaturationCode:\n readout.regime\n .adc\n .digitalSaturationCode,\n expectedDigitalSaturation:\n codeAfterDigitalGain >=\n readout.regime\n .adc\n .digitalSaturationCode,\n electronicReadNoiseMeanElectrons:\n 0,\n electronicReadNoiseRmsElectrons:\n readout\n .combinedReadNoiseRmsElectrons,\n electronicReadNoiseSampled:\n false,\n adcQuantizationApplied:\n false,\n rawCodeValueProduced:\n false,\n isoUsedToInferRegime:\n false\n },\n \"sensor-expected-electronic-readout\",\n \"2.0.0\",\n [\n \"Expected readout uses complete expected stored charge only after the upstream physical-capacity assessment confirms the expectation is not above physical capacity.\",\n \"Electronic read-noise mean is zero and is not sampled in this expectation result.\",\n \"The explicitly selected conversion regime is not inferred from ISO, sensor technology family or marketing mode names; an ISO signal chain may bind an exposure index to a declared regime.\",\n \"Declared ADC integral non-linearity and post-ADC digital gain are applied to the continuous expectation without quantization.\",\n \"Pre-ADC electron-equivalent saturation, black offset and ADC/digital saturation remain separate domains.\",\n \"ADC quantization is not applied to the expectation value.\"\n ]\n );\n}\n\n/**\n * Nearest integer, with ties going towards +infinity. Math.round is exact for every double. (In\n * contrast, floor(x + 0.5) returns 1 for 0.49999999999999994, because the addition rounds up.)\n * Adding 0 turns -0 into +0.\n */\nfunction roundHalfUp(\n value: number\n): number {\n return Math.round(value) + 0;\n}\n\nfunction integralNonLinearityOffset(\n inl:\n SensorAdcIntegralNonLinearity | undefined,\n code: number\n): number {\n if (inl === undefined) {\n return 0;\n }\n const knots = inl.knots;\n const first = knots[0]!;\n const last = knots[knots.length - 1]!;\n if (code <= first.code) {\n return first.offsetCodes;\n }\n if (code >= last.code) {\n return last.offsetCodes;\n }\n let low = 0;\n let high = knots.length - 1;\n while (high - low > 1) {\n const middle = (low + high) >> 1;\n if (knots[middle]!.code <= code) {\n low = middle;\n } else {\n high = middle;\n }\n }\n const a = knots[low]!;\n const b = knots[high]!;\n return (\n a.offsetCodes +\n ((code - a.code) /\n (b.code - a.code)) *\n (b.offsetCodes - a.offsetCodes)\n );\n}\n\n/**\n * Shared ADC transfer function: continuous input code (signal/gain + black + INL), rounded half up\n * and limited to the ADC code range, then optional post-ADC digital gain about black, rounded again.\n * The caller applies the final clamp to [0, digitalSaturationCode]. Exported internally for the lean\n * native executor; not exported from the package.\n */\nexport function adcTransfer(\n regime:\n SensorReadoutConversionRegime,\n adcMaximumCode: number,\n electronEquivalent: number\n): {\n codeBeforeQuantization: number;\n inlOffset: number;\n adcCode: number;\n digitalGain: number;\n quantized: number;\n} {\n const ideal =\n electronEquivalent /\n regime\n .systemConversionGainElectronsPerCode\n .value +\n regime.adc.blackLevelCode;\n const inlOffset =\n integralNonLinearityOffset(\n regime.adc.integralNonLinearity,\n ideal\n );\n const codeBeforeQuantization =\n ideal + inlOffset;\n const quantizedAdc =\n roundHalfUp(\n codeBeforeQuantization\n );\n const digitalGain =\n regime.adc.digitalGain ?? 1;\n if (\n regime.adc.digitalGain ===\n undefined\n ) {\n return {\n codeBeforeQuantization,\n inlOffset,\n adcCode:\n quantizedAdc,\n digitalGain,\n quantized:\n quantizedAdc\n };\n }\n const adcCode =\n Math.max(\n 0,\n Math.min(\n quantizedAdc,\n adcMaximumCode\n )\n );\n return {\n codeBeforeQuantization,\n inlOffset,\n adcCode,\n digitalGain,\n quantized:\n roundHalfUp(\n (adcCode -\n regime.adc\n .blackLevelCode) *\n digitalGain +\n regime.adc\n .blackLevelCode\n )\n };\n}\n\n/**\n * Simulates one RAW code from a charge realization with the declared seed and regime: steps 3–7 of\n * the readout order (see the module notes). Signed read noise is kept through the black pedestal and\n * quantization, and only the final code is clamped. Returns the bounded native ADC code and per-step\n * diagnostics.\n * @param input - The input; see `SimulateSensorRawCodeInput` for its fields, units and coordinates.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function simulateSensorRawCode(\n input:\n SimulateSensorRawCodeInput\n): CalculationResult<SensorRawCodeSample> {\n requireInputKeys(input, \"simulateSensorRawCode\", [\"chargeRealization\", \"physicalCapacityAssessment\", \"readoutProfile\", \"regimeId\", \"readNoiseSeedUint32\", \"fixedPatternNoise\"]);\n const readout =\n resolveSensorReadoutRegime({\n profile:\n input.readoutProfile,\n regimeId:\n input.regimeId\n });\n validateCapacityAgainstRealization(\n input.chargeRealization,\n input\n .physicalCapacityAssessment,\n readout\n );\n const readNoiseSeed =\n requireUint32(\n input.readNoiseSeedUint32,\n \"readNoiseSeedUint32\"\n );\n const random =\n createRandom(\n readNoiseSeed\n );\n\n const realized =\n input.chargeRealization\n .totalRealizedStoredElectronEquivalentCount;\n if (\n !Number.isFinite(realized) ||\n realized < 0\n ) {\n throw new InvalidScientificInputError(\n \"Charge realization total must be finite and nonnegative.\"\n );\n }\n\n const physicalCapacity =\n input\n .physicalCapacityAssessment\n .physicalChargeCapacityElectrons;\n const afterPhysical =\n Math.min(\n realized,\n physicalCapacity\n );\n const physicalSaturation =\n afterPhysical < realized;\n const overflow =\n Math.max(\n 0,\n realized -\n physicalCapacity\n );\n\n const readNoiseComponents =\n readout.regime\n .readNoiseComponents.map(\n (component) => {\n const sampled =\n component\n .rmsElectrons.value ===\n 0\n ? 0\n : sampleStandardNormal(\n random\n ) *\n component\n .rmsElectrons.value;\n return {\n componentId:\n component\n .componentId,\n rmsElectrons:\n component\n .rmsElectrons\n .value,\n sampledElectrons:\n sampled\n };\n }\n );\n const totalReadNoise =\n readNoiseComponents.reduce(\n (sum, component) =>\n sum +\n component\n .sampledElectrons,\n 0\n );\n const pattern =\n fixedPatternForRealization(\n input.fixedPatternNoise,\n input.chargeRealization\n );\n const fixedPatternOffset =\n pattern === null\n ? 0\n : pattern\n .readoutOffsetElectrons;\n\n const afterReadNoise =\n afterPhysical +\n totalReadNoise +\n fixedPatternOffset;\n const preAdcThreshold =\n readout.regime\n .preAdcSaturationElectronEquivalent\n .value;\n // Stored charge is nonnegative, but the electronic signal after it is signed.\n // Keep negative read noise until the black pedestal and the unsigned ADC limit.\n const afterPreAdc =\n Math.min(\n afterReadNoise,\n preAdcThreshold\n );\n const preAdcSaturation =\n afterReadNoise >\n preAdcThreshold;\n\n const transfer =\n adcTransfer(\n readout.regime,\n readout.adcMaximumCode,\n afterPreAdc\n );\n const codeBeforeQuantization =\n transfer.codeBeforeQuantization;\n const quantized =\n transfer.quantized;\n const rawCode =\n Math.max(\n 0,\n Math.min(\n quantized,\n readout.regime\n .adc\n .digitalSaturationCode\n )\n );\n\n return approximationResult(\n {\n readoutProfileId:\n readout.profileId,\n regimeId:\n readout.regime\n .regimeId,\n samplingProfileId:\n input.chargeRealization\n .samplingProfileId,\n completenessProfileId:\n input.chargeRealization\n .completenessProfileId,\n capacityProfileId:\n input\n .physicalCapacityAssessment\n .capacityProfileId,\n colorSamplingProfileId:\n input.chargeRealization\n .colorSamplingProfileId,\n channelId:\n input.chargeRealization\n .channelId,\n site: {\n ...input\n .chargeRealization.site\n },\n bindingId:\n input.chargeRealization\n .bindingId,\n chargeSeedUint32:\n input.chargeRealization\n .seedUint32,\n readNoiseSeedUint32:\n readNoiseSeed,\n realizedStoredElectronEquivalentCountBeforePhysicalCapacity:\n realized,\n physicalChargeCapacityElectrons:\n physicalCapacity,\n electronEquivalentAfterPhysicalScalarSaturation:\n afterPhysical,\n physicalScalarSaturationApplied:\n physicalSaturation,\n overflowElectronEquivalentDiagnostic:\n overflow,\n bloomingModeled: false,\n electronicReadNoiseComponents:\n readNoiseComponents,\n totalElectronicReadNoiseElectrons:\n totalReadNoise,\n fixedPatternNoiseProfileId:\n pattern === null\n ? null\n : pattern.profileId,\n fixedPatternReadoutOffsetElectrons:\n fixedPatternOffset,\n electronEquivalentAfterReadNoise:\n afterReadNoise,\n preAdcSaturationElectronEquivalent:\n preAdcThreshold,\n electronEquivalentAfterPreAdcSaturation:\n afterPreAdc,\n preAdcSaturationApplied:\n preAdcSaturation,\n systemConversionGainElectronsPerCode:\n readout.regime\n .systemConversionGainElectronsPerCode\n .value,\n blackLevelCode:\n readout.regime\n .adc.blackLevelCode,\n codeBeforeQuantization,\n adcIntegralNonLinearityOffsetCodes:\n transfer.inlOffset,\n adcCodeBeforeDigitalGain:\n transfer.adcCode,\n digitalGain:\n transfer.digitalGain,\n quantizedCodeBeforeDigitalClamp:\n quantized,\n adcBitDepth:\n readout.regime\n .adc.bitDepth,\n adcMaximumCode:\n readout.adcMaximumCode,\n digitalSaturationCode:\n readout.regime\n .adc\n .digitalSaturationCode,\n rawCode,\n digitalSaturationApplied:\n quantized >=\n readout.regime\n .adc\n .digitalSaturationCode,\n lowerCodeClampApplied:\n quantized < 0,\n adcTransfer:\n \"uniform-round-half-up\",\n physicalSaturationApplied:\n physicalSaturation,\n electronicReadNoiseApplied:\n readNoiseComponents\n .some(\n (component) =>\n component\n .rmsElectrons >\n 0\n ),\n conversionGainApplied:\n true,\n adcQuantizationApplied:\n true,\n rawCodeValueProduced:\n true,\n isoUsedToInferRegime:\n false,\n deterministicSeededRealization:\n true\n },\n \"sensor-raw-code-stochastic-readout\",\n \"4.0.0\",\n [\n \"A stochastic stored-charge realization is scalar-clamped at the explicit physical storage capacity; this is a bounded saturation approximation and does not model blooming, neighbor transport or anti-blooming behavior.\",\n \"Independent input-referred Gaussian electronic read-noise components, plus any declared static fixed-pattern row/column offsets, are added after physical charge saturation and before the explicit pre-ADC electron-equivalent saturation threshold.\",\n \"System conversion gain is expressed in electrons per digital-number code unit for the explicitly selected regime; an ISO-dependent gain exists only where an explicit ISO signal chain binds the setting to a declared regime.\",\n \"Signed electronic read noise survives the upper-only pre-ADC saturation threshold. Black level and any declared ADC integral non-linearity are added before uniform round-half-up quantization (exact ties toward +infinity); an optional post-ADC digital gain about black is re-quantized; codes are then clamped to zero/digital saturation and valid below-black codes are retained.\",\n \"Physical storage capacity, pre-ADC saturation and digital/ADC saturation remain separate thresholds.\",\n \"The charge seed and read-noise seed are separate deterministic simulation identities; neither is cryptographically secure.\"\n ]\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"raw-readout.js","sourceRoot":"","sources":["../../src/sensor/raw-readout.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EACL,mBAAmB,EAEpB,MAAM,+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qB;QAC1B,OAAO;QACP,wBAAwB,EACtB,SAAS;YACT,OAAO,CAAC,MAAM;iBACX,GAAG;iBACH,qBAAqB;QAC1B,qBAAqB,EACnB,SAAS,GAAG,CAAC;QACf,WAAW,EACT,uBAAuB;QACzB,yBAAyB,EACvB,kBAAkB;QACpB,0BAA0B,EACxB,mBAAmB;aAChB,IAAI,CACH,CAAC,SAAS,EAAE,EAAE,CACZ,SAAS;aACN,YAAY;YACf,CAAC,CACJ;QACL,qBAAqB,EACnB,IAAI;QACN,sBAAsB,EACpB,IAAI;QACN,oBAAoB,EAClB,IAAI;QACN,oBAAoB,EAClB,KAAK;QACP,8BAA8B,EAC5B,IAAI;KACP,EACD,oCAAoC,EACpC,OAAO,EACP;QACE,2NAA2N;QAC3N,uPAAuP;QACvP,gOAAgO;QAChO,0XAA0X;QAC1X,sGAAsG;QACtG,4HAA4H;KAC7H,CACF,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * RAW readout: turns the expected charge in a sensor site into a RAW code, with shot noise, read\n * noise and the ADC (analogue-to-digital converter).\n *\n * The steps, in order:\n * 1. expected charge;\n * 2. separately seeded random photo and dark draws (Poisson shot noise);\n * 3. signed electronic read noise;\n * 4. the upper pre-ADC clipping threshold;\n * 5. the black pedestal (offset);\n * 6. ADC quantization, rounding to nearest with ties up;\n * 7. limits on the unsigned code.\n *\n * Values below black stay signed until the final code clamp. Physical storage saturation, pre-ADC\n * clipping and digital clipping are reported separately. The ISO setting never invents a conversion\n * regime; regimes are declared.\n * @see docs/SENSOR_RAW_PRODUCER.md for equations, coordinate/unit conventions, blockers and support\n * limits.\n */\n\nimport {\n approximationResult,\n type CalculationResult\n} from \"../core/calculation-result.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport {\n parseEvidenceList,\n type EvidenceBackedFact,\n type EvidenceProvenance\n} from \"../core/evidence-provenance.js\";\nimport { InvalidScientificInputError } from \"../core/validation.js\";\nimport {\n createDeterministicUniformStream,\n sampleDeterministicStandardNormal,\n samplePortableStandardNormal,\n type DeterministicUniformStream\n} from \"./stochastic-seed.js\";\nimport { portableExp, portableLog } from \"../core/portable-math.js\";\nimport type {\n SensorPhotoAccumulatedChargeComposition as SensorAccumulatedChargeComposition\n} from \"./accumulated-charge.js\";\nimport type {\n SensorPhysicalChargeCapacityAssessment\n} from \"./physical-charge-capacity.js\";\nimport type {\n SensorSpectralResponseScientificStatus\n} from \"./spectral-response.js\";\nimport { requireInputKeys, requireConfigRecord as requireRecord, requireTrimmedConfigString as requireNonEmptyString, requireConfigFinite as requireFinite, parseConfigScientificStatus as parseStatus, parseConfigLimitations as parseLimitations, requireConfigFiniteAboveZero as requirePositiveFinite, requireConfigFiniteAtLeastZero as requireNonNegativeFinite } from \"../core/record-validation.js\";\nimport {\n evaluateParsedFixedPatternSite,\n parseSensorFixedPatternNoiseProfile,\n type SensorFixedPatternNoiseProfile,\n type SensorFixedPatternSiteValues\n} from \"./fixed-pattern-noise.js\";\n\nexport const SENSOR_CHARGE_SAMPLING_PROFILE_SCHEMA_VERSION =\n \"0.1.0\" as const;\nexport const SENSOR_READOUT_CONVERSION_PROFILE_SCHEMA_VERSION =\n \"0.1.0\" as const;\n\nexport type SensorAdditionalChargeSamplingModel =\n | \"poisson\"\n | \"deterministic-expected-electron-equivalent\";\n\nexport interface SensorAdditionalChargeSamplingPolicy {\n componentId: string;\n model:\n SensorAdditionalChargeSamplingModel;\n}\n\nexport interface SensorChargeSamplingProfile {\n schemaVersion:\n typeof SENSOR_CHARGE_SAMPLING_PROFILE_SCHEMA_VERSION;\n profileId: string;\n completenessProfileId: string;\n scientificStatus: \"approximation\";\n photoShotNoiseModel: \"poisson\";\n darkShotNoiseModel: \"poisson\";\n additionalComponentPolicies:\n readonly SensorAdditionalChargeSamplingPolicy[];\n evidence:\n readonly EvidenceProvenance[];\n limitations: readonly string[];\n}\n\nexport interface SimulateSensorChargeRealizationInput {\n accumulatedCharge:\n SensorAccumulatedChargeComposition;\n samplingProfile:\n SensorChargeSamplingProfile;\n seedUint32: number;\n /**\n * Optional fixed-pattern noise for this sensor. PRNU (photo-response non-uniformity) scales the\n * photo Poisson mean; DSNU (dark-signal non-uniformity) and hot pixels scale the dark Poisson mean.\n * If omitted, the result is exactly the uniform population model.\n */\n fixedPatternNoise?:\n SensorFixedPatternNoiseProfile;\n}\n\nexport interface SensorChargeRealization {\n samplingProfileId: string;\n completenessProfileId: string;\n colorSamplingProfileId: string;\n channelId: string;\n site: {\n x: number;\n y: number;\n };\n bindingId: string;\n seedUint32: number;\n photoExpectedElectronCount: number;\n photoRealizedElectronCount: number;\n darkExpectedElectronCount: number;\n darkRealizedElectronCount: number;\n /** Fixed-pattern profile applied to this realization, or null for the uniform population model. */\n fixedPatternNoiseProfileId:\n string | null;\n /** PRNU gain applied to the photo expectation (exactly 1 without a fixed pattern). */\n photoResponseGainFactor: number;\n /** DSNU/hot-pixel factor applied to the dark expectation (exactly 1 without a fixed pattern). */\n darkCurrentFactor: number;\n hotPixel: boolean;\n /** Poisson means actually sampled: expectation × the site's fixed-pattern factor. */\n photoSampledMeanElectronCount: number;\n darkSampledMeanElectronCount: number;\n additionalComponents:\n readonly {\n componentId: string;\n expectedElectronCount: number;\n realizedElectronEquivalentCount:\n number;\n model:\n SensorAdditionalChargeSamplingModel;\n }[];\n totalExpectedStoredElectronCount:\n number;\n totalRealizedStoredElectronEquivalentCount:\n number;\n photoShotNoiseApplied: true;\n darkShotNoiseApplied: true;\n electronicReadNoiseApplied: false;\n physicalSaturationApplied: false;\n bloomingModeled: false;\n conversionGainApplied: false;\n adcQuantizationApplied: false;\n rawCodeValueProduced: false;\n stochasticModel:\n \"independent-poisson-photo-dark-explicit-additional-policy\";\n deterministicSeededRealization:\n true;\n}\n\n/**\n * Optional ADC integral non-linearity (INL): an offset in code units (LSB, least significant bit),\n * piecewise linear in the ideal continuous ADC input code, added before quantization. The points must\n * start at code 0 and end at the ADC maximum code. If omitted, the ADC is ideal and uniform.\n */\nexport interface SensorAdcIntegralNonLinearity {\n kind: \"piecewise-linear-code-offset\";\n knots: readonly { code: number; offsetCodes: number }[];\n evidence: readonly EvidenceProvenance[];\n}\n\n/**\n * Optional record of how one regime's ISO gain was derived (the exposure index of CIPA DC-004,\n * relative to the base exposure index). The readout equations still use\n * systemConversionGainElectronsPerCode (analog, before the ADC) and adc.digitalGain (after the ADC).\n * This record must agree with them and never replaces them.\n */\nexport interface SensorReadoutExposureIndexGain {\n exposureIndex: number;\n baseExposureIndex: number;\n /** Analog (pre-ADC) gain relative to the base-exposure-index regime. */\n analogGain: number;\n /** Post-ADC digital gain; equals adc.digitalGain (1 when omitted). */\n digitalGain: number;\n conversionGainMode:\n | \"single-conversion-gain\"\n | \"low-conversion-gain\"\n | \"high-conversion-gain\";\n evidence: readonly EvidenceProvenance[];\n}\n\nexport interface SensorElectronicReadNoiseComponent {\n componentId: string;\n rmsElectrons:\n EvidenceBackedFact<number>;\n evidence:\n readonly EvidenceProvenance[];\n}\n\n/**\n * One explicitly selected electronic conversion regime. It has a sourced number of\n * electrons per code, an upper pre-ADC threshold in electron equivalents, separate\n * read-noise components (RMS electrons) and an unsigned ADC coding policy. The black\n * pedestal and digital saturation are in code units. The regime does not guess its\n * hardware mechanism, is not chosen from ISO automatically, and does not replace\n * physical storage capacity.\n */\nexport interface SensorReadoutConversionRegime {\n regimeId: string;\n scientificStatus:\n SensorSpectralResponseScientificStatus;\n systemConversionGainElectronsPerCode:\n EvidenceBackedFact<number>;\n preAdcSaturationElectronEquivalent:\n EvidenceBackedFact<number>;\n readNoiseComponents:\n readonly SensorElectronicReadNoiseComponent[];\n adc: {\n bitDepth: number;\n blackLevelCode: number;\n digitalSaturationCode: number;\n transfer:\n \"uniform-round-half-up\";\n /**\n * Optional post-ADC digital gain (>= 1) applied about the black level:\n * code = roundHalfUp((adcCode - black) * digitalGain + black). Omission means 1.\n */\n digitalGain?: number;\n integralNonLinearity?:\n SensorAdcIntegralNonLinearity;\n };\n exposureIndexGain?:\n SensorReadoutExposureIndexGain;\n evidence:\n readonly EvidenceProvenance[];\n limitations: readonly string[];\n}\n\nexport interface SensorReadoutConversionProfile {\n schemaVersion:\n typeof SENSOR_READOUT_CONVERSION_PROFILE_SCHEMA_VERSION;\n profileId: string;\n colorSamplingProfileId: string;\n channelId: string;\n regimes:\n readonly SensorReadoutConversionRegime[];\n regimeSelectionOwnedBy:\n \"explicit-upstream-camera-state-not-inferred-from-iso\";\n evidence:\n readonly EvidenceProvenance[];\n}\n\nexport interface ResolveSensorReadoutRegimeInput {\n profile:\n SensorReadoutConversionProfile;\n regimeId: string;\n}\n\nexport interface ResolvedSensorReadoutRegime {\n profileId: string;\n colorSamplingProfileId: string;\n channelId: string;\n regime:\n SensorReadoutConversionRegime;\n regimeSelectionOwnedBy:\n \"explicit-upstream-camera-state-not-inferred-from-iso\";\n adcMaximumCode: number;\n combinedReadNoiseRmsElectrons:\n number;\n}\n\nexport interface CalculateExpectedSensorReadoutInput {\n accumulatedCharge:\n SensorAccumulatedChargeComposition;\n physicalCapacityAssessment:\n SensorPhysicalChargeCapacityAssessment;\n readoutProfile:\n SensorReadoutConversionProfile;\n regimeId: string;\n}\n\nexport interface SensorExpectedReadoutSignal {\n readoutProfileId: string;\n regimeId: string;\n completenessProfileId: string;\n capacityProfileId: string;\n colorSamplingProfileId: string;\n channelId: string;\n site: {\n x: number;\n y: number;\n };\n bindingId: string;\n expectedStoredElectronCount:\n number;\n expectedStoredChargeBelowOrAtPhysicalCapacity:\n true;\n expectedElectronEquivalentAfterPreAdcSaturation:\n number;\n preAdcSaturationAppliedToExpectation:\n boolean;\n systemConversionGainElectronsPerCode:\n number;\n expectedCodeBeforeBlackOffset:\n number;\n blackLevelCode: number;\n /** Continuous ADC input code including any declared INL offset. */\n expectedCodeBeforeQuantization:\n number;\n adcIntegralNonLinearityOffsetCodes:\n number;\n digitalGain: number;\n /** Continuous code after post-ADC digital gain about black (equals the ADC input without one). */\n expectedCodeAfterDigitalGain:\n number;\n adcBitDepth: number;\n adcMaximumCode: number;\n digitalSaturationCode: number;\n expectedDigitalSaturation:\n boolean;\n electronicReadNoiseMeanElectrons:\n 0;\n electronicReadNoiseRmsElectrons:\n number;\n electronicReadNoiseSampled: false;\n adcQuantizationApplied: false;\n rawCodeValueProduced: false;\n isoUsedToInferRegime: false;\n}\n\nexport interface SimulateSensorRawCodeInput {\n chargeRealization:\n SensorChargeRealization;\n physicalCapacityAssessment:\n SensorPhysicalChargeCapacityAssessment;\n readoutProfile:\n SensorReadoutConversionProfile;\n regimeId: string;\n readNoiseSeedUint32: number;\n /**\n * Optional fixed pattern; must be the same profile used for the charge realization. Its static\n * row/column offsets are added with read noise before the pre-ADC threshold.\n */\n fixedPatternNoise?:\n SensorFixedPatternNoiseProfile;\n}\n\nexport interface SensorRawCodeSample {\n readoutProfileId: string;\n regimeId: string;\n samplingProfileId: string;\n completenessProfileId: string;\n capacityProfileId: string;\n colorSamplingProfileId: string;\n channelId: string;\n site: {\n x: number;\n y: number;\n };\n bindingId: string;\n chargeSeedUint32: number;\n readNoiseSeedUint32: number;\n realizedStoredElectronEquivalentCountBeforePhysicalCapacity:\n number;\n physicalChargeCapacityElectrons:\n number;\n electronEquivalentAfterPhysicalScalarSaturation:\n number;\n physicalScalarSaturationApplied:\n boolean;\n overflowElectronEquivalentDiagnostic:\n number;\n bloomingModeled: false;\n electronicReadNoiseComponents:\n readonly {\n componentId: string;\n rmsElectrons: number;\n sampledElectrons: number;\n }[];\n totalElectronicReadNoiseElectrons:\n number;\n /** Fixed-pattern profile applied at readout, or null. */\n fixedPatternNoiseProfileId:\n string | null;\n /** Static fixed-pattern row + column offset in input-referred electrons (0 without a pattern). */\n fixedPatternReadoutOffsetElectrons:\n number;\n electronEquivalentAfterReadNoise:\n number;\n preAdcSaturationElectronEquivalent:\n number;\n /** Signed electronic signal after the upper (pre-ADC) clip, before conversion and the black pedestal. */\n electronEquivalentAfterPreAdcSaturation:\n number;\n preAdcSaturationApplied:\n boolean;\n systemConversionGainElectronsPerCode:\n number;\n blackLevelCode: number;\n /** Continuous ADC input code including any declared integral non-linearity offset. */\n codeBeforeQuantization:\n number;\n /** INL offset added before quantization (0 for an ideal ADC). */\n adcIntegralNonLinearityOffsetCodes:\n number;\n /** ADC output after quantization and the ADC code-range limit, before digital gain. */\n adcCodeBeforeDigitalGain:\n number;\n /** Post-ADC digital gain (1 when the regime declares none). */\n digitalGain: number;\n quantizedCodeBeforeDigitalClamp:\n number;\n adcBitDepth: number;\n adcMaximumCode: number;\n digitalSaturationCode: number;\n rawCode: number;\n digitalSaturationApplied:\n boolean;\n lowerCodeClampApplied:\n boolean;\n adcTransfer:\n \"uniform-round-half-up\";\n physicalSaturationApplied: boolean;\n electronicReadNoiseApplied:\n boolean;\n conversionGainApplied: true;\n adcQuantizationApplied: true;\n rawCodeValueProduced: true;\n isoUsedToInferRegime: false;\n deterministicSeededRealization:\n true;\n}\n\nfunction requireUint32(\n value: unknown,\n path: string\n): number {\n if (\n typeof value !== \"number\" ||\n !Number.isSafeInteger(value) ||\n value < 0 ||\n value > 0xffff_ffff\n ) {\n throw new InvalidScientificInputError(\n path +\n \" must be an unsigned 32-bit integer.\"\n );\n }\n return value;\n}\n\nexport function requireSafeInteger(\n value: unknown,\n path: string\n): number {\n if (\n typeof value !== \"number\" ||\n !Number.isSafeInteger(value)\n ) {\n throw new InvalidConfigurationError(\n path + \" must be a safe integer.\"\n );\n }\n return value;\n}\n\nexport function parsePositiveFact(\n value: unknown,\n path: string\n): EvidenceBackedFact<number> {\n const record =\n requireRecord(value, path, [\"value\", \"evidence\"]);\n return {\n value:\n requirePositiveFinite(\n record.value,\n path + \".value\"\n ),\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n )\n };\n}\n\nexport function parseNonNegativeFact(\n value: unknown,\n path: string\n): EvidenceBackedFact<number> {\n const record =\n requireRecord(value, path, [\"value\", \"evidence\"]);\n return {\n value:\n requireNonNegativeFinite(\n record.value,\n path + \".value\"\n ),\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n )\n };\n}\n\n/**\n * Validates untrusted input and returns it as a normalized, typed value. Unknown enum values,\n * missing required fields and inconsistent scientific data are rejected.\n *\n * The profile sets how expected charge is sampled into random photo and dark counts.\n * @param value - Untrusted data. TypeScript types alone are not validation.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function parseSensorChargeSamplingProfile(\n value: unknown\n): SensorChargeSamplingProfile {\n const record =\n requireRecord(\n value,\n \"sensorChargeSamplingProfile\", [\"schemaVersion\", \"scientificStatus\", \"photoShotNoiseModel\", \"darkShotNoiseModel\", \"additionalComponentPolicies\", \"profileId\", \"completenessProfileId\", \"evidence\", \"limitations\"]\n );\n\n if (\n record.schemaVersion !==\n SENSOR_CHARGE_SAMPLING_PROFILE_SCHEMA_VERSION\n ) {\n throw new InvalidConfigurationError(\n 'sensorChargeSamplingProfile.schemaVersion must be \"' +\n SENSOR_CHARGE_SAMPLING_PROFILE_SCHEMA_VERSION +\n '\".'\n );\n }\n if (\n record.scientificStatus !==\n \"approximation\"\n ) {\n throw new InvalidConfigurationError(\n 'sensorChargeSamplingProfile.scientificStatus must be \"approximation\".'\n );\n }\n if (\n record.photoShotNoiseModel !==\n \"poisson\" ||\n record.darkShotNoiseModel !==\n \"poisson\"\n ) {\n throw new InvalidConfigurationError(\n \"sensorChargeSamplingProfile photo/dark shot-noise models must be Poisson.\"\n );\n }\n if (\n !Array.isArray(\n record.additionalComponentPolicies\n )\n ) {\n throw new InvalidConfigurationError(\n \"sensorChargeSamplingProfile.additionalComponentPolicies must be an array.\"\n );\n }\n\n const additionalComponentPolicies =\n record.additionalComponentPolicies.map(\n (entry, index) => {\n const path =\n \"sensorChargeSamplingProfile.additionalComponentPolicies[\" +\n index +\n \"]\";\n const policy =\n requireRecord(\n entry,\n path, [\"model\", \"componentId\"]\n );\n if (\n policy.model !==\n \"poisson\" &&\n policy.model !==\n \"deterministic-expected-electron-equivalent\"\n ) {\n throw new InvalidConfigurationError(\n path +\n \".model is invalid.\"\n );\n }\n return {\n componentId:\n requireNonEmptyString(\n policy.componentId,\n path +\n \".componentId\"\n ),\n model:\n policy.model\n } as SensorAdditionalChargeSamplingPolicy;\n }\n );\n\n const ids =\n additionalComponentPolicies.map(\n (policy) =>\n policy.componentId\n );\n if (\n new Set(ids).size !==\n ids.length\n ) {\n throw new InvalidConfigurationError(\n \"sensorChargeSamplingProfile.additionalComponentPolicies must not contain duplicate componentId values.\"\n );\n }\n\n return {\n schemaVersion:\n SENSOR_CHARGE_SAMPLING_PROFILE_SCHEMA_VERSION,\n profileId:\n requireNonEmptyString(\n record.profileId,\n \"sensorChargeSamplingProfile.profileId\"\n ),\n completenessProfileId:\n requireNonEmptyString(\n record.completenessProfileId,\n \"sensorChargeSamplingProfile.completenessProfileId\"\n ),\n scientificStatus:\n \"approximation\",\n photoShotNoiseModel:\n \"poisson\",\n darkShotNoiseModel:\n \"poisson\",\n additionalComponentPolicies,\n evidence:\n parseEvidenceList(\n record.evidence,\n \"sensorChargeSamplingProfile.evidence\"\n ),\n limitations:\n parseLimitations(\n record.limitations,\n \"sensorChargeSamplingProfile.limitations\"\n )\n };\n}\n\nfunction parseReadNoiseComponent(\n value: unknown,\n path: string\n): SensorElectronicReadNoiseComponent {\n const record =\n requireRecord(value, path, [\"componentId\", \"rmsElectrons\", \"evidence\"]);\n return {\n componentId:\n requireNonEmptyString(\n record.componentId,\n path + \".componentId\"\n ),\n rmsElectrons:\n parseNonNegativeFact(\n record.rmsElectrons,\n path + \".rmsElectrons\"\n ),\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n )\n };\n}\n\nfunction parseIntegralNonLinearity(\n value: unknown,\n path: string,\n adcMaximumCode: number\n): SensorAdcIntegralNonLinearity {\n const record =\n requireRecord(value, path, [\"kind\", \"knots\", \"evidence\"]);\n if (\n record.kind !==\n \"piecewise-linear-code-offset\"\n ) {\n throw new InvalidConfigurationError(\n path +\n '.kind must be \"piecewise-linear-code-offset\".'\n );\n }\n if (\n !Array.isArray(record.knots) ||\n record.knots.length < 2 ||\n record.knots.length > 4096\n ) {\n throw new InvalidConfigurationError(\n path +\n \".knots must contain 2 through 4096 knots.\"\n );\n }\n const knots =\n record.knots.map(\n (entry: unknown, index: number) => {\n const knot =\n requireRecord(\n entry,\n path + \".knots[\" + index + \"]\", [\"code\", \"offsetCodes\"]\n );\n return {\n code: requireFinite(\n knot.code,\n path + \".knots[\" + index + \"].code\"\n ),\n offsetCodes: requireFinite(\n knot.offsetCodes,\n path + \".knots[\" + index + \"].offsetCodes\"\n )\n };\n }\n );\n if (\n knots[0]!.code !== 0 ||\n knots[knots.length - 1]!.code !==\n adcMaximumCode ||\n knots.some(\n (knot, index) =>\n index > 0 &&\n knot.code <=\n knots[index - 1]!.code\n ) ||\n knots.some(\n (knot) =>\n Math.abs(knot.offsetCodes) >\n adcMaximumCode\n )\n ) {\n throw new InvalidConfigurationError(\n path +\n \".knots must strictly increase from code 0 to the ADC maximum code with bounded offsets.\"\n );\n }\n return {\n kind:\n \"piecewise-linear-code-offset\",\n knots,\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n )\n };\n}\n\nfunction parseExposureIndexGain(\n value: unknown,\n path: string,\n adcDigitalGain: number\n): SensorReadoutExposureIndexGain {\n const record =\n requireRecord(value, path, [\"exposureIndex\", \"baseExposureIndex\", \"analogGain\", \"digitalGain\", \"conversionGainMode\", \"evidence\"]);\n const exposureIndex =\n requirePositiveFinite(\n record.exposureIndex,\n path + \".exposureIndex\"\n );\n const baseExposureIndex =\n requirePositiveFinite(\n record.baseExposureIndex,\n path + \".baseExposureIndex\"\n );\n const analogGain =\n requirePositiveFinite(\n record.analogGain,\n path + \".analogGain\"\n );\n const digitalGain =\n requirePositiveFinite(\n record.digitalGain,\n path + \".digitalGain\"\n );\n const mode =\n record.conversionGainMode;\n if (\n mode !== \"single-conversion-gain\" &&\n mode !== \"low-conversion-gain\" &&\n mode !== \"high-conversion-gain\"\n ) {\n throw new InvalidConfigurationError(\n path +\n \".conversionGainMode is invalid.\"\n );\n }\n const ratio =\n exposureIndex /\n baseExposureIndex;\n if (\n digitalGain !==\n adcDigitalGain ||\n Math.abs(\n analogGain * digitalGain -\n ratio\n ) >\n 1e-12 * ratio\n ) {\n throw new InvalidConfigurationError(\n path +\n \" must satisfy analogGain x digitalGain = exposureIndex / baseExposureIndex and digitalGain = adc.digitalGain.\"\n );\n }\n return {\n exposureIndex,\n baseExposureIndex,\n analogGain,\n digitalGain,\n conversionGainMode: mode,\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n )\n };\n}\n\nfunction parseRegime(\n value: unknown,\n path: string\n): SensorReadoutConversionRegime {\n const record =\n requireRecord(value, path, [\"adc\", \"readNoiseComponents\", \"systemConversionGainElectronsPerCode\", \"exposureIndexGain\", \"regimeId\", \"scientificStatus\", \"preAdcSaturationElectronEquivalent\", \"evidence\", \"limitations\"]);\n const adc =\n requireRecord(\n record.adc,\n path + \".adc\", [\"bitDepth\", \"blackLevelCode\", \"digitalSaturationCode\", \"transfer\", \"digitalGain\", \"integralNonLinearity\"]\n );\n const bitDepth =\n requireSafeInteger(\n adc.bitDepth,\n path + \".adc.bitDepth\"\n );\n if (\n bitDepth < 1 ||\n bitDepth > 30\n ) {\n throw new InvalidConfigurationError(\n path +\n \".adc.bitDepth must be from 1 through 30.\"\n );\n }\n const adcMaximumCode =\n 2 ** bitDepth - 1;\n const blackLevelCode =\n requireSafeInteger(\n adc.blackLevelCode,\n path + \".adc.blackLevelCode\"\n );\n const digitalSaturationCode =\n requireSafeInteger(\n adc.digitalSaturationCode,\n path +\n \".adc.digitalSaturationCode\"\n );\n\n if (\n blackLevelCode < 0 ||\n blackLevelCode >\n adcMaximumCode\n ) {\n throw new InvalidConfigurationError(\n path +\n \".adc.blackLevelCode must lie inside the unsigned ADC code range.\"\n );\n }\n if (\n digitalSaturationCode <=\n blackLevelCode ||\n digitalSaturationCode >\n adcMaximumCode\n ) {\n throw new InvalidConfigurationError(\n path +\n \".adc.digitalSaturationCode must be greater than blackLevelCode and at most the ADC maximum code.\"\n );\n }\n if (\n adc.transfer !==\n \"uniform-round-half-up\"\n ) {\n throw new InvalidConfigurationError(\n path +\n '.adc.transfer must be \"uniform-round-half-up\".'\n );\n }\n if (\n !Array.isArray(\n record.readNoiseComponents\n )\n ) {\n throw new InvalidConfigurationError(\n path +\n \".readNoiseComponents must be an array.\"\n );\n }\n const readNoiseComponents =\n record.readNoiseComponents.map(\n (entry, index) =>\n parseReadNoiseComponent(\n entry,\n path +\n \".readNoiseComponents[\" +\n index +\n \"]\"\n )\n );\n const componentIds =\n readNoiseComponents.map(\n (entry) =>\n entry.componentId\n );\n if (\n new Set(componentIds).size !==\n componentIds.length\n ) {\n throw new InvalidConfigurationError(\n path +\n \".readNoiseComponents must not contain duplicate componentId values.\"\n );\n }\n\n const digitalGain =\n adc.digitalGain === undefined\n ? undefined\n : requireFinite(\n adc.digitalGain,\n path + \".adc.digitalGain\"\n );\n if (\n digitalGain !== undefined &&\n (digitalGain < 1 ||\n digitalGain > 65536)\n ) {\n throw new InvalidConfigurationError(\n path +\n \".adc.digitalGain must be from 1 through 65536.\"\n );\n }\n const integralNonLinearity =\n adc.integralNonLinearity === undefined\n ? undefined\n : parseIntegralNonLinearity(\n adc.integralNonLinearity,\n path + \".adc.integralNonLinearity\",\n adcMaximumCode\n );\n const systemConversionGainElectronsPerCode =\n parsePositiveFact(\n record\n .systemConversionGainElectronsPerCode,\n path +\n \".systemConversionGainElectronsPerCode\"\n );\n const exposureIndexGain =\n record.exposureIndexGain === undefined\n ? undefined\n : parseExposureIndexGain(\n record.exposureIndexGain,\n path + \".exposureIndexGain\",\n digitalGain ?? 1\n );\n\n return {\n regimeId:\n requireNonEmptyString(\n record.regimeId,\n path + \".regimeId\"\n ),\n scientificStatus:\n parseStatus(\n record.scientificStatus,\n path +\n \".scientificStatus\"\n ),\n systemConversionGainElectronsPerCode,\n preAdcSaturationElectronEquivalent:\n parsePositiveFact(\n record\n .preAdcSaturationElectronEquivalent,\n path +\n \".preAdcSaturationElectronEquivalent\"\n ),\n readNoiseComponents,\n adc: {\n bitDepth,\n blackLevelCode,\n digitalSaturationCode,\n transfer:\n \"uniform-round-half-up\",\n ...(digitalGain === undefined\n ? {}\n : { digitalGain }),\n ...(integralNonLinearity === undefined\n ? {}\n : { integralNonLinearity })\n },\n ...(exposureIndexGain === undefined\n ? {}\n : { exposureIndexGain }),\n evidence:\n parseEvidenceList(\n record.evidence,\n path + \".evidence\"\n ),\n limitations:\n parseLimitations(\n record.limitations,\n path + \".limitations\"\n )\n };\n}\n\n/**\n * Validates untrusted input and returns it as a normalized, typed value. Unknown enum values,\n * missing required fields and inconsistent scientific data are rejected.\n *\n * The profile lists the declared conversion regimes. ISO never invents a regime.\n * @param value - Untrusted data. TypeScript types alone are not validation.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function parseSensorReadoutConversionProfile(\n value: unknown\n): SensorReadoutConversionProfile {\n const record =\n requireRecord(\n value,\n \"sensorReadoutConversionProfile\", [\"schemaVersion\", \"regimeSelectionOwnedBy\", \"regimes\", \"profileId\", \"colorSamplingProfileId\", \"channelId\", \"evidence\"]\n );\n if (\n record.schemaVersion !==\n SENSOR_READOUT_CONVERSION_PROFILE_SCHEMA_VERSION\n ) {\n throw new InvalidConfigurationError(\n 'sensorReadoutConversionProfile.schemaVersion must be \"' +\n SENSOR_READOUT_CONVERSION_PROFILE_SCHEMA_VERSION +\n '\".'\n );\n }\n if (\n record.regimeSelectionOwnedBy !==\n \"explicit-upstream-camera-state-not-inferred-from-iso\"\n ) {\n throw new InvalidConfigurationError(\n 'sensorReadoutConversionProfile.regimeSelectionOwnedBy must be \"explicit-upstream-camera-state-not-inferred-from-iso\".'\n );\n }\n if (\n !Array.isArray(\n record.regimes\n ) ||\n record.regimes.length === 0\n ) {\n throw new InvalidConfigurationError(\n \"sensorReadoutConversionProfile.regimes must be a non-empty array.\"\n );\n }\n const regimes =\n record.regimes.map(\n (entry, index) =>\n parseRegime(\n entry,\n \"sensorReadoutConversionProfile.regimes[\" +\n index +\n \"]\"\n )\n );\n const ids =\n regimes.map(\n (regime) =>\n regime.regimeId\n );\n if (\n new Set(ids).size !==\n ids.length\n ) {\n throw new InvalidConfigurationError(\n \"sensorReadoutConversionProfile.regimes must not contain duplicate regimeId values.\"\n );\n }\n\n return {\n schemaVersion:\n SENSOR_READOUT_CONVERSION_PROFILE_SCHEMA_VERSION,\n profileId:\n requireNonEmptyString(\n record.profileId,\n \"sensorReadoutConversionProfile.profileId\"\n ),\n colorSamplingProfileId:\n requireNonEmptyString(\n record.colorSamplingProfileId,\n \"sensorReadoutConversionProfile.colorSamplingProfileId\"\n ),\n channelId:\n requireNonEmptyString(\n record.channelId,\n \"sensorReadoutConversionProfile.channelId\"\n ),\n regimes,\n regimeSelectionOwnedBy:\n \"explicit-upstream-camera-state-not-inferred-from-iso\",\n evidence:\n parseEvidenceList(\n record.evidence,\n \"sensorReadoutConversionProfile.evidence\"\n )\n };\n}\n\n/**\n * Selects a declared readout regime and checks it against the exact channel and profile identity.\n * The regime is never inferred from ISO.\n * @param input - The input; see `ResolveSensorReadoutRegimeInput` for its fields, units and coordinates.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function resolveSensorReadoutRegime(\n input:\n ResolveSensorReadoutRegimeInput\n): ResolvedSensorReadoutRegime {\n requireInputKeys(input, \"resolveSensorReadoutRegime\", [\"profile\", \"regimeId\"]);\n const profile =\n parseSensorReadoutConversionProfile(\n input.profile\n );\n if (\n typeof input.regimeId !==\n \"string\" ||\n input.regimeId.trim().length ===\n 0\n ) {\n throw new InvalidConfigurationError(\n \"regimeId must be a non-empty string.\"\n );\n }\n const regimeId =\n input.regimeId.trim();\n const regime =\n profile.regimes.find(\n (entry) =>\n entry.regimeId === regimeId\n );\n if (regime === undefined) {\n throw new InvalidScientificInputError(\n \"regimeId is not declared by the sensor readout conversion profile.\"\n );\n }\n const combinedReadNoiseRmsElectrons =\n Math.sqrt(\n regime.readNoiseComponents.reduce(\n (sum, component) =>\n sum +\n component\n .rmsElectrons.value *\n component\n .rmsElectrons.value,\n 0\n )\n );\n\n return {\n profileId:\n profile.profileId,\n colorSamplingProfileId:\n profile.colorSamplingProfileId,\n channelId:\n profile.channelId,\n regime,\n regimeSelectionOwnedBy:\n profile\n .regimeSelectionOwnedBy,\n adcMaximumCode:\n 2 **\n regime.adc.bitDepth -\n 1,\n combinedReadNoiseRmsElectrons\n };\n}\n\nfunction validateChargeIdentity(\n charge:\n SensorAccumulatedChargeComposition,\n capacity:\n SensorPhysicalChargeCapacityAssessment,\n readout:\n ResolvedSensorReadoutRegime\n): true {\n if (\n charge.completenessProfileId !==\n capacity\n .completenessProfileId ||\n charge.colorSamplingProfileId !==\n capacity\n .colorSamplingProfileId ||\n charge.channelId !==\n capacity.channelId ||\n charge.site.x !==\n capacity.site.x ||\n charge.site.y !==\n capacity.site.y ||\n charge.bindingId !==\n capacity.bindingId\n ) {\n throw new InvalidScientificInputError(\n \"Physical capacity assessment identity must match the accumulated charge.\"\n );\n }\n // The assessment copies the complete expected stored-electron total exactly from the charge it\n // assessed. So the match must be exact: an assessment made for any other charge is out of date.\n if (\n charge\n .totalExpectedStoredElectronCount !==\n capacity\n .totalExpectedStoredElectronCount\n ) {\n throw new InvalidScientificInputError(\n \"Physical capacity assessment must be computed for the supplied accumulated charge; its total expected stored electrons differ.\"\n );\n }\n if (\n readout\n .colorSamplingProfileId !==\n charge.colorSamplingProfileId ||\n readout.channelId !==\n charge.channelId\n ) {\n throw new InvalidScientificInputError(\n \"Sensor readout profile color/channel identity must match the accumulated charge.\"\n );\n }\n const belowOrAtCapacity =\n capacity\n .totalExpectedStoredElectronCount <=\n capacity\n .physicalChargeCapacityElectrons;\n if (\n capacity\n .expectedChargeCapacityStatus ===\n \"above-capacity\" ||\n !belowOrAtCapacity\n ) {\n throw new InvalidScientificInputError(\n \"Expected stored charge above physical capacity cannot enter linear expected readout; the actual post-saturation stored charge is not defined by the upstream assessment.\"\n );\n }\n if (\n charge.saturationAssessed !==\n false ||\n charge.adcQuantizationApplied !==\n false ||\n charge.rawCodeValueProduced !==\n false\n ) {\n throw new InvalidScientificInputError(\n \"Sensor readout requires the unmodified accumulated-charge result.\"\n );\n }\n return belowOrAtCapacity;\n}\n\nfunction additionalPolicyMap(\n profile:\n SensorChargeSamplingProfile,\n charge:\n SensorAccumulatedChargeComposition\n): ReadonlyMap<\n string,\n SensorAdditionalChargeSamplingPolicy\n> {\n if (\n profile.completenessProfileId !==\n charge.completenessProfileId\n ) {\n throw new InvalidScientificInputError(\n \"Charge sampling profile completenessProfileId must match the accumulated charge.\"\n );\n }\n\n const chargeIds =\n charge.additionalComponents.map(\n (component) =>\n component.componentId\n ).sort();\n const policyIds =\n profile\n .additionalComponentPolicies\n .map(\n (policy) =>\n policy.componentId\n )\n .sort();\n\n if (\n chargeIds.length !==\n policyIds.length ||\n chargeIds.some(\n (id, index) =>\n id !== policyIds[index]\n )\n ) {\n throw new InvalidScientificInputError(\n \"Charge sampling profile must declare exactly one policy for every accumulated additional-charge component.\"\n );\n }\n\n return new Map(\n profile.additionalComponentPolicies.map(\n (policy) => [\n policy.componentId,\n policy\n ] as const\n )\n );\n}\n\ntype DeterministicRandom = DeterministicUniformStream;\n\nfunction createRandom(\n seedUint32: number\n): DeterministicRandom {\n return createDeterministicUniformStream(seedUint32);\n}\n\n/**\n * log(n!) for n < 256: entry n is ln 2 + ln 3 + … + ln n, summed in that order, so each entry\n * is bit-identical to summing the logarithms on demand (the partial sums of one loop).\n */\nconst SMALL_LOG_FACTORIALS = ((): Float64Array => {\n const table = new Float64Array(256);\n let sum = 0;\n for (let value = 2; value < 256; value += 1) {\n sum += Math.log(value);\n table[value] = sum;\n }\n return table;\n})();\n\n/**\n * Computes log(n!) without forming the factorial, which would overflow. Small counts\n * sum the logarithms directly (read from a table of the same partial sums). Larger counts\n * use Stirling's formula with the correction terms 1/(12n) - 1/(360n³). This is internal\n * to the Poisson rejection sampler; it is not a claim about physical accuracy or uncertainty.\n */\nfunction logFactorial(\n n: number\n): number {\n if (n < 2) {\n return 0;\n }\n if (n < 256) {\n return SMALL_LOG_FACTORIALS[n]!;\n }\n\n const inverse = 1 / n;\n const inverseCubed =\n inverse * inverse * inverse;\n return (\n (n + 0.5) * Math.log(n) -\n n +\n 0.5 *\n Math.log(\n 2 * Math.PI\n ) +\n inverse / 12 -\n inverseCubed / 360\n );\n}\n\n/** Means at or above this use the continuity-corrected normal approximation. */\nconst POISSON_NORMAL_APPROXIMATION_MINIMUM_MEAN =\n 1e9;\n\n/**\n * Draws a nonnegative integer from a Poisson distribution with the given mean.\n *\n * - Mean 0 returns exactly 0.\n * - Mean below 30: multiply uniform random numbers until the product drops below e^(−mean).\n * - Mean from 30 to below 1e9: Hörmann's (1993) PTRS transformed rejection, comparing log\n * probabilities to avoid overflow.\n * - Mean of 1e9 and above: a continuity-corrected normal approximation, because the log terms lose\n * precision there.\n *\n * The same mean and random stream reproduce the same draw. Increasing the mean does not guarantee\n * that each individual draw increases. Exported internally for the lean native executor, which must\n * draw exactly as simulateSensorChargeRealization does; not exported from the package.\n */\nexport function samplePoisson(\n mean: number,\n random:\n DeterministicRandom\n): number {\n if (\n !Number.isFinite(mean) ||\n mean < 0\n ) {\n throw new InvalidScientificInputError(\n \"Poisson mean must be finite and nonnegative.\"\n );\n }\n if (mean === 0) {\n return 0;\n }\n\n if (\n mean >=\n POISSON_NORMAL_APPROXIMATION_MINIMUM_MEAN\n ) {\n // Above 1e9 the log-probability terms of the rejection test reach about 1e10 and cancel badly\n // (variance/mean is 1.012 at 1e14). Here the continuity-corrected normal approximation has a\n // relative skewness error of 1/sqrt(mean) <= 3.2e-5 (Poisson skewness 1/sqrt(mean): NIST/SEMATECH\n // e-Handbook of Statistical Methods, sec. 1.3.6.6.19, free; normal approximation with continuity\n // correction: SOCR, University of Michigan, free. Also see: Johnson, Kemp & Kotz, Univariate\n // Discrete Distributions, 3rd ed., section 4.4).\n return Math.max(\n 0,\n Math.floor(\n mean +\n Math.sqrt(mean) *\n sampleStandardNormal(\n random\n ) +\n 0.5\n )\n );\n }\n\n if (mean < 30) {\n const threshold =\n Math.exp(-mean);\n let product = 1;\n let count = 0;\n do {\n count += 1;\n product *=\n random.next();\n } while (\n product > threshold\n );\n return count - 1;\n }\n\n const sqrtMean =\n Math.sqrt(mean);\n const b =\n 0.931 +\n 2.53 * sqrtMean;\n const a =\n -0.059 +\n 0.02483 * b;\n const inverseAlpha =\n 1.1239 +\n 1.1328 /\n (b - 3.4);\n const vR =\n 0.9277 -\n 3.6224 /\n (b - 2);\n\n for (;;) {\n const u =\n random.next() - 0.5;\n const v =\n random.next();\n const uS =\n 0.5 - Math.abs(u);\n if (uS <= 0) {\n continue;\n }\n const k =\n Math.floor(\n (2 * a / uS + b) *\n u +\n mean +\n 0.43\n );\n\n if (\n uS >= 0.07 &&\n v <= vR &&\n k >= 0\n ) {\n return k;\n }\n if (\n k < 0 ||\n (\n uS < 0.013 &&\n v > uS\n )\n ) {\n continue;\n }\n\n const lhs =\n Math.log(\n v *\n inverseAlpha /\n (a /\n (uS * uS) +\n b)\n );\n const rhs =\n -mean +\n k * Math.log(mean) -\n logFactorial(k);\n\n if (lhs <= rhs) {\n return k;\n }\n }\n}\n\n/** log(n!) as `logFactorial` computes it, with the portable logarithm (`portableLog`) in place of Math.log. */\nlet portableSmallLogFactorials: Float64Array | undefined;\nfunction portableLogFactorial(n: number): number {\n if (n < 2) return 0;\n if (n < 256) {\n if (!portableSmallLogFactorials) {\n const table = new Float64Array(256);\n let sum = 0;\n for (let value = 2; value < 256; value += 1) { sum += portableLog(value); table[value] = sum; }\n portableSmallLogFactorials = table;\n }\n return portableSmallLogFactorials[n]!;\n }\n const inverse = 1 / n, inverseCubed = inverse * inverse * inverse;\n // 0.5·ln(2π), as logFactorial forms it; computed on first use, so a bundle without the portable sampler need not evaluate it.\n portableHalfLogTwoPi ??= 0.5 * portableLog(2 * Math.PI);\n return (n + 0.5) * portableLog(n) - n + portableHalfLogTwoPi + inverse / 12 - inverseCubed / 360;\n}\nlet portableHalfLogTwoPi: number | undefined;\n\n/**\n * Internal (not exported from the package): `samplePoisson` for one fixed mean, with the per-mean constants (e^(−mean),\n * the PTRS constants and ln mean) computed once. Each draw takes the same branch, reads the same random values and\n * forms every value with the same expressions as `samplePoisson(mean, random)`, so the draws are identical; it is for\n * callers that draw many times with one mean (the display view's AHD correction).\n *\n * With `portable` true, every exponential, logarithm and normal draw uses the engine's portable functions\n * (`portableExp`, `portableLog`, `samplePortableStandardNormal`) instead of Math.exp, Math.log and the Box–Muller of\n * Math.log/Math.cos, so the draws are the same in every JavaScript engine; they then equal `samplePoisson`'s except\n * where a comparison falls within the last-bit difference of those functions. The display view uses this form.\n */\nexport function createPoissonSampler(\n mean: number,\n portable = false\n): (random: DeterministicRandom) => number {\n if (\n !Number.isFinite(mean) ||\n mean < 0\n ) {\n throw new InvalidScientificInputError(\n \"Poisson mean must be finite and nonnegative.\"\n );\n }\n if (mean === 0) {\n return () => 0;\n }\n const exp = portable ? portableExp : Math.exp, log = portable ? portableLog : Math.log;\n const logFactorialOf = portable ? portableLogFactorial : logFactorial;\n if (\n mean >=\n POISSON_NORMAL_APPROXIMATION_MINIMUM_MEAN\n ) {\n if (!portable) return (random) => samplePoisson(mean, random);\n const sqrtMean = Math.sqrt(mean);\n return (random) => Math.max(0, Math.floor(mean + sqrtMean * samplePortableStandardNormal(random) + 0.5));\n }\n if (mean < 30) {\n const threshold =\n exp(-mean);\n return (random) => {\n let product = 1;\n let count = 0;\n do {\n count += 1;\n product *=\n random.next();\n } while (\n product > threshold\n );\n return count - 1;\n };\n }\n const sqrtMean =\n Math.sqrt(mean);\n const b =\n 0.931 +\n 2.53 * sqrtMean;\n const a =\n -0.059 +\n 0.02483 * b;\n const inverseAlpha =\n 1.1239 +\n 1.1328 /\n (b - 3.4);\n const vR =\n 0.9277 -\n 3.6224 /\n (b - 2);\n const logMean =\n log(mean);\n return (random) => {\n for (;;) {\n const u =\n random.next() - 0.5;\n const v =\n random.next();\n const uS =\n 0.5 - Math.abs(u);\n if (uS <= 0) {\n continue;\n }\n const k =\n Math.floor(\n (2 * a / uS + b) *\n u +\n mean +\n 0.43\n );\n if (\n uS >= 0.07 &&\n v <= vR &&\n k >= 0\n ) {\n return k;\n }\n if (\n k < 0 ||\n (\n uS < 0.013 &&\n v > uS\n )\n ) {\n continue;\n }\n const lhs =\n log(\n v *\n inverseAlpha /\n (a /\n (uS * uS) +\n b)\n );\n const rhs =\n -mean +\n k * logMean -\n logFactorialOf(k);\n if (lhs <= rhs) {\n return k;\n }\n }\n };\n}\n\n/**\n * Internal (not exported from the package): draws `count` Poisson samples of one mean from one seeded\n * stream, exactly as the charge realization does. Used by the sampler's distribution tests.\n */\nexport function samplePoissonStreamForValidation(\n mean: number,\n seedUint32: number,\n count: number\n): number[] {\n const random =\n createRandom(seedUint32);\n return Array.from(\n { length: count },\n () =>\n samplePoisson(\n mean,\n random\n )\n );\n}\n\n/**\n * Internal (not exported from the package): draws `count` standard normal values from one seeded\n * stream, exactly as the read-noise path does. Used by the sampler's distribution tests.\n */\nexport function sampleStandardNormalStreamForValidation(\n seedUint32: number,\n count: number\n): number[] {\n const random =\n createRandom(seedUint32);\n return Array.from(\n { length: count },\n () =>\n sampleStandardNormal(\n random\n )\n );\n}\n\nfunction sampleStandardNormal(\n random:\n DeterministicRandom\n): number {\n return sampleDeterministicStandardNormal(random);\n}\n\n/**\n * Draws deterministic, separately seeded Poisson counts for photo and dark charge, and applies the\n * declared policies for additional components, starting from the expected accumulated charge.\n *\n * This is steps 1–2 of the readout order (see the module notes). Physical storage saturation is\n * reported separately from later clipping.\n * @param input - The input; see `SimulateSensorChargeRealizationInput` for its fields, units and coordinates.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function simulateSensorChargeRealization(\n input:\n SimulateSensorChargeRealizationInput\n): CalculationResult<SensorChargeRealization> {\n requireInputKeys(input, \"simulateSensorChargeRealization\", [\"accumulatedCharge\", \"samplingProfile\", \"seedUint32\", \"fixedPatternNoise\"]);\n const profile =\n parseSensorChargeSamplingProfile(\n input.samplingProfile\n );\n const seed =\n requireUint32(\n input.seedUint32,\n \"seedUint32\"\n );\n const charge =\n input.accumulatedCharge;\n\n if (\n charge.accumulatedChargeCompleteness !==\n \"complete-for-physical-storage-capacity-assessment\" ||\n charge.saturationAssessed !==\n false ||\n charge.adcQuantizationApplied !==\n false ||\n charge.rawCodeValueProduced !==\n false\n ) {\n throw new InvalidScientificInputError(\n \"Charge realization requires a complete unsaturated pre-readout accumulated-charge result.\"\n );\n }\n\n const policies =\n additionalPolicyMap(\n profile,\n charge\n );\n const pattern =\n input.fixedPatternNoise === undefined\n ? null\n : fixedPatternAtSite(\n parseSensorFixedPatternNoiseProfile(\n input.fixedPatternNoise\n ),\n charge\n .colorSamplingProfileId,\n charge.site\n );\n const photoGain =\n pattern === null\n ? 1\n : pattern\n .photoResponseGainFactor;\n const darkFactor =\n pattern === null\n ? 1\n : pattern.darkCurrentFactor;\n const photoMean =\n pattern === null\n ? charge\n .photoExpectedElectronCount\n : charge\n .photoExpectedElectronCount *\n photoGain;\n const darkMean =\n pattern === null\n ? charge\n .darkExpectedElectronCount\n : charge\n .darkExpectedElectronCount *\n darkFactor;\n const random =\n createRandom(seed);\n const photoRealized =\n samplePoisson(\n photoMean,\n random\n );\n const darkRealized =\n samplePoisson(\n darkMean,\n random\n );\n\n const additionalComponents =\n charge.additionalComponents.map(\n (component) => {\n const policy =\n policies.get(\n component.componentId\n )!;\n const realized =\n policy.model ===\n \"poisson\"\n ? samplePoisson(\n component\n .expectedElectronCount,\n random\n )\n : component\n .expectedElectronCount;\n return {\n componentId:\n component.componentId,\n expectedElectronCount:\n component\n .expectedElectronCount,\n realizedElectronEquivalentCount:\n realized,\n model:\n policy.model\n };\n }\n );\n\n const additionalRealized =\n additionalComponents.reduce(\n (sum, component) =>\n sum +\n component\n .realizedElectronEquivalentCount,\n 0\n );\n const totalRealized =\n photoRealized +\n darkRealized +\n additionalRealized;\n\n if (\n !Number.isFinite(\n totalRealized\n ) ||\n totalRealized < 0\n ) {\n throw new InvalidScientificInputError(\n \"Realized stored charge must remain finite and nonnegative.\"\n );\n }\n\n return approximationResult(\n {\n samplingProfileId:\n profile.profileId,\n completenessProfileId:\n charge\n .completenessProfileId,\n colorSamplingProfileId:\n charge\n .colorSamplingProfileId,\n channelId:\n charge.channelId,\n site: {\n ...charge.site\n },\n bindingId:\n charge.bindingId,\n seedUint32:\n seed,\n photoExpectedElectronCount:\n charge\n .photoExpectedElectronCount,\n photoRealizedElectronCount:\n photoRealized,\n darkExpectedElectronCount:\n charge\n .darkExpectedElectronCount,\n darkRealizedElectronCount:\n darkRealized,\n fixedPatternNoiseProfileId:\n pattern === null\n ? null\n : pattern.profileId,\n photoResponseGainFactor:\n photoGain,\n darkCurrentFactor:\n darkFactor,\n hotPixel:\n pattern?.hotPixel ?? false,\n photoSampledMeanElectronCount:\n photoMean,\n darkSampledMeanElectronCount:\n darkMean,\n additionalComponents,\n totalExpectedStoredElectronCount:\n charge\n .totalExpectedStoredElectronCount,\n totalRealizedStoredElectronEquivalentCount:\n totalRealized,\n photoShotNoiseApplied:\n true,\n darkShotNoiseApplied:\n true,\n electronicReadNoiseApplied:\n false,\n physicalSaturationApplied:\n false,\n bloomingModeled: false,\n conversionGainApplied:\n false,\n adcQuantizationApplied:\n false,\n rawCodeValueProduced:\n false,\n stochasticModel:\n \"independent-poisson-photo-dark-explicit-additional-policy\",\n deterministicSeededRealization:\n true\n },\n \"sensor-charge-stochastic-realization\",\n \"3.0.0\",\n [\n \"An optional explicit fixed-pattern profile multiplies the photo Poisson mean by the site's PRNU gain and the dark Poisson mean by its DSNU/hot-pixel factor; without one the uniform population expectation is sampled. Fixed-pattern values are deterministic per sensor instance and colour-sampling site.\",\n \"Poisson means of 1e9 electrons and above use a continuity-corrected normal approximation.\",\n \"Photo-generated and dark-generated electron counts are sampled independently from Poisson distributions using an explicit deterministic seed.\",\n \"Each additional stored-charge component uses its explicitly declared Poisson or deterministic electron-equivalent policy; Photivra does not infer defect/leakage statistics from the component name.\",\n \"This is a pre-saturation, pre-electronic-read-noise charge realization and remains separate from expectation-value calculations.\",\n \"The seeded PRNG is a deterministic simulation mechanism and is not cryptographically secure; its seed is scrambled by the MurmurHash3 fmix32 finalizer so nearby seeds give unrelated streams.\"\n ]\n );\n}\n\nfunction fixedPatternAtSite(\n profile:\n SensorFixedPatternNoiseProfile,\n colorSamplingProfileId: string,\n site: { x: number; y: number }\n): SensorFixedPatternSiteValues {\n if (\n profile.colorSamplingProfileId !==\n colorSamplingProfileId\n ) {\n throw new InvalidScientificInputError(\n \"Fixed-pattern noise profile colour-sampling identity must match the charge.\"\n );\n }\n return evaluateParsedFixedPatternSite(\n profile,\n site\n );\n}\n\nfunction fixedPatternForRealization(\n value:\n SensorFixedPatternNoiseProfile | undefined,\n charge:\n SensorChargeRealization\n): SensorFixedPatternSiteValues | null {\n if (value === undefined) {\n if (\n charge.fixedPatternNoiseProfileId !==\n null &&\n charge.fixedPatternNoiseProfileId !==\n undefined\n ) {\n throw new InvalidScientificInputError(\n \"A charge realization with a fixed pattern requires the same fixed-pattern profile at readout.\"\n );\n }\n return null;\n }\n const profile =\n parseSensorFixedPatternNoiseProfile(\n value\n );\n if (\n charge.fixedPatternNoiseProfileId !==\n profile.profileId\n ) {\n throw new InvalidScientificInputError(\n \"Readout fixed-pattern profile must be the profile used for the charge realization.\"\n );\n }\n return fixedPatternAtSite(\n profile,\n charge.colorSamplingProfileId,\n charge.site\n );\n}\n\nfunction validateCapacityAgainstRealization(\n charge:\n SensorChargeRealization,\n capacity:\n SensorPhysicalChargeCapacityAssessment,\n readout:\n ResolvedSensorReadoutRegime\n): void {\n if (\n charge.completenessProfileId !==\n capacity\n .completenessProfileId ||\n charge.colorSamplingProfileId !==\n capacity\n .colorSamplingProfileId ||\n charge.channelId !==\n capacity.channelId ||\n charge.site.x !==\n capacity.site.x ||\n charge.site.y !==\n capacity.site.y ||\n charge.bindingId !==\n capacity.bindingId\n ) {\n throw new InvalidScientificInputError(\n \"Physical capacity assessment identity must match the charge realization.\"\n );\n }\n if (\n charge\n .totalExpectedStoredElectronCount !==\n capacity\n .totalExpectedStoredElectronCount\n ) {\n throw new InvalidScientificInputError(\n \"Physical capacity assessment must be computed for the charge behind the realization; its total expected stored electrons differ.\"\n );\n }\n if (\n readout\n .colorSamplingProfileId !==\n charge.colorSamplingProfileId ||\n readout.channelId !==\n charge.channelId\n ) {\n throw new InvalidScientificInputError(\n \"Sensor readout profile color/channel identity must match the charge realization.\"\n );\n }\n}\n\n/**\n * Maps the expected charge through the declared gain, offset and readout limits, with no random\n * sampling. Each kind of clipping (physical storage, pre-ADC, digital) is reported separately.\n * @param input - The input; see `CalculateExpectedSensorReadoutInput` for its fields, units and coordinates.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function calculateExpectedSensorReadout(\n input:\n CalculateExpectedSensorReadoutInput\n): CalculationResult<SensorExpectedReadoutSignal> {\n requireInputKeys(input, \"calculateExpectedSensorReadout\", [\"accumulatedCharge\", \"physicalCapacityAssessment\", \"readoutProfile\", \"regimeId\"]);\n const readout =\n resolveSensorReadoutRegime({\n profile:\n input.readoutProfile,\n regimeId:\n input.regimeId\n });\n const expectedStoredChargeBelowOrAtPhysicalCapacity =\n validateChargeIdentity(\n input.accumulatedCharge,\n input\n .physicalCapacityAssessment,\n readout\n );\n\n const expected =\n input.accumulatedCharge\n .totalExpectedStoredElectronCount;\n const threshold =\n readout.regime\n .preAdcSaturationElectronEquivalent\n .value;\n const afterPreAdc =\n Math.min(\n expected,\n threshold\n );\n const codeSignal =\n afterPreAdc /\n readout.regime\n .systemConversionGainElectronsPerCode\n .value;\n const inlOffset =\n integralNonLinearityOffset(\n readout.regime.adc\n .integralNonLinearity,\n codeSignal +\n readout.regime\n .adc.blackLevelCode\n );\n const codeBeforeQuantization =\n codeSignal +\n readout.regime\n .adc.blackLevelCode +\n inlOffset;\n const digitalGain =\n readout.regime.adc\n .digitalGain ?? 1;\n const codeAfterDigitalGain =\n readout.regime.adc\n .digitalGain === undefined\n ? codeBeforeQuantization\n : (Math.min(\n codeBeforeQuantization,\n readout.adcMaximumCode\n ) -\n readout.regime.adc\n .blackLevelCode) *\n digitalGain +\n readout.regime.adc\n .blackLevelCode;\n\n return approximationResult(\n {\n readoutProfileId:\n readout.profileId,\n regimeId:\n readout.regime\n .regimeId,\n completenessProfileId:\n input.accumulatedCharge\n .completenessProfileId,\n capacityProfileId:\n input\n .physicalCapacityAssessment\n .capacityProfileId,\n colorSamplingProfileId:\n input.accumulatedCharge\n .colorSamplingProfileId,\n channelId:\n input.accumulatedCharge\n .channelId,\n site: {\n ...input\n .accumulatedCharge\n .site\n },\n bindingId:\n input.accumulatedCharge\n .bindingId,\n expectedStoredElectronCount:\n expected,\n expectedStoredChargeBelowOrAtPhysicalCapacity,\n expectedElectronEquivalentAfterPreAdcSaturation:\n afterPreAdc,\n preAdcSaturationAppliedToExpectation:\n afterPreAdc < expected,\n systemConversionGainElectronsPerCode:\n readout.regime\n .systemConversionGainElectronsPerCode\n .value,\n expectedCodeBeforeBlackOffset:\n codeSignal,\n blackLevelCode:\n readout.regime\n .adc.blackLevelCode,\n expectedCodeBeforeQuantization:\n codeBeforeQuantization,\n adcIntegralNonLinearityOffsetCodes:\n inlOffset,\n digitalGain,\n expectedCodeAfterDigitalGain:\n codeAfterDigitalGain,\n adcBitDepth:\n readout.regime\n .adc.bitDepth,\n adcMaximumCode:\n readout.adcMaximumCode,\n digitalSaturationCode:\n readout.regime\n .adc\n .digitalSaturationCode,\n expectedDigitalSaturation:\n codeAfterDigitalGain >=\n readout.regime\n .adc\n .digitalSaturationCode,\n electronicReadNoiseMeanElectrons:\n 0,\n electronicReadNoiseRmsElectrons:\n readout\n .combinedReadNoiseRmsElectrons,\n electronicReadNoiseSampled:\n false,\n adcQuantizationApplied:\n false,\n rawCodeValueProduced:\n false,\n isoUsedToInferRegime:\n false\n },\n \"sensor-expected-electronic-readout\",\n \"2.0.0\",\n [\n \"Expected readout uses complete expected stored charge only after the upstream physical-capacity assessment confirms the expectation is not above physical capacity.\",\n \"Electronic read-noise mean is zero and is not sampled in this expectation result.\",\n \"The explicitly selected conversion regime is not inferred from ISO, sensor technology family or marketing mode names; an ISO signal chain may bind an exposure index to a declared regime.\",\n \"Declared ADC integral non-linearity and post-ADC digital gain are applied to the continuous expectation without quantization.\",\n \"Pre-ADC electron-equivalent saturation, black offset and ADC/digital saturation remain separate domains.\",\n \"ADC quantization is not applied to the expectation value.\"\n ]\n );\n}\n\n/**\n * Nearest integer, with ties going towards +infinity. Math.round is exact for every double. (In\n * contrast, floor(x + 0.5) returns 1 for 0.49999999999999994, because the addition rounds up.)\n * Adding 0 turns -0 into +0.\n */\nfunction roundHalfUp(\n value: number\n): number {\n return Math.round(value) + 0;\n}\n\nfunction integralNonLinearityOffset(\n inl:\n SensorAdcIntegralNonLinearity | undefined,\n code: number\n): number {\n if (inl === undefined) {\n return 0;\n }\n const knots = inl.knots;\n const first = knots[0]!;\n const last = knots[knots.length - 1]!;\n if (code <= first.code) {\n return first.offsetCodes;\n }\n if (code >= last.code) {\n return last.offsetCodes;\n }\n let low = 0;\n let high = knots.length - 1;\n while (high - low > 1) {\n const middle = (low + high) >> 1;\n if (knots[middle]!.code <= code) {\n low = middle;\n } else {\n high = middle;\n }\n }\n const a = knots[low]!;\n const b = knots[high]!;\n return (\n a.offsetCodes +\n ((code - a.code) /\n (b.code - a.code)) *\n (b.offsetCodes - a.offsetCodes)\n );\n}\n\n/**\n * Shared ADC transfer function: continuous input code (signal/gain + black + INL), rounded half up\n * and limited to the ADC code range, then optional post-ADC digital gain about black, rounded again.\n * The caller applies the final clamp to [0, digitalSaturationCode]. Exported internally for the lean\n * native executor; not exported from the package.\n */\nexport function adcTransfer(\n regime:\n SensorReadoutConversionRegime,\n adcMaximumCode: number,\n electronEquivalent: number\n): {\n codeBeforeQuantization: number;\n inlOffset: number;\n adcCode: number;\n digitalGain: number;\n quantized: number;\n} {\n const ideal =\n electronEquivalent /\n regime\n .systemConversionGainElectronsPerCode\n .value +\n regime.adc.blackLevelCode;\n const inlOffset =\n integralNonLinearityOffset(\n regime.adc.integralNonLinearity,\n ideal\n );\n const codeBeforeQuantization =\n ideal + inlOffset;\n const quantizedAdc =\n roundHalfUp(\n codeBeforeQuantization\n );\n const digitalGain =\n regime.adc.digitalGain ?? 1;\n if (\n regime.adc.digitalGain ===\n undefined\n ) {\n return {\n codeBeforeQuantization,\n inlOffset,\n adcCode:\n quantizedAdc,\n digitalGain,\n quantized:\n quantizedAdc\n };\n }\n const adcCode =\n Math.max(\n 0,\n Math.min(\n quantizedAdc,\n adcMaximumCode\n )\n );\n return {\n codeBeforeQuantization,\n inlOffset,\n adcCode,\n digitalGain,\n quantized:\n roundHalfUp(\n (adcCode -\n regime.adc\n .blackLevelCode) *\n digitalGain +\n regime.adc\n .blackLevelCode\n )\n };\n}\n\n/**\n * Simulates one RAW code from a charge realization with the declared seed and regime: steps 3–7 of\n * the readout order (see the module notes). Signed read noise is kept through the black pedestal and\n * quantization, and only the final code is clamped. Returns the bounded native ADC code and per-step\n * diagnostics.\n * @param input - The input; see `SimulateSensorRawCodeInput` for its fields, units and coordinates.\n * @returns The result. Success does not imply calibration.\n *\n * @see docs/API_REFERENCE.md for the package export and its full type definitions.\n */\nexport function simulateSensorRawCode(\n input:\n SimulateSensorRawCodeInput\n): CalculationResult<SensorRawCodeSample> {\n requireInputKeys(input, \"simulateSensorRawCode\", [\"chargeRealization\", \"physicalCapacityAssessment\", \"readoutProfile\", \"regimeId\", \"readNoiseSeedUint32\", \"fixedPatternNoise\"]);\n const readout =\n resolveSensorReadoutRegime({\n profile:\n input.readoutProfile,\n regimeId:\n input.regimeId\n });\n validateCapacityAgainstRealization(\n input.chargeRealization,\n input\n .physicalCapacityAssessment,\n readout\n );\n const readNoiseSeed =\n requireUint32(\n input.readNoiseSeedUint32,\n \"readNoiseSeedUint32\"\n );\n const random =\n createRandom(\n readNoiseSeed\n );\n\n const realized =\n input.chargeRealization\n .totalRealizedStoredElectronEquivalentCount;\n if (\n !Number.isFinite(realized) ||\n realized < 0\n ) {\n throw new InvalidScientificInputError(\n \"Charge realization total must be finite and nonnegative.\"\n );\n }\n\n const physicalCapacity =\n input\n .physicalCapacityAssessment\n .physicalChargeCapacityElectrons;\n const afterPhysical =\n Math.min(\n realized,\n physicalCapacity\n );\n const physicalSaturation =\n afterPhysical < realized;\n const overflow =\n Math.max(\n 0,\n realized -\n physicalCapacity\n );\n\n const readNoiseComponents =\n readout.regime\n .readNoiseComponents.map(\n (component) => {\n const sampled =\n component\n .rmsElectrons.value ===\n 0\n ? 0\n : sampleStandardNormal(\n random\n ) *\n component\n .rmsElectrons.value;\n return {\n componentId:\n component\n .componentId,\n rmsElectrons:\n component\n .rmsElectrons\n .value,\n sampledElectrons:\n sampled\n };\n }\n );\n const totalReadNoise =\n readNoiseComponents.reduce(\n (sum, component) =>\n sum +\n component\n .sampledElectrons,\n 0\n );\n const pattern =\n fixedPatternForRealization(\n input.fixedPatternNoise,\n input.chargeRealization\n );\n const fixedPatternOffset =\n pattern === null\n ? 0\n : pattern\n .readoutOffsetElectrons;\n\n const afterReadNoise =\n afterPhysical +\n totalReadNoise +\n fixedPatternOffset;\n const preAdcThreshold =\n readout.regime\n .preAdcSaturationElectronEquivalent\n .value;\n // Stored charge is nonnegative, but the electronic signal after it is signed.\n // Keep negative read noise until the black pedestal and the unsigned ADC limit.\n const afterPreAdc =\n Math.min(\n afterReadNoise,\n preAdcThreshold\n );\n const preAdcSaturation =\n afterReadNoise >\n preAdcThreshold;\n\n const transfer =\n adcTransfer(\n readout.regime,\n readout.adcMaximumCode,\n afterPreAdc\n );\n const codeBeforeQuantization =\n transfer.codeBeforeQuantization;\n const quantized =\n transfer.quantized;\n const rawCode =\n Math.max(\n 0,\n Math.min(\n quantized,\n readout.regime\n .adc\n .digitalSaturationCode\n )\n );\n\n return approximationResult(\n {\n readoutProfileId:\n readout.profileId,\n regimeId:\n readout.regime\n .regimeId,\n samplingProfileId:\n input.chargeRealization\n .samplingProfileId,\n completenessProfileId:\n input.chargeRealization\n .completenessProfileId,\n capacityProfileId:\n input\n .physicalCapacityAssessment\n .capacityProfileId,\n colorSamplingProfileId:\n input.chargeRealization\n .colorSamplingProfileId,\n channelId:\n input.chargeRealization\n .channelId,\n site: {\n ...input\n .chargeRealization.site\n },\n bindingId:\n input.chargeRealization\n .bindingId,\n chargeSeedUint32:\n input.chargeRealization\n .seedUint32,\n readNoiseSeedUint32:\n readNoiseSeed,\n realizedStoredElectronEquivalentCountBeforePhysicalCapacity:\n realized,\n physicalChargeCapacityElectrons:\n physicalCapacity,\n electronEquivalentAfterPhysicalScalarSaturation:\n afterPhysical,\n physicalScalarSaturationApplied:\n physicalSaturation,\n overflowElectronEquivalentDiagnostic:\n overflow,\n bloomingModeled: false,\n electronicReadNoiseComponents:\n readNoiseComponents,\n totalElectronicReadNoiseElectrons:\n totalReadNoise,\n fixedPatternNoiseProfileId:\n pattern === null\n ? null\n : pattern.profileId,\n fixedPatternReadoutOffsetElectrons:\n fixedPatternOffset,\n electronEquivalentAfterReadNoise:\n afterReadNoise,\n preAdcSaturationElectronEquivalent:\n preAdcThreshold,\n electronEquivalentAfterPreAdcSaturation:\n afterPreAdc,\n preAdcSaturationApplied:\n preAdcSaturation,\n systemConversionGainElectronsPerCode:\n readout.regime\n .systemConversionGainElectronsPerCode\n .value,\n blackLevelCode:\n readout.regime\n .adc.blackLevelCode,\n codeBeforeQuantization,\n adcIntegralNonLinearityOffsetCodes:\n transfer.inlOffset,\n adcCodeBeforeDigitalGain:\n transfer.adcCode,\n digitalGain:\n transfer.digitalGain,\n quantizedCodeBeforeDigitalClamp:\n quantized,\n adcBitDepth:\n readout.regime\n .adc.bitDepth,\n adcMaximumCode:\n readout.adcMaximumCode,\n digitalSaturationCode:\n readout.regime\n .adc\n .digitalSaturationCode,\n rawCode,\n digitalSaturationApplied:\n quantized >=\n readout.regime\n .adc\n .digitalSaturationCode,\n lowerCodeClampApplied:\n quantized < 0,\n adcTransfer:\n \"uniform-round-half-up\",\n physicalSaturationApplied:\n physicalSaturation,\n electronicReadNoiseApplied:\n readNoiseComponents\n .some(\n (component) =>\n component\n .rmsElectrons >\n 0\n ),\n conversionGainApplied:\n true,\n adcQuantizationApplied:\n true,\n rawCodeValueProduced:\n true,\n isoUsedToInferRegime:\n false,\n deterministicSeededRealization:\n true\n },\n \"sensor-raw-code-stochastic-readout\",\n \"4.0.0\",\n [\n \"A stochastic stored-charge realization is scalar-clamped at the explicit physical storage capacity; this is a bounded saturation approximation and does not model blooming, neighbor transport or anti-blooming behavior.\",\n \"Independent input-referred Gaussian electronic read-noise components, plus any declared static fixed-pattern row/column offsets, are added after physical charge saturation and before the explicit pre-ADC electron-equivalent saturation threshold.\",\n \"System conversion gain is expressed in electrons per digital-number code unit for the explicitly selected regime; an ISO-dependent gain exists only where an explicit ISO signal chain binds the setting to a declared regime.\",\n \"Signed electronic read noise survives the upper-only pre-ADC saturation threshold. Black level and any declared ADC integral non-linearity are added before uniform round-half-up quantization (exact ties toward +infinity); an optional post-ADC digital gain about black is re-quantized; codes are then clamped to zero/digital saturation and valid below-black codes are retained.\",\n \"Physical storage capacity, pre-ADC saturation and digital/ADC saturation remain separate thresholds.\",\n \"The charge seed and read-noise seed are separate deterministic simulation identities; neither is cryptographically secure.\"\n ]\n );\n}\n"]}
|
|
@@ -17,72 +17,10 @@ import { computeEffectiveSaturationCode } from "../capture/raw-white-level.js";
|
|
|
17
17
|
import { parseEvidenceList } from "../core/evidence-provenance.js";
|
|
18
18
|
import { InvalidScientificInputError } from "../core/validation.js";
|
|
19
19
|
import { parseSensorColorSamplingProfile, resolveColorSamplingSite } from "./color-sampling.js";
|
|
20
|
-
import { requireInputObject, requireInputKeys,
|
|
20
|
+
import { requireInputObject, requireInputKeys, requireConfigRecord as requireRecord, requireTrimmedConfigString as requireNonEmptyString, requireConfigFinite as requireFinite, parseConfigScientificStatus as parseStatus, requireInputNonNegativeSafeInteger as requireNonNegativeSafeIntegerInput, parseConfigLimitations as parseLimitations } from "../core/record-validation.js";
|
|
21
|
+
import { requireSafeInteger } from "./raw-readout.js";
|
|
21
22
|
export const SENSOR_RAW_CAPTURE_SAMPLE_VERSION = "0.1.0";
|
|
22
23
|
export const SENSOR_RAW_RECONSTRUCTION_PROFILE_SCHEMA_VERSION = "0.1.0";
|
|
23
|
-
function requireRecord(value, path, allowedKeys) {
|
|
24
|
-
if (typeof value !== "object" ||
|
|
25
|
-
value === null ||
|
|
26
|
-
Array.isArray(value)) {
|
|
27
|
-
throw new InvalidConfigurationError(path + " must be an object.");
|
|
28
|
-
}
|
|
29
|
-
if (allowedKeys !== null)
|
|
30
|
-
rejectUnknownFields(value, allowedKeys, path);
|
|
31
|
-
return value;
|
|
32
|
-
}
|
|
33
|
-
function requireNonEmptyString(value, path) {
|
|
34
|
-
if (typeof value !== "string" ||
|
|
35
|
-
value.trim().length === 0) {
|
|
36
|
-
throw new InvalidConfigurationError(path +
|
|
37
|
-
" must be a non-empty string.");
|
|
38
|
-
}
|
|
39
|
-
return value.trim();
|
|
40
|
-
}
|
|
41
|
-
function requireFinite(value, path) {
|
|
42
|
-
if (typeof value !== "number" ||
|
|
43
|
-
!Number.isFinite(value)) {
|
|
44
|
-
throw new InvalidConfigurationError(path + " must be finite.");
|
|
45
|
-
}
|
|
46
|
-
return value;
|
|
47
|
-
}
|
|
48
|
-
function requireSafeInteger(value, path) {
|
|
49
|
-
if (typeof value !== "number" ||
|
|
50
|
-
!Number.isSafeInteger(value)) {
|
|
51
|
-
throw new InvalidConfigurationError(path + " must be a safe integer.");
|
|
52
|
-
}
|
|
53
|
-
return value;
|
|
54
|
-
}
|
|
55
|
-
function requireNonNegativeSafeIntegerInput(value, path) {
|
|
56
|
-
if (typeof value !== "number" ||
|
|
57
|
-
!Number.isSafeInteger(value) ||
|
|
58
|
-
value < 0) {
|
|
59
|
-
throw new InvalidScientificInputError(path +
|
|
60
|
-
" must be a non-negative safe integer.");
|
|
61
|
-
}
|
|
62
|
-
return value;
|
|
63
|
-
}
|
|
64
|
-
function parseLimitations(value, path) {
|
|
65
|
-
if (!Array.isArray(value)) {
|
|
66
|
-
throw new InvalidConfigurationError(path + " must be an array.");
|
|
67
|
-
}
|
|
68
|
-
const parsed = value.map((entry, index) => requireNonEmptyString(entry, path +
|
|
69
|
-
"[" +
|
|
70
|
-
index +
|
|
71
|
-
"]"));
|
|
72
|
-
if (new Set(parsed).size !==
|
|
73
|
-
parsed.length) {
|
|
74
|
-
throw new InvalidConfigurationError(path +
|
|
75
|
-
" must not contain duplicates.");
|
|
76
|
-
}
|
|
77
|
-
return parsed;
|
|
78
|
-
}
|
|
79
|
-
function parseStatus(value, path) {
|
|
80
|
-
if (value !== "calibrated" &&
|
|
81
|
-
value !== "approximation") {
|
|
82
|
-
throw new InvalidConfigurationError(path + " is invalid.");
|
|
83
|
-
}
|
|
84
|
-
return value;
|
|
85
|
-
}
|
|
86
24
|
function parseContribution(value, path) {
|
|
87
25
|
const record = requireRecord(value, path, ["offsetX", "offsetY", "sourceChannelId", "weight"]);
|
|
88
26
|
return {
|