Skip to content

05_03_04_numerical_specifications - Estado del Proyecto

✅ COMPLETADO

Fecha de completación: 2025-10-10

📊 Métricas Finales

  • Tests: 38/38 pasando ✅
  • Cobertura: 100% ✅
  • Líneas de código: ~1,600 LOC
  • Ejemplos funcionales: 2
  • Documentación: Completa

🎯 Objetivos Alcanzados

1. Sistema de Formatos Numéricos ✅

  • FixedPointFormat con Q notation
  • FloatingPointFormat (float32, float64, bfloat16)
  • Cálculo de rangos y resolución
  • SNR teórico automático
  • Recomendaciones de accumulator width

2. Especificación de Rangos Dinámicos ✅

  • Clase ValueRange para señales y parámetros
  • Validación de valores contra rangos
  • Cálculo de headroom en dB
  • Soporte para escalas lineales y logarítmicas

3. Sistema de Tolerancias ✅

  • Clase Tolerance con múltiples tipos
  • Absolute tolerance
  • Relative percentage tolerance
  • Relative dB tolerance
  • LSB tolerance
  • Validación automática expected vs actual

4. Manejo de Overflow/Underflow ✅

  • Enums para comportamientos
  • Saturation, wrapping, warning
  • Flush-to-zero vs gradual underflow
  • Detección de riesgo de overflow
  • Verificación de headroom

5. Especificación Completa ✅

  • Clase NumericalSpecification unificada
  • Validación de señales y coeficientes
  • Cálculo de SNR teórico
  • Cálculo de ENOB
  • Generación de reportes
  • Detección de riesgos de overflow

6. Factory Functions ✅

  • create_standard_audio_spec(bit_depth)
  • create_fixed_point_biquad_spec(q_format)
  • Specs predefinidos para 16/24/32-bit audio
  • Notas de implementación automáticas

7. Suite de Tests ✅

TestFixedPointFormat (6 tests): - Q1.15 format, range, resolution - Q1.23 format - Unsigned formats - String representation

TestFloatingPointFormat (4 tests): - float32/float64 formats - Dynamic range calculation - String representation

TestValueRange (4 tests): - Normalized audio range - Validation - Headroom calculation - String representation

TestTolerance (4 tests): - Absolute tolerance - Relative percent - Relative dB - String representation

TestNumericalSpecification (10 tests): - Basic specification - Signal/coefficient validation - Theoretical SNR (fixed/float) - ENOB calculation - Accumulator width recommendation - Overflow risk detection - Headroom checking - Report generation

TestFactoryFunctions (6 tests): - 16/24/32-bit audio specs - Biquad spec creation - Implementation notes - Invalid bit depth handling

TestEdgeCases (4 tests): - Zero tolerance checking - Negative headroom - Missing range validation - Overflow with no ranges

8. Ejemplos Funcionales ✅

  • format_comparison.py - Comparación de formatos numéricos
  • overflow_analysis.py - Análisis de overflow y headroom

🏗️ Arquitectura Implementada

numerical_spec.py
├── Enums
│   ├── PrecisionType (FIXED_POINT, FLOATING_POINT, INTEGER)
│   ├── OverflowBehavior (SATURATION, WRAPPING, WARNING)
│   ├── UnderflowBehavior (FLUSH_TO_ZERO, GRADUAL)
│   ├── ToleranceType (ABSOLUTE, RELATIVE_PERCENT, RELATIVE_DB, LSB)
│   └── ScalingStrategy (L1_NORM, L2_NORM, INFINITY_NORM)
├── FixedPointFormat
│   ├── integer_bits, fractional_bits, is_signed
│   ├── total_bits, q_notation
│   ├── range_min, range_max, resolution
│   └── __str__()
├── FloatingPointFormat
│   ├── mantissa_bits, exponent_bits
│   ├── total_bits, precision_bits
│   ├── dynamic_range_db
│   └── __str__()
├── ValueRange
│   ├── min_value, max_value, units, scale
│   ├── contains(value)
│   ├── validate(value)
│   ├── headroom_db(nominal_max)
│   └── __str__()
├── Tolerance
│   ├── value, tolerance_type
│   ├── check(expected, actual)
│   └── __str__()
├── NumericalSpecification
│   ├── precision_type
│   ├── signal_format, coefficient_format, accumulator_format
│   ├── input_range, output_range, internal_range
│   ├── overflow_behavior, underflow_behavior
│   ├── coefficient_tolerance, output_tolerance
│   ├── scaling_strategy, headroom_db
│   ├── expected_snr_db, max_thd_n_percent
│   │
│   ├── validate_signal_range(value, stage)
│   ├── validate_coefficient(value)
│   ├── calculate_theoretical_snr()
│   ├── calculate_enob(measured_sinad_db)
│   ├── recommend_accumulator_width()
│   ├── check_overflow_risk(max_gain)
│   └── generate_report()
└── Factory Functions
    ├── create_standard_audio_spec(bit_depth)
    └── create_fixed_point_biquad_spec(q_format)

📈 Resultados de Ejemplo

Standard Audio Formats

16-bit Audio:
  Format:         Q1.15 (16-bit signed)
  Accumulator:    Q1.31 (32-bit signed)
  SNR (expected): 96.0 dB
  Resolution:     0.0000305176 (LSB)

24-bit Audio:
  Format:         Q1.23 (24-bit signed)
  Accumulator:    Q1.47 (48-bit signed)
  SNR (expected): 144.0 dB
  Resolution:     0.0000001192 (LSB)

32-bit Audio:
  Format:         float32 (23m + 8e)
  SNR (expected): 144.0 dB
  Dynamic range:  ~192 dB

Q Format Comparison

Format    Bits    Resolution              Range                 SNR (dB)
Q1.7      8       0.007812500000          [-2.0, 1.992188]      49.9
Q1.15     16      0.000030517578          [-2.0, 1.999969]      98.1
Q1.23     24      0.000000119209          [-2.0, 2.000000]      146.2
Q1.31     32      0.000000000466          [-2.0, 2.000000]      194.4

Overflow Risk Analysis

Standard Audio (6 dB headroom):
  Gain 0.5x: ✓ OK    No overflow risk detected
  Gain 1.0x: ✓ OK    No overflow risk detected
  Gain 1.5x: ⚠️  RISK  Overflow risk: 3.5 dB above maximum
  Gain 2.0x: ⚠️  RISK  Overflow risk: 6.0 dB above maximum

Headroom Recommendations

Application                  Headroom    Linear    Rationale
Simple gain/filter           3.0 dB      1.41x     Minimal processing
EQ chain (3-5 bands)         6.0 dB      2.00x     Multiple filters may peak-align
Compressor/Limiter           12.0 dB     3.98x     Handles extreme dynamics
Reverb/Delay feedback        12.0 dB     3.98x     Multiple taps sum together
Complex multi-FX             18.0 dB     7.94x     Many processing stages

🔧 Tecnologías Utilizadas

  • Python 3.12 con type hints
  • dataclasses para estructuras
  • Enum para tipos
  • math para cálculos
  • unittest para testing

📝 Fórmulas Implementadas

SNR Teórico

# Fixed-point (N-bit quantization):
SNR = 6.02 * N + 1.76 dB

# Floating-point (M-bit mantissa):
SNR = 6.02 * (M + 1) dB  # +1 for implicit bit

ENOB (Effective Number of Bits)

ENOB = (SINAD - 1.76) / 6.02

Headroom

headroom_dB = 20 * log10(max_value / nominal_max)

Q-Format Range

# For Qm.n (m integer, n fractional):
range_min = -2^m (if signed)
range_max = 2^m - 2^(-n)
resolution = 2^(-n)  # LSB

🎓 Conceptos DSP Demostrados

  1. Fixed-Point vs Floating-Point
  2. Fixed: Uniform resolution, limited dynamic range
  3. Float: Adaptive resolution, wide dynamic range

  4. Headroom Allocation

  5. Reserve bits/range for peaks
  6. Tradeoff: headroom vs SNR in fixed-point
  7. "Free" in floating-point

  8. Accumulator Sizing

  9. Rule: 2x signal width for MAC operations
  10. Prevents intermediate overflow
  11. Critical for filters/convolution

  12. Tolerance Specifications

  13. Absolute: ±0.001
  14. Relative: ±1%
  15. dB: ±0.5 dB
  16. Application-specific

  17. Overflow Handling

  18. Saturation: Clamp to range (introduces distortion)
  19. Wrapping: Modulo arithmetic (catastrophic if unexpected)
  20. Warning: Detect and report

  21. SNR Limitations

  22. 16-bit: ~96 dB theoretical
  23. 24-bit: ~144 dB theoretical
  24. Actual < theoretical due to implementation

🔗 Integración

Este módulo se integra con: - 05_03_01_equation_database: Numerical specs en algorithm entries - 05_03_03_transfer_functions: Coefficient validation - 05_03_05_algorithm_templates (siguiente): Template specs - 05_03_06_validation_criteria: Numerical validation rules

🚀 Próximos Pasos

Módulo completado. Continuar con: - TAREA 6: 05_03_05_algorithm_templates - TAREA 7: 05_03_06_validation_criteria

📚 Referencias

  • Fixed-Point Arithmetic: An Introduction to Digital Signal Processors, Texas Instruments
  • Q Number Format: Wikipedia, Q (number format)
  • Audio Precision: Audio EQ Cookbook
  • IEEE 754: Standard for Floating-Point Arithmetic