Update app.py
Browse files3 unmodified lines45678910781314159101819201112222324252627131415161729181920212223362425265 unmodified lines32333448495051353637385639404142614344454 unmodified lines50515272735354555657587959818260838461866263646590919293949596979899100661026768691057071727374757611277787980818211983848586878812689909134 unmodified lines1261271281671681691701291301731741311321331341 unmodified line1361371381821391401411861421881891901911921931941951431441451461471981991482011491501511521531542071551561575 unmodified lines1631641652192201661671686 unmodified lines1751761772331782352361791801812381821831841852431861871882461891901911922511931941952541961971981992592002012022622632642652662672682692702712722732742752762772032042802812052062072086 unmodified lines2152162172942952962972182192202211 unmodified line2232242253052262272282291 unmodified line2312322333132342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263 unmodified linesfrom dataclasses import dataclass, fieldfrom typing import Dict, Tuple, List
# ==============================================================================# 1. ESPECIFICACIONES DE INGENIERÍA: HUSQVARNA HC3 (CORE S1+ / EP6)# ==============================================================================
@dataclass(frozen=True)class BatterySpecs: """ Configuración de Hardware Inmutable. """ MODELO: str = 'Husqvarna Hard Cross HC3' MOTOR: str = 'Shimano EP6 (85Nm)' # ENERGÍA (Simplo Core S1+) CAPACIDAD_NOMINAL_AH: float = 17.5 CAPACIDAD_NOMINAL_AH: float = 17.5 VOLTAJE_NOMINAL: float = 36.0 BUFFER_SEGURIDAD_BMS: float = 0.05 # 5% Reserva intocable # FÍSICA PESO_BICI_KG: float = 24.5 PESO_EQUIPO_KG: float = 4.5 AMPERAJE_CARGADOR: float = 4.0 BUFFER_SEGURIDAD_BMS: float = 0.05 PESO_BICI_KG: float = 24.5 PESO_EQUIPO_KG: float = 4.5 AMPERAJE_CARGADOR: float = 4.0 # CURVAS FÍSICAS (NMC 21700) OCV_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_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) TEMP_X: Tuple[float, ...] = (-10.0, -5.0, 0.0, 5.0, 10.0, 20.0, 40.0) TEMP_Y: Tuple[float, ...] = (0.70, 0.78, 0.85, 0.92, 0.97, 1.00, 1.00)
# PERFILES DE RENDIMIENTO PERFILES_TORQUE: Dict[str, List[float]] = field(default_factory=lambda: { 'ECO (Nvl 1)': [27, 5.0, 0.40, 0.96], 'Nivel 2': [34, 6.8, 0.50, 0.95],5 unmodified lines
SPECS = BatterySpecs()
# ==============================================================================# 2. KERNEL FÍSICO DE SIMULACIÓN (V54)# ==============================================================================
def get_voltage(soc: float) -> float: return float(np.interp(soc, SPECS.OCV_X, SPECS.OCV_Y))
def calcular_salud(km: float, ciclos_drift: int) -> dict: # Degradación Cíclica ciclos = max(0.0, float(km) / 75.0) degradacion = (0.03 * (1 - np.exp(-0.05 * ciclos))) + (0.0002 * ciclos) soh = max(0.60, min(1.0, 1.0 - degradacion)) # Drift (Desbalanceo) drift_pct = 0.0 if ciclos_drift > 5: x = ciclos_drift - 54 unmodified linesdef factor_clima_ruta(temp: float) -> float: return float(np.interp(temp, SPECS.TEMP_X, SPECS.TEMP_Y))
def simulador_master_v54(km, ciclos_drift, inicio, fin, temp_trastero): # Validacionesdef simulador_master_v53(km, ciclos_drift, inicio, fin, temp_trastero): if temp_trastero < -5 or temp_trastero > 50: return {"estado": "ERROR_TEMP"} salud = calcular_salud(km, ciclos_drift) soh = salud["soh"] cap_total = SPECS.CAPACIDAD_NOMINAL_AH * soh # CASO 1: SOBRECARGA (Usuario pide menos de lo que tiene) if inicio > fin: if inicio >= fin: exceso_ah = cap_total * ((inicio - fin) / 100.0) exceso_wh = exceso_ah * SPECS.VOLTAJE_NOMINAL return { "estado": "DRENAR", "estado": "CARGADO", "soh": soh, "drift": salud["drift"], "tiempo": 0, "energia": -exceso_wh, # Energía negativa (a gastar) "cap_final_wh": cap_total * (inicio / 100.0) * SPECS.VOLTAJE_NOMINAL }
# CASO 2: YA LISTA (Iguales) if inicio == fin: return { "estado": "CARGADO", "soh": soh, "drift": salud["drift"], "tiempo": 0, "energia": 0, "cap_final_wh": cap_total * (inicio / 100.0) * SPECS.VOLTAJE_NOMINAL "cap_final_wh": 0 }
# CASO 3: CARGA NECESARIA cap_total = SPECS.CAPACIDAD_NOMINAL_AH * soh ah_actual = cap_total * (inicio / 100.0) ah_objetivo = cap_total * (fin / 100.0) t_min = 0.0 e_wh = 0.0 # Arrhenius (Velocidad de Carga) if temp_trastero < 15: f_temp = max(0.15, 0.4 + (0.04 * temp_trastero)) elif temp_trastero > 35: f_temp = 0.92 else: f_temp = 1.0
dt = 1.0 / 60.0
# Integración while ah_actual < ah_objetivo: soc_now = ah_actual / cap_total v_now = get_voltage(soc_now) i_target = SPECS.AMPERAJE_CARGADOR * f_temp # Simulación CV (Saturación) if v_now >= (SPECS.OCV_Y[-1] - 0.25): diff = v_now - (SPECS.OCV_Y[-1] - 0.6) i_real = i_target * np.exp(-4.5 * max(0, diff))34 unmodified lines "cap_final_wh": ah_actual * SPECS.VOLTAJE_NOMINAL }
# ==============================================================================# 3. INTERFAZ VISUAL MAESTRA (V54 - PLATINUM UI)# ==============================================================================
def generar_interfaz_final(km_val, temp_trastero, temp_ruta, elev_val, peso_piloto, ciclos_drift, inicio_val, fin_val): try: # Ejecutar Simulación res = simulador_master_v54( res = simulador_master_v53( float(km_val), int(ciclos_drift), float(inicio_val), float(fin_val), float(temp_trastero) )1 unmodified line if res["estado"] == "ERROR_TEMP": return "<div style='background:#fee2e2; padding:20px; color:#991b1b; text-align:center;'>⛔ <b>ERROR:</b> Temperatura insegura.</div>"
# --- GESTIÓN DE DATOS --- drift_pct = res["drift"] soh = res["soh"] pct_objetivo = float(fin_val) pct_inicio = float(inicio_val) # Lógica de Visualización de Carga if res["estado"] == "DRENAR": tiempo_display = "EXCESO" # Mostramos la energía negativa en rojo energia_display = f"{int(res['energia'])} Wh" cap_bruta = res['cap_final_wh'] elif res["estado"] == "CARGADO": if res["estado"] == "CARGADO": pct_calculo = float(inicio_val) cap_bruta = (SPECS.CAPACIDAD_NOMINAL_AH * soh * SPECS.VOLTAJE_NOMINAL) * (pct_calculo/100.0) tiempo_display = "LISTA" energia_display = "0 Wh" cap_bruta = res['cap_final_wh'] else: # Carga Normal pct_calculo = float(fin_val) cap_bruta = res['cap_final_wh'] h, m = divmod(math.ceil(res["tiempo"]), 60) tiempo_display = f"{h}h {m}m" energia_display = f"+{int(res['energia'])} Wh"
# --- FÍSICA DE RUTA --- cap_util = cap_bruta * (1.0 - SPECS.BUFFER_SEGURIDAD_BMS) cap_util_drift = cap_util * (1.0 - drift_pct) wh_perdidos_drift = cap_util * drift_pct5 unmodified lines masa_total = SPECS.PESO_BICI_KG + float(peso_piloto) + SPECS.PESO_EQUIPO_KG g = 9.81 wh_gravedad = (masa_total * g * float(elev_val)) / 3600.0
# --- UI: PANEL DE ESTRATEGIA --- def get_card_style(is_active, color_hex): base = "flex: 1; padding: 10px; border-radius: 12px; margin: 2px;"6 unmodified lines return f"color: {color_hex}; font-weight: 800;" return "color: #6b7280; font-weight: 600;"
# Lógica de Activación active_storage = 30 <= pct_objetivo <= 60 active_daily = 60 < pct_objetivo <= 95 active_balance = pct_objetivo > 95 active_daily = 60 < pct_objetivo <= 90 active_balance = pct_objetivo > 90
# Tarjeta 1: Almacenaje html_storage = f""" <div style="{get_card_style(active_storage, '#6366f1')}"> <div style="font-size:9px; text-transform:uppercase; {get_text_style(active_storage, '#4f46e5')}">📦 Hibernación</div> <div style="font-size:16px; font-weight:800; color:#1f2937;">40-60%</div> <div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Almacenaje largo plazo.</div> <div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Para guardar la bici meses.</div> </div>"""
# Tarjeta 2: Diario html_daily = f""" <div style="{get_card_style(active_daily, '#16a34a')}"> <div style="font-size:9px; text-transform:uppercase; {get_text_style(active_daily, '#15803d')}">🔋 Diario</div> <div style="font-size:16px; font-weight:800; color:#1f2937;">80-90%</div> <div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Longevidad máxima.</div> <div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Vida útil máxima. Rutas normales.</div> </div>"""
# Tarjeta 3: Balanceo html_balance = f""" <div style="{get_card_style(active_balance, '#ea580c')}"> <div style="font-size:9px; text-transform:uppercase; {get_text_style(active_balance, '#c2410c')}">⚖️ Balanceo</div> <div style="font-size:16px; font-weight:800; color:#1f2937;">100%</div> <div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Mantenimiento (+45min).</div> <div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Cada 10 cargas (+45min).</div> </div>"""
# --- AVISO INTELIGENTE DE EXCESO --- header_color = "#2563eb" # Azul por defecto header_gradient = "linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)" aviso_drenaje = "" if res["estado"] == "DRENAR" and active_storage: header_color = "#dc2626" header_gradient = "linear-gradient(135deg, #dc2626 0%, #991b1b 100%)" aviso_drenaje = """ <div style="background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c; padding: 10px; border-radius: 12px; margin-bottom: 16px; font-size: 11px; text-align:center;"> <b>⚠️ EXCESO DE CARGA PARA ALMACENAJE</b><br> Tienes más batería de la recomendada para hibernar. Úsala antes de guardarla. </div> """
# --- HTML PRINCIPAL --- html = f""" <div style="font-family: -apple-system, sans-serif; max-width: 450px; margin: auto; color: #111827;"> <div style="background: {header_gradient}; color: white; padding: 20px; border-radius: 16px; text-align: center; box-shadow: 0 4px 12px rgba(0,0,0,0.2); margin-bottom: 20px;"> <div style="background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); color: white; padding: 20px; border-radius: 16px; text-align: center; box-shadow: 0 4px 12px rgba(37, 99, 235, 0.25); margin-bottom: 20px;"> <div style="font-size: 10px; font-weight: 700; opacity: 0.9; letter-spacing: 1px;">TIEMPO DE CARGA ({int(temp_trastero)}°C)</div> <div style="font-size: 42px; font-weight: 800; line-height: 1.1;">{tiempo_display}</div> <div style="margin-top:6px;">6 unmodified lines {html_daily} {html_balance} </div> {aviso_drenaje}
""" """ if drift_pct > 0.015: html += f"""1 unmodified line <div style="font-size:11px; font-weight:800; color:#be123c; margin-bottom:2px;">⚠️ MANTENIMIENTO NECESARIO</div> <div style="font-size:11px; color:#9f1239;"> Llevas {int(ciclos_drift)} cargas rápidas. Has perdido un <b>{drift_pct*100:.1f}%</b> de capacidad. <br><i>Solución: Carga hoy al 100%.</i> <br><i>Solución: Selecciona objetivo 100% hoy.</i> </div> </div> """1 unmodified line if f_clima < 0.98: perdida_clima = int((1.0 - f_clima) * 100) html += f""" <div style="background: #eff6ff; border: 1px solid #bfdbfe; color: #1e40af; <div style="background: #eff6ff; border: 1px solid #bfdbfe; color: #1e40af; padding: 10px 12px; border-radius: 12px; margin-bottom: 16px; font-size: 11px; display:flex; align-items:center;"> <span style="font-size:16px; margin-right:8px;">❄️</span> <div><b>Ruta Fría ({float(temp_ruta)}°C):</b> Rendimiento cae un <b>{perdida_clima}%</b>.</div> </div>"""
html += """ <div style="background: white; border: 1px solid #e5e7eb; border-radius: 16px; overflow: hidden;"> <div style="padding: 10px 16px; background: #f9fafb; border-bottom: 1px solid #e5e7eb; font-size: 10px; font-weight: 700; color: #6b7280; letter-spacing: 0.5px;"> PREDICCIÓN DE AUTONOMÍA REAL </div> """ for modo, specs_modo in SPECS.PERFILES_TORQUE.items(): factor_rodadura = masa_total / 105.0 consumo_llano = specs_modo[1] * factor_rodadura factor_asist = specs_modo[2] efic_termica = specs_modo[3] coste_subida = wh_gravedad * factor_asist * (1.0 / efic_termica) wh_rodadura = cap_rueda - coste_subida if cap_rueda > 0: pct_barra = min(100, max(0, (coste_subida / cap_rueda * 100))) else: pct_barra = 100 if wh_rodadura > 0: distancia = int(wh_rodadura / consumo_llano) color = "#15803d" if distancia > 25 else "#b45309" if distancia > 10 else "#b91c1c" html += f""" <div style="padding: 12px 16px; border-bottom: 1px solid #f3f4f6;"> <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;"> <div style="font-size: 13px; font-weight: 700; color: #1f2937;">{modo}</div> <div style="font-size: 16px; font-weight: 800; color: {color};">{distancia} km</div> </div> <div style="height: 6px; background: #f3f4f6; border-radius: 3px; overflow:hidden; display:flex;"> <div style="width: {pct_barra}%; background: #94a3b8;"></div> <div style="flex-grow: 1; background: {color};"></div> </div> <div style="display:flex; justify-content:space-between; margin-top:2px;"> <div style="font-size: 9px; color: #9ca3af;">Subida: -{int(coste_subida)}Wh</div> <div style="font-size: 9px; color: #9ca3af;">Rodar</div> </div> </div>""" else: max_m = int(float(elev_val) * (cap_rueda / coste_subida)) if coste_subida > 0 else 0 html += f""" <div style="padding: 12px 16px; border-bottom: 1px solid #f3f4f6; background: #fef2f2;"> <div style="display:flex; justify-content:space-between; align-items:center;"> <div style="font-size: 13px; font-weight: 700; color: #991b1b;">{modo}</div> <div style="font-size: 13px; font-weight: 800; color: #dc2626;">AGOTADA</div> </div> <div style="font-size: 10px; color: #b91c1c; margin-top:4px;">⚠️ Límite físico: {max_m}m desnivel</div> </div>""" html += "</div></div>" return html
except Exception as e: return f"Error: {str(e)}"
with gr.Blocks(title="Husqvarna HC3 Fast UI", css="footer {display: none !important;}") as app: gr.Markdown("### ⚡ Husqvarna HC3 | V53 Fast UI") with gr.Row(): with gr.Column(): inp_km = gr.Number(label="Odómetro Total (km)", value=1500) inp_ciclos = gr.Slider(0, 50, value=20, label="Cargas sin balancear (Drift)", step=1) inp_peso = gr.Slider(50, 100, value=68, label="Tu Peso (kg)", step=1) inp_elev = gr.Slider(0, 3000, value=1000, label="Desnivel Objetivo (m)", step=50) gr.Markdown("---") with gr.Row(): inp_t_trastero = gr.Slider(-5, 40, value=20, label="Temp. Trastero (Carga)") inp_t_ruta = gr.Slider(-10, 40, value=5, label="Temp. Exterior (Ruta)") inp_inicio = gr.Slider(0, 100, value=20, step=5, label="% Batería ACTUAL") inp_fin = gr.Slider(5, 100, value=100, step=5, label="% Batería OBJETIVO") btn = gr.Button("CALCULAR ESTRATEGIA", variant="primary") with gr.Column(): out = gr.HTML(label="Informe Técnico")
btn.click( fn=generar_interfaz_final, inputs=[inp_km, inp_t_trastero, inp_t_ruta, inp_elev, inp_peso, inp_ciclos, inp_inicio, inp_fin], outputs=out )
if __name__ == "__main__": app.launch()app.py+116-103