Update app.py
Browse files3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778791 unmodified line818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921932 unmodified lines1961971981992002012022032042052062072083 unmodified linesfrom typing import Dict, Tuple, List, Any# ==============================================================================# 1. ESPECIFICACIONES DE INGENIERÍA (HARDWARE CONFIG)# ==============================================================================@dataclass(frozen=True)class BatterySpecs:"""Especificaciones técnicas inmutables para Husqvarna HC3 / Shimano EP6.Química: Li-Ion NMC (Nickel Manganese Cobalt)."""MODELO: str = 'Husqvarna HC3'MOTOR: str = 'Shimano EP6 (Custom Tuned)'# Capacidad y VoltajesCAPACIDAD_NOMINAL_AH: float = 17.5 # 630Wh @ 36VVOLTAJE_NOMINAL: float = 36.0VOLTAJE_MAX: float = 42.0 # 4.2V/celdaVOLTAJE_MIN: float = 30.0 # 3.0V/celda# Cargador y EficienciaAMPERAJE_CARGADOR: float = 4.0 # Charger S (4A Output)EFICIENCIA_COULOMBICA: float = 0.99 # Eficiencia químicaEFICIENCIA_ENERGETICA: float = 0.95 # Pérdidas térmicas# Curva OCV (Open Circuit Voltage) InterpoladaOCV_CURVE_X: Tuple[float, ...] = (0.0, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1.0)OCV_CURVE_Y: Tuple[float, ...] = (31.0, 32.5, 34.0, 35.1, 35.8, 36.3, 36.7, 37.2, 38.0, 39.2, 40.8, 41.5, 42.0)# Consumo Energético Realista (Wh/km)PERFILES_TORQUE: Dict[str, List[float]] = field(default_factory=lambda: {'ECO (Nvl 1)': [27, 5.2],'TRL (Nvl 3)': [42, 8.6],'BST (Nvl 6)': [63, 15.1]})SPECS = BatterySpecs()# ==============================================================================# 2. MOTOR FÍSICO DE SIMULACIÓN (KERNEL)# ==============================================================================def get_voltage_from_soc(soc_decimal: float) -> float:return float(np.interp(soc_decimal, SPECS.OCV_CURVE_X, SPECS.OCV_CURVE_Y))def calcular_soh(km: float) -> float:ciclos = max(0.0, float(km) / 60.0)degradacion = (0.04 * (1 - np.exp(-0.02 * ciclos))) + (0.0002 * ciclos)return max(0.60, min(1.0, 1.0 - degradacion))def motor_carga_v26(km_odo: float, inicio_pct: float, fin_pct: float, temp_amb: float) -> Dict[str, Any]:"""Simulador de carga minuto a minuto con integración trapezoidal y corrección de over-shoot."""# --- Validaciones de Entrada ---# Corrección para evitar errores de precisión flotante en la comparaciónif inicio_pct >= fin_pct:raise ValueError(f"Objetivo ({fin_pct}%) debe ser superior al actual ({inicio_pct}%).")if temp_amb < -10 or temp_amb > 50:raise EnvironmentError("Temperatura crítica: BMS ha bloqueado la carga por seguridad.")# --- Inicialización ---soh = calcular_soh(km_odo)capacidad_total_ah = SPECS.CAPACIDAD_NOMINAL_AH * sohah_actual = capacidad_total_ah * (inicio_pct / 100.0)ah_objetivo = capacidad_total_ah * (fin_pct / 100.0)tiempo_acumulado_min = 0.0energia_acumulada_wh = 0.0# Factor Térmicoif temp_amb < 15:factor_termico = max(0.1, 0.4 + (0.04 * temp_amb))elif temp_amb > 35:1 unmodified lineelse:factor_termico = 1.0dt_horas = 1.0 / 60.0# --- Bucle Principal ---while ah_actual < ah_objetivo:soc_t0 = ah_actual / capacidad_total_ahvoltaje_t0 = get_voltage_from_soc(soc_t0)# Algoritmo CC/CVcorriente_max_teorica = SPECS.AMPERAJE_CARGADOR * factor_termicoif voltaje_t0 >= (SPECS.VOLTAJE_MAX - 0.2):sobrevoltaje = voltaje_t0 - (SPECS.VOLTAJE_MAX - 0.6)factor_cv = np.exp(-3.0 * max(0, sobrevoltaje))current_amps = corriente_max_teorica * factor_cvelse:current_amps = corriente_max_teoricaif current_amps < 0.1: current_amps = 0.1# Clamping y paso de tiempodelta_ah_step = current_amps * dt_horas * SPECS.EFICIENCIA_COULOMBICAdistancia_meta = ah_objetivo - ah_actualfin_de_ciclo = Falseif delta_ah_step >= distancia_meta:delta_ah_step = distancia_metafraccion_tiempo = delta_ah_step / (current_amps * SPECS.EFICIENCIA_COULOMBICA * dt_horas) if current_amps > 0 else 0tiempo_step = fraccion_tiempofin_de_ciclo = Trueelse:tiempo_step = 1.0# Integración Trapezoidal de Energíaah_temp_final = ah_actual + delta_ah_stepsoc_t1 = ah_temp_final / capacidad_total_ahvoltaje_t1 = get_voltage_from_soc(soc_t1)voltaje_promedio = (voltaje_t0 + voltaje_t1) / 2delta_wh = delta_ah_step * voltaje_promedio * SPECS.EFICIENCIA_ENERGETICAah_actual += delta_ah_stepenergia_acumulada_wh += delta_whtiempo_acumulado_min += tiempo_stepif fin_de_ciclo: breakreturn {"soh": soh,"tiempo_min": tiempo_acumulado_min,"energia_wh": energia_acumulada_wh,"capacidad_final_wh": ah_actual * SPECS.VOLTAJE_NOMINAL,"soc_final_pct": (ah_actual / capacidad_total_ah) * 100.0}# ==============================================================================# 3. INTERFAZ GRÁFICA (GRADIO UI)# ==============================================================================def interfaz_simulador(km, temp, inicio, fin):try:# CORRECCIÓN CRÍTICA V26: USO DE ARGUMENTOS NOMBRADOS PARA EVITAR ERROR DE MAPEOres = motor_carga_v26(km_odo=float(km),inicio_pct=float(inicio), # Antes recibía 'temp' por error posicionalfin_pct=float(fin), # Antes recibía 'inicio' por error posicionaltemp_amb=float(temp) # Antes recibía 'fin' por error posicional)h, m = divmod(int(res["tiempo_min"]), 60)informe = f"""📊 REPORTE DE INGENIERÍA V26 (FIXED)=======================================OBJETIVO: {res['soc_final_pct']:.1f}% SoC[1] DIAGNÓSTICO DE SALUD• Estado (SOH): {res['soh']*100:.2f}%• Ciclos Totales: {int(km/60)} ciclos est.[2] PARÁMETROS DE CARGA• Tiempo Total: {h}h {m}min• Energía Ingestada: {res['energia_wh']:.1f} Wh• Capacidad Disp.: {res['capacidad_final_wh']:.1f} Wh[3] PREDICCIÓN DE AUTONOMÍA---------------------------------------"""for modo, (par, consumo) in SPECS.PERFILES_TORQUE.items():dist = res['capacidad_final_wh'] / consumoinforme += f"• {modo:<12} ({par} Nm) -> {int(dist)} km\n "informe += "\n" + "="*39if fin >= 99:informe += "\n⚡ AVISO: Balanceo de celdas pasivo activo.\n El BMS requiere 45 min extra tras finalizar."return informeexcept Exception as e:return f"❌ ERROR: {str(e)}"# Configuración del Layoutwith gr.Blocks(title="Husqvarna BMS Pro", theme=gr.themes.Soft(primary_hue="blue")) as app:gr.Markdown("# ⚡ Husqvarna HC3 | BMS Digital Twin V26")gr.Markdown("Simulador electroquímico de alta precisión para gestión de baterías e-MTB.")with gr.Row():with gr.Column():2 unmodified linesgr.Markdown("---")inp_inicio = gr.Slider(0, 99, value=20, label="% Batería ACTUAL", step=1)inp_fin = gr.Slider(1, 100, value=100, label="% Batería OBJETIVO", step=1)btn_run = gr.Button("EJECUTAR SIMULACIÓN", variant="primary")with gr.Column():out_console = gr.Textbox(label="Resultados y Telemetría", lines=16, show_copy_button=True, text_align="left")btn_run.click(interfaz_simulador, inputs=[inp_km, inp_temp, inp_inicio, inp_fin], outputs=out_console)if __name__ == "__main__":app.launch()3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283841 unmodified line86878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941952 unmodified lines1981992002012022032042052062072082093 unmodified linesfrom typing import Dict, Tuple, List, Any# ==============================================================================# 1. ESPECIFICACIONES DE INGENIERÍA (CONFIGURACIÓN E-TUBE PROJECT)# ==============================================================================@dataclass(frozen=True)class BatterySpecs:"""Especificaciones técnicas: Husqvarna HC3 + Shimano EP6.Perfil: Custom 'Fine Tune' (Mid) - 6 Niveles."""MODELO: str = 'Husqvarna HC3'MOTOR: str = 'Shimano EP6 (Custom Tuned)'# Capacidad y Voltajes (Core S1+ 630Wh)CAPACIDAD_NOMINAL_AH: float = 17.5VOLTAJE_NOMINAL: float = 36.0VOLTAJE_MAX: float = 42.0VOLTAJE_MIN: float = 30.0# CargadorAMPERAJE_CARGADOR: float = 4.0EFICIENCIA_COULOMBICA: float = 0.99EFICIENCIA_ENERGETICA: float = 0.95# Curva OCV (Química NMC)OCV_CURVE_X: Tuple[float, ...] = (0.0, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1.0)OCV_CURVE_Y: Tuple[float, ...] = (31.0, 32.5, 34.0, 35.1, 35.8, 36.3, 36.7, 37.2, 38.0, 39.2, 40.8, 41.5, 42.0)# MATRIZ DE CONSUMO EXACTA (Basada en tu captura E-Tube)# Rango: 27Nm (Eco) hasta 63Nm (Max Torque capado)# Interpolación de consumo basada en física de arrastre MulletPERFILES_TORQUE: Dict[str, List[float]] = field(default_factory=lambda: {'Nivel 1 (Eco)': [27, 5.2], # Base (Mínima asistencia)'Nivel 2': [34, 7.1], # Interpolado'Nivel 3': [41, 9.3], # Assist Start Point'Nivel 4': [48, 11.5], # Zona media'Nivel 5': [55, 13.4], # Alta potencia'Nivel 6 (Max)': [63, 15.2] # Tope configurado en tu app (63Nm)})SPECS = BatterySpecs()# ==============================================================================# 2. MOTOR FÍSICO DE SIMULACIÓN (KERNEL V27)# ==============================================================================def get_voltage_from_soc(soc_decimal: float) -> float:return float(np.interp(soc_decimal, SPECS.OCV_CURVE_X, SPECS.OCV_CURVE_Y))def calcular_soh(km: float) -> float:# Modelo de degradación para celdas 21700ciclos = max(0.0, float(km) / 60.0)degradacion = (0.04 * (1 - np.exp(-0.02 * ciclos))) + (0.0002 * ciclos)return max(0.60, min(1.0, 1.0 - degradacion))def motor_carga_v27(km_odo: float, inicio_pct: float, fin_pct: float, temp_amb: float) -> Dict[str, Any]:"""Simulador con corrección de argumentos y lógica 'Clamping'."""# Validacionesif inicio_pct >= fin_pct:raise ValueError(f"Objetivo ({fin_pct}%) debe ser superior al actual ({inicio_pct}%).")if temp_amb < -10 or temp_amb > 50:raise EnvironmentError("Temperatura crítica. Carga detenida.")# Inicializaciónsoh = calcular_soh(km_odo)capacidad_total_ah = SPECS.CAPACIDAD_NOMINAL_AH * sohah_actual = capacidad_total_ah * (inicio_pct / 100.0)ah_objetivo = capacidad_total_ah * (fin_pct / 100.0)t_min = 0.0e_wh = 0.0# Factor Térmico Ajustadoif temp_amb < 15:factor_termico = max(0.1, 0.4 + (0.04 * temp_amb))elif temp_amb > 35:1 unmodified lineelse:factor_termico = 1.0dt = 1.0 / 60.0# Bucle Integraciónwhile ah_actual < ah_objetivo:soc_t0 = ah_actual / capacidad_total_ahv_t0 = get_voltage_from_soc(soc_t0)# CC/CV Lógicai_max = SPECS.AMPERAJE_CARGADOR * factor_termicoif v_t0 >= (SPECS.VOLTAJE_MAX - 0.2):diff = v_t0 - (SPECS.VOLTAJE_MAX - 0.6)i_real = i_max * np.exp(-3.0 * max(0, diff))else:i_real = i_maxif i_real < 0.1: i_real = 0.1# Paso de integración con Clampingdelta_ah = i_real * dt * SPECS.EFICIENCIA_COULOMBICAdistancia = ah_objetivo - ah_actualfin_ciclo = Falseif delta_ah >= distancia:delta_ah = distanciafraccion = delta_ah / (i_real * SPECS.EFICIENCIA_COULOMBICA * dt) if i_real > 0 else 0t_step = fraccionfin_ciclo = Trueelse:t_step = 1.0# Energía (Trapezoidal)ah_next = ah_actual + delta_ahv_t1 = get_voltage_from_soc(ah_next / capacidad_total_ah)v_avg = (v_t0 + v_t1) / 2delta_wh = delta_ah * v_avg * SPECS.EFICIENCIA_ENERGETICAah_actual += delta_ahe_wh += delta_wht_min += t_stepif fin_ciclo: breakreturn {"soh": soh,"tiempo": t_min,"energia": e_wh,"capacidad_final": ah_actual * SPECS.VOLTAJE_NOMINAL,"soc_final": (ah_actual / capacidad_total_ah) * 100.0}# ==============================================================================# 3. INTERFAZ GRÁFICA (V27 - E-TUBE STYLE)# ==============================================================================def interfaz_simulador(km, temp, inicio, fin):try:# Argumentos nombrados para evitar errores de mapeores = motor_carga_v27(km_odo=float(km),inicio_pct=float(inicio),fin_pct=float(fin),temp_amb=float(temp))h, m = divmod(int(res["tiempo"]), 60)informe = f"""📊 REPORTE DE INGENIERÍA V27 (CUSTOM TUNED)===========================================CONFIGURACIÓN: {SPECS.MOTOR}LÍMITE TORQUE: 63 Nm (Usuario)[1] ESTADO BATERÍA• Salud (SOH): {res['soh']*100:.1f}%• Ciclos Aprox: {int(km/60)}[2] TIEMPOS DE CARGA• Tiempo Total: {h}h {m}min• Energía Carga: {res['energia']:.1f} Wh• SoC Final: {res['soc_final']:.1f}%[3] RANGO REAL (TUS 6 NIVELES)-------------------------------------------"""cap_util = res['capacidad_final']for nombre, (par, consumo) in SPECS.PERFILES_TORQUE.items():dist = cap_util / consumoinforme += f"• {nombre:<13} ({par} Nm) -> {int(dist)} km\n "informe += "\n" + "="*43if fin >= 99:informe += "\n⚡ AVISO: Balanceo activo. Deja conectado +45min."return informeexcept Exception as e:return f"❌ ERROR: {str(e)}"# Layoutwith gr.Blocks(title="Husqvarna HC3 Twin", theme=gr.themes.Soft(primary_hue="blue")) as app:gr.Markdown("# ⚡ Husqvarna HC3 | Digital Twin V27")gr.Markdown("Simulador sincronizado con perfil Shimano E-Tube 'Fine Tune' (27-63Nm).")with gr.Row():with gr.Column():2 unmodified linesgr.Markdown("---")inp_inicio = gr.Slider(0, 99, value=20, label="% Batería ACTUAL", step=1)inp_fin = gr.Slider(1, 100, value=100, label="% Batería OBJETIVO", step=1)btn = gr.Button("CALCULAR DATOS", variant="primary")with gr.Column():out = gr.Textbox(label="Telemetría", lines=18, show_copy_button=True)btn.click(interfaz_simulador, inputs=[inp_km, inp_temp, inp_inicio, inp_fin], outputs=out)if __name__ == "__main__":app.launch()
app.py+97-96