Update app.py
Browse files3 unmodified lines4567789101112131412131416171815161721181923242520212223272824252630272829303435363738313233403435363738453940414243445145464748495051585952535455636456575859606162636465666768676970717273744 unmodified lines79808178798082838485868387888589909192909394959396979899100981011021011031041051061051071081095 unmodified lines1151161171171181181191201211221241231241259 unmodified lines1351361371401381391421431401411421431461441451481461471481495 unmodified lines1551561571601611621581591601611621631641651641661671661671681681691701711731721731751741751771781791761771781791811801811821831851861871881891841851861871881911921931941891901911921931941951961971981992002012022032042052062072082091981992002102112122132142152042162062072082092102112172132142152162172182182192202212202212222232242232242252252262272282292272302312292302322332342352362372352362382392382402412402412422432442432452462472462472482492502512522532542552482492502512592522532542622552562572652662582592602612622632642722652662672742682692702712722732742772752762772802782792822802812852822832842853 unmodified linesfrom typing import Dict, Tuple, List
# ==============================================================================# 1. ESPECIFICACIONES DE HARDWARE: HUSQVARNA HC3 (2023)# 1. ESPECIFICACIONES: HUSQVARNA HC3 (2023)# ==============================================================================
@dataclass(frozen=True)class BatterySpecs: # --- IDENTIDAD --- MODELO: str = 'Husqvarna HC3 (2023)' MOTOR: str = 'Shimano EP6 (Custom Tune)' MODELO: str = 'Husqvarna Hard Cross HC3' MOTOR: str = 'Shimano EP6 (85Nm)' # --- ENERGÍA (Simplo Core S1+) --- # Capacidad Total Real: 630Wh. # El BMS corta antes del 0% real para evitar daños químicos. # BATERÍA (Simplo Core S1+) CAPACIDAD_NOMINAL_AH: float = 17.5 VOLTAJE_NOMINAL: float = 36.0 BUFFER_SEGURIDAD_BMS: float = 0.05 # 5% de energía "fantasma" no utilizable BUFFER_SEGURIDAD_BMS: float = 0.05 # 5% Reserva intocable # --- FÍSICA DEL USUARIO (Tú) --- PESO_BICI_KG: float = 24.5 # Talla M + Pedales + Líquido Tubeless PESO_EQUIPO_KG: float = 4.5 # Mochila, agua (1.5L), herramientas, casco # FÍSICA USUARIO PESO_BICI_KG: float = 24.5 PESO_EQUIPO_KG: float = 4.5 # --- CARGADOR --- AMPERAJE_CARGADOR: float = 4.0 # Charger S # CARGADOR AMPERAJE_CARGADOR: float = 4.0 # --- CURVA DE VOLTAJE (Química NMC 21700) --- # CURVA OCV (NMC 21700) 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)
# --- PERFILES DE RENDIMIENTO (Shimano EP6) --- # [0]: Torque (Nm) # [1]: Consumo Rodadura Base (Wh/km en llano) # [2]: Factor de Asistencia (Cuánto empuja el motor vs tú) # [3]: Eficiencia Térmica (NUEVO V37: El motor pierde eficiencia a alta potencia) # PERFILES (EP6 TUNED) # [Nm, Wh/km, %Asist, Eficiencia] PERFILES_TORQUE: Dict[str, List[float]] = field(default_factory=lambda: { 'ECO (Nvl 1)': [27, 5.0, 0.40, 0.96], # 96% Eficiente (Va frío) 'ECO (Nvl 1)': [27, 5.0, 0.40, 0.96], 'Nivel 2': [34, 6.8, 0.50, 0.95], 'TRAIL (Nvl 3)':[41, 8.9, 0.60, 0.94], 'Nivel 4': [48, 11.0, 0.70, 0.92], 'Nivel 5': [55, 12.8, 0.80, 0.90], 'BOOST (Nvl 6)':[63, 14.5, 0.90, 0.88] # 88% Eficiente (Pérdidas por calor I^2R) 'BOOST (Nvl 6)':[63, 14.5, 0.90, 0.88] })
SPECS = BatterySpecs()
# ==============================================================================# 2. MOTOR FÍSICO (SIMULACIÓN DE CARGA)# 2. MOTOR FÍSICO (SIMULACIÓN DE CARGA EN TRASTERO)# ==============================================================================
def get_voltage(soc: float) -> float: return float(np.interp(soc, SPECS.OCV_CURVE_X, SPECS.OCV_CURVE_Y))
def calcular_soh(km: float) -> float: # Degradación ajustada a uso ligero (menos estrés en celdas) ciclos = max(0.0, float(km) / 72.0) ciclos = max(0.0, float(km) / 75.0) degradacion = (0.03 * (1 - np.exp(-0.05 * ciclos))) + (0.0002 * ciclos) return max(0.60, min(1.0, 1.0 - degradacion))
def simulador_carga_v37(km, inicio, fin, temp): # Blindaje Lógicodef factor_temperatura_descarga(temp_exterior: float) -> float: """Penalización de autonomía por frío EXTERIOR (Voltage Sag)""" if temp_exterior >= 20: return 1.0 if temp_exterior >= 10: return 0.98 if temp_exterior >= 5: return 0.95 # -5% if temp_exterior >= 0: return 0.90 # -10% (Típico invierno) if temp_exterior >= -5: return 0.82 # -18% return 0.70 # Congelación
# --- SIMULADOR DE CARGA (Usa Temperatura del Trastero) ---def simulador_carga_v39(km, inicio, fin, temp_trastero): if inicio >= fin: return {"estado": "CARGADO", "soh": calcular_soh(km)} if temp < -10 or temp > 55: # El BMS protege la carga si el TRASTERO está helado, no la calle. if temp_trastero < -5 or temp_trastero > 50: return {"estado": "ERROR_TEMP"}
soh = calcular_soh(km)4 unmodified lines t_min = 0.0 e_wh = 0.0 # Factor Térmico de Carga (Arrhenius) if temp < 15: f_temp = max(0.15, 0.4 + (0.04 * temp)) elif temp > 35: f_temp = 0.92 # Arrhenius usando temp_trastero (Probablemente cálido) 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 # 1 min dt = 1.0 / 60.0
# Bucle de Integración Numérica while ah_actual < ah_objetivo: soc_t0 = ah_actual / cap_total v_t0 = get_voltage(soc_t0) # CC/CV Logic i_target = SPECS.AMPERAJE_CARGADOR * f_temp # CC/CV Logic if v_t0 >= (42.0 - 0.2): # Acercándose a CV if v_t0 >= (42.0 - 0.2): diff = v_t0 - (42.0 - 0.6) i_real = i_target * np.exp(-3.5 * max(0, diff)) else: i_real = i_target if i_real < 0.1: i_real = 0.1
delta_ah = i_real * dt * 0.99 # 99% Eficiencia química delta_ah = i_real * dt * 0.99 distancia = ah_objetivo - ah_actual fin_ciclo = False # Clamping exacto if delta_ah >= distancia: delta_ah = distancia fraccion = delta_ah / (i_real * 0.99 * dt) if i_real > 0 else 05 unmodified lines ah_next = ah_actual + delta_ah v_t1 = get_voltage(ah_next / cap_total) v_avg = (v_t0 + v_t1) / 2 # Wh reales consumidos del enchufe (aprox) vs guardados delta_wh = delta_ah * v_avg ah_actual += delta_ah e_wh += delta_wh t_min += t_step if fin_ciclo: break return {9 unmodified lines# 3. RENDERIZADOR VISUAL (HTML5 NATIVO iOS)# ==============================================================================
def generar_vista_final(km_val, temp_val, elev_val, peso_piloto, inicio_val, fin_val):def generar_vista_final(km_val, temp_trastero, temp_ruta, elev_val, peso_piloto, inicio_val, fin_val): try: # 1. Ejecutar Kernel res = simulador_carga_v37(float(km_val), float(inicio_val), float(fin_val), float(temp_val)) # 1. Simular Carga (EN TRASTERO) res = simulador_carga_v39(float(km_val), float(inicio_val), float(fin_val), float(temp_trastero)) if res["estado"] == "ERROR_TEMP": return "<div style='background:#fee2e2; padding:20px; border-radius:12px; color:#991b1b; font-weight:bold; text-align:center;'>⛔ Temperatura Crítica (Protección BMS)</div>" return "<div style='background:#fee2e2; padding:20px; color:#991b1b; text-align:center;'>⛔ <b>ERROR:</b> Trastero demasiado frío/caliente para cargar.</div>"
# 2. Calcular Energía Disponible (Usable Real) # 2. Datos de Energía if res["estado"] == "CARGADO": soh = res["soh"] cap_bruta = (SPECS.CAPACIDAD_NOMINAL_AH * soh * SPECS.VOLTAJE_NOMINAL) * (float(inicio_val)/100.0)5 unmodified lines tiempo_txt = f"{h}h {m}m" energia_txt = f"+{res['energia']:.0f} Wh"
# APLICAR BUFFER DE SEGURIDAD (5% que nunca debes contar) cap_util = cap_bruta * (1.0 - SPECS.BUFFER_SEGURIDAD_BMS) if cap_util < 0: cap_util = 0 # 3. CÁLCULO DE AUTONOMÍA (EN RUTA) cap_util_teorica = cap_bruta * (1.0 - SPECS.BUFFER_SEGURIDAD_BMS) # Factor Térmico de RUTA (Aquí afecta el frío de fuera) f_clima = factor_temperatura_descarga(float(temp_ruta)) cap_util_real = cap_util_teorica * f_clima if cap_util_real < 0: cap_util_real = 0
# 3. Física de Peso Total # Física de Peso y Gravedad masa_total = SPECS.PESO_BICI_KG + float(peso_piloto) + SPECS.PESO_EQUIPO_KG # 4. Física de Elevación (Julios) # E_potencial = m * g * h g = 9.81 julios_totales = masa_total * g * float(elev_val) wh_gravedad_bruto = julios_totales / 3600.0
# --- CONSTRUCCIÓN HTML --- # --- HTML BUILDER --- html = f""" <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; max-width: 450px; margin: auto; color: #1f2937;"> <div style="font-family: -apple-system, system-ui, sans-serif; max-width: 450px; margin: auto; color: #111827;"> <div style="background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%); color: white; padding: 24px; border-radius: 20px; text-align: center; box-shadow: 0 10px 25px -5px rgba(37, 99, 235, 0.4); margin-bottom: 20px;"> <div style="font-size: 11px; font-weight: 700; opacity: 0.8; letter-spacing: 1px; text-transform: uppercase;">TIEMPO DE CARGA</div> <div style="font-size: 42px; font-weight: 800; letter-spacing: -1px; line-height: 1.1;">{tiempo_txt}</div> <div style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); color: white; padding: 24px; border-radius: 20px; text-align: center; box-shadow: 0 10px 20px -5px rgba(124, 58, 237, 0.4); margin-bottom: 16px;"> <div style="font-size: 11px; font-weight: 700; opacity: 0.9; letter-spacing: 1px; text-transform: uppercase;">TIEMPO DE CARGA ({int(temp_trastero)}°C)</div> <div style="font-size: 44px; font-weight: 800; letter-spacing: -1.5px; line-height: 1;">{tiempo_txt}</div> <div style="margin-top:8px;"> <span style="background: rgba(255,255,255,0.2); font-size: 13px; padding: 4px 12px; border-radius: 99px; font-weight: 600;">⚡ {energia_txt}</span> <span style="background: rgba(255,255,255,0.25); font-size: 13px; padding: 4px 12px; border-radius: 99px; font-weight: 600;">⚡ {energia_txt}</span> </div> </div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 20px;"> <div style="background: #f8fafc; padding: 16px; border-radius: 16px; border: 1px solid #e2e8f0; text-align:center;"> <div style="font-size: 24px;">⚖️</div> <div style="font-size: 11px; color: #64748b; font-weight: 700; margin-top:4px;">PESO TOTAL</div> <div style="font-size: 16px; font-weight: 800; color: #334155;">{masa_total:.1f} kg</div> <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px;"> <div style="background: #f8fafc; padding: 14px; border-radius: 16px; border: 1px solid #e2e8f0; text-align:center;"> <div style="font-size: 10px; color: #64748b; font-weight: 700; text-transform:uppercase;">Peso Total</div> <div style="font-size: 18px; font-weight: 800; color: #334155;">{masa_total:.1f} <span style="font-size:12px">kg</span></div> </div> <div style="background: #f8fafc; padding: 16px; border-radius: 16px; border: 1px solid #e2e8f0; text-align:center;"> <div style="font-size: 24px;">🏔️</div> <div style="font-size: 11px; color: #64748b; font-weight: 700; margin-top:4px;">DESNIVEL</div> <div style="font-size: 16px; font-weight: 800; color: #334155;">{int(float(elev_val))} m</div> <div style="background: #f8fafc; padding: 14px; border-radius: 16px; border: 1px solid #e2e8f0; text-align:center;"> <div style="font-size: 10px; color: #64748b; font-weight: 700; text-transform:uppercase;">Meta Desnivel</div> <div style="font-size: 18px; font-weight: 800; color: #334155;">{int(float(elev_val))} <span style="font-size:12px">m</span></div> </div> </div> """ # AVISO DE CLIMA (Solo si hace frío FUERA) if f_clima < 1.0: perdida = int((1.0 - f_clima) * 100) html += f""" <div style="background: #eff6ff; border: 1px solid #bfdbfe; color: #1e40af; padding: 12px 15px; border-radius: 12px; margin-bottom: 16px; font-size: 12px; display:flex; align-items:center;"> <span style="font-size:18px; margin-right:10px;">❄️</span> <div> <b>Ruta Fría ({float(temp_ruta)}°C):</b><br> Autonomía reducida un <b>{perdida}%</b> por eficiencia química. </div> </div> """
html += """ <div style="background: white; border: 1px solid #e5e7eb; border-radius: 20px; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);"> <div style="background: #f1f5f9; padding: 12px 20px; border-bottom: 1px solid #e2e8f0; font-size: 11px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;"> Autonomía Real (Safety Buffer -5%) <div style="background: white; border: 1px solid #e2e8f0; border-radius: 20px; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);"> <div style="padding: 12px 20px; background: #f8fafc; border-bottom: 1px solid #f1f5f9; font-size: 11px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;"> Autonomía Real Estimada </div> """ # Bucle de Modos con Física Térmica V37 for modo, specs_modo in SPECS.PERFILES_TORQUE.items(): consumo_base = specs_modo[1] factor_asist = specs_modo[2] efic_termica = specs_modo[3] # <--- NUEVO EN V37 # 1. Ajuste de Rodadura por Peso # Si pesas menos de 100kg (sistema), ruedas mejor. factor_rodadura = masa_total / 105.0 consumo_llano_ajustado = consumo_base * factor_rodadura # 2. Coste de Gravedad # Wh que paga la batería = (Wh Gravedad * Asistencia) / Eficiencia Térmica Dinámica # En Boost (efic 0.88), pagar la gravedad sale más caro que en Eco (0.96) coste_gravedad_total = wh_gravedad_bruto * factor_asist * (1.0 / efic_termica) consumo_llano = specs_modo[1] * factor_rodadura factor_asist = specs_modo[2] efic_termica = specs_modo[3] # 3. Energía Restante para Rodar wh_para_rodar = cap_util - coste_gravedad_total coste_gravedad = wh_gravedad_bruto * factor_asist * (1.0 / efic_termica) wh_rodadura = cap_util_real - coste_gravedad if wh_para_rodar > 0: distancia = int(wh_para_rodar / consumo_llano_ajustado) color = "#16a34a" if distancia > 20 else "#ca8a04" if wh_rodadura > 0: distancia = int(wh_rodadura / consumo_llano) color = "#16a34a" if distancia > 25 else "#d97706" if distancia > 10 else "#dc2626" html += f""" <div style="padding: 16px 20px; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center;"> <div style="padding: 14px 20px; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center;"> <div> <div style="font-size: 15px; font-weight: 700; color: #1e293b;">{modo}</div> <div style="font-size: 11px; color: #94a3b8; font-weight: 500;">-{int(coste_gravedad_total)} Wh subida</div> <div style="font-size: 14px; font-weight: 700; color: #1f2937;">{modo}</div> <div style="font-size: 10px; color: #94a3b8; font-weight: 500;">-{int(coste_gravedad)} Wh subida</div> </div> <div style="font-size: 18px; font-weight: 800; color: {color};">{distancia} km</div> </div>""" else: # Caso donde la gravedad consume toda la batería disponible max_subida_posible = int(float(elev_val) * (cap_util / coste_gravedad_total)) max_subida = int(float(elev_val) * (cap_util_real / coste_gravedad)) html += f""" <div style="padding: 16px 20px; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center; background: #fef2f2;"> <div style="padding: 14px 20px; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center; background: #fef2f2;"> <div> <div style="font-size: 15px; font-weight: 700; color: #991b1b;">{modo}</div> <div style="font-size: 11px; color: #b91c1c; font-weight: 600;">⚠️ Límite: {max_subida_posible}m desnivel</div> <div style="font-size: 14px; font-weight: 700; color: #991b1b;">{modo}</div> <div style="font-size: 10px; color: #b91c1c;">⚠️ Límite subida: {max_subida}m</div> </div> <div style="font-size: 18px; font-weight: 800; color: #dc2626;">0 km</div> <div style="font-size: 18px; font-weight: 800; color: #ef4444;">0 km</div> </div>""" html += "</div>" # Footer html += f""" <div style="margin-top: 20px; text-align: center; font-size: 11px; color: #94a3b8;"> Configuración: {SPECS.MODELO} • Piloto: {peso_piloto}kg </div> """ html += "</div>" html += "</div></div>" return html
except Exception as e: return f"Error Crítico: {str(e)}" return f"Error: {str(e)}"
# ==============================================================================# 4. LANZAMIENTO (CONFIGURACIÓN DE UI)# 4. UI V39 (DOBLE TEMPERATURA)# ==============================================================================
with gr.Blocks(title="Husqvarna V37", css="footer {display: none !important;}") as app: gr.Markdown("### ⚡ Husqvarna HC3 | Definitive Edition V37")with gr.Blocks(title="Husqvarna V39", css="footer {display: none !important;}") as app: gr.Markdown("### ⚡ Husqvarna HC3 | Dual Climate V39") with gr.Row(): with gr.Column(): inp_km = gr.Number(label="Odómetro (km)", value=1500) inp_peso = gr.Slider(50, 100, value=68, label="Tu Peso (kg)", step=1) inp_elev = gr.Slider(0, 2500, value=1000, label="Desnivel Objetivo (m)", step=50) inp_elev = gr.Slider(0, 3000, value=1000, label="Desnivel Objetivo (m)", step=50) gr.Markdown("---") inp_temp = gr.Slider(-10, 50, value=20, label="Temp Ambiente (°C)") # --- NUEVO: DOBLE TEMPERATURA --- with gr.Row(): inp_temp_carga = gr.Slider(-5, 40, value=20, label="Temp. Trastero (Carga)") inp_temp_ruta = gr.Slider(-10, 40, value=5, label="Temp. Exterior (Ruta)") inp_inicio = gr.Slider(0, 99, value=20, label="% Batería ACTUAL") inp_fin = gr.Slider(1, 100, value=100, label="% Batería OBJETIVO") btn = gr.Button("CALCULAR RUTA", variant="primary") btn = gr.Button("EJECUTAR SIMULACIÓN", variant="primary") with gr.Column(): out = gr.HTML(label="Resultados") out = gr.HTML(label="Dashboard")
# ENLACE DE VARIABLES 100% SEGURO btn.click( fn=generar_vista_final, inputs=[inp_km, inp_temp, inp_elev, inp_peso, inp_inicio, inp_fin], inputs=[inp_km, inp_temp_carga, inp_temp_ruta, inp_elev, inp_peso, inp_inicio, inp_fin], outputs=out )
app.py+114-117