File size: 14,149 Bytes
1ac7c47 5db6a37 54edd8b 4fb66cb 6c5db83 54edd8b 5db6a37 4a356eb 2dfef39 5db6a37 2dfef39 3a53baf 7bd6975 23cf605 7bd6975 54edd8b 23cf605 4fb66cb 23cf605 4fb66cb 23cf605 54edd8b bf89223 5db6a37 131ff23 6c5db83 4fb66cb 7bd6975 b160c40 6c5db83 9c12316 6c5db83 9c12316 7bd6975 6c5db83 7bd6975 54edd8b 6c5db83 4a356eb 3a53baf 7bd6975 9c12316 7bd6975 2dfef39 7bd6975 2dfef39 7bd6975 6c5db83 7bd6975 54edd8b 2dfef39 3a53baf 54edd8b 6c5db83 03faf6f 6c5db83 54edd8b 7bd6975 3a53baf 7bd6975 6c5db83 54edd8b 3a53baf e89e14f 6c5db83 8257312 54edd8b 8257312 6c5db83 54edd8b 03faf6f 6c5db83 54edd8b 3a53baf 54edd8b 7bd6975 03faf6f 7bd6975 54edd8b 6c5db83 1541a9f 6c5db83 9c12316 6c5db83 d9c0f14 6c5db83 9c12316 6c5db83 8257312 6c5db83 1541a9f 6c5db83 2dfef39 6c5db83 7bd6975 6c5db83 7bd6975 6c5db83 4fb66cb 2dfef39 6c5db83 2dfef39 6c5db83 2dfef39 6c5db83 2dfef39 6c5db83 2dfef39 6c5db83 2dfef39 6c5db83 2dfef39 6c5db83 2dfef39 6c5db83 2dfef39 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | import gradio as gr
import numpy as np
from dataclasses import dataclass, field
from typing import Dict, Tuple, List
from functools import lru_cache
@dataclass(frozen=True)
class BatterySpecs:
MODELO: str = 'Husqvarna Hard Cross HC3'
MOTOR: str = 'Shimano EP6 (85Nm)'
CAPACIDAD_NOMINAL_AH: float = 17.5
VOLTAJE_NOMINAL: float = 36.0
BUFFER_SEGURIDAD_BMS: float = 0.05
PESO_BICI_KG: float = 24.5
PESO_EQUIPO_KG: float = 4.5
AMPERAJE_CARGADOR: float = 4.0
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_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],
'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]
})
SPECS = BatterySpecs()
CUSTOM_CSS = """
footer {display: none !important;}
.error-box {background:#fee2e2; padding:20px; color:#991b1b; text-align:center; font-weight:bold; border-radius:12px;}
.ui-container {font-family: system-ui, sans-serif; max-width: 450px; margin: 0 auto; color: #111827; width: 100%; box-sizing: border-box;}
@media (max-width: 480px) { .cards-row { flex-direction: column; gap: 8px; } }
@media (prefers-color-scheme: dark) { .ui-container { filter: invert(0.9) hue-rotate(180deg); } .hero-card { filter: invert(1) hue-rotate(180deg); } }
.hero-card {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;}
.hero-title {font-size: 10px; font-weight: 700; opacity: 0.9; letter-spacing: 1px;}
.hero-time {font-size: 42px; font-weight: 800; line-height: 1.1;}
.hero-badge {background: rgba(255,255,255,0.2); font-size: 12px; padding: 3px 10px; border-radius: 99px; display:inline-block; margin-top:6px;}
.cards-row {display: flex; justify-content: space-between; margin-bottom: 20px; gap:4px;}
.strategy-card {flex: 1; padding: 10px; border-radius: 12px; border: 1px solid #e5e7eb; background: #f9fafb; opacity: 0.6; transition: all 0.2s;}
.strategy-card.active {background: white; opacity: 1; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);}
.strategy-card.storage.active {border: 2px solid #6366f1;}
.strategy-card.daily.active {border: 2px solid #16a34a;}
.strategy-card.balance.active {border: 2px solid #ea580c;}
.strategy-title {font-size:9px; text-transform:uppercase; font-weight:600; color:#6b7280;}
.strategy-card.storage.active .strategy-title {color: #4f46e5; font-weight: 800;}
.strategy-card.daily.active .strategy-title {color: #15803d; font-weight: 800;}
.strategy-card.balance.active .strategy-title {color: #c2410c; font-weight: 800;}
.strategy-pct {font-size:16px; font-weight:800; color:#1f2937;}
.strategy-desc {font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;}
.warning-box {background: #fff1f2; border: 1px solid #fda4af; padding: 12px; border-radius: 12px; margin-bottom: 16px;}
.warning-title {font-size:11px; font-weight:800; color:#be123c; margin-bottom:2px;}
.warning-text {font-size:11px; color:#9f1239;}
.info-box {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;}
.info-icon {font-size:16px; margin-right:8px;}
.results-container {background: white; border: 1px solid #e5e7eb; border-radius: 16px; overflow: hidden;}
.results-header {padding: 10px 16px; background: #f9fafb; border-bottom: 1px solid #e5e7eb; font-size: 10px; font-weight: 700; color: #6b7280; letter-spacing: 0.5px;}
.mode-row {padding: 12px 16px; border-bottom: 1px solid #f3f4f6;}
.mode-row.exhausted {background: #fef2f2;}
.mode-header {display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;}
.mode-name {font-size: 13px; font-weight: 700; color: #1f2937;}
.mode-name.exhausted {color: #991b1b;}
.mode-dist {font-size: 16px; font-weight: 800;}
.mode-dist.exhausted {color: #dc2626; font-size: 13px;}
.progress-bar {height: 6px; background: #f3f4f6; border-radius: 3px; overflow:hidden; display:flex;}
.progress-used {background: #94a3b8;}
.mode-details {display:flex; justify-content:space-between; margin-top:2px; font-size: 9px; color: #9ca3af;}
"""
@lru_cache(maxsize=128)
def get_voltage(soc: float) -> float:
return float(np.interp(soc, SPECS.OCV_X, SPECS.OCV_Y))
@lru_cache(maxsize=32)
def factor_clima_ruta(temp: float) -> float:
return float(np.interp(temp, SPECS.TEMP_X, SPECS.TEMP_Y))
def calcular_salud(km: float, ciclos_drift: int) -> dict:
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_pct = 0.08 * ((ciclos_drift - 5) / (ciclos_drift + 10)) if ciclos_drift > 5 else 0.0
return {"soh": soh, "drift": drift_pct}
def simulador_master_v53(km: float, ciclos_drift: int, inicio: float, fin: float, temp_trastero: float) -> dict:
if temp_trastero < -5 or temp_trastero > 50:
return {"estado": "ERROR_TEMP"}
salud = calcular_salud(km, ciclos_drift)
soh = salud["soh"]
if inicio >= fin:
return {
"estado": "CARGADO",
"soh": soh,
"drift": salud["drift"],
"tiempo": 0.0,
"energia": 0.0,
"cap_final_wh": 0.0
}
cap_total = SPECS.CAPACIDAD_NOMINAL_AH * soh
ah_actual = cap_total * (inicio / 100.0)
ah_objetivo = cap_total * (fin / 100.0)
f_temp = max(0.15, 0.4 + (0.04 * temp_trastero)) if temp_trastero < 15 else 0.92 if temp_trastero > 35 else 1.0
t_min = 0.0
e_wh = 0.0
dt = 0.5
while ah_actual < ah_objetivo:
soc_now = ah_actual / cap_total
v_now = get_voltage(soc_now)
i_target = SPECS.AMPERAJE_CARGADOR * f_temp
if v_now >= (SPECS.OCV_Y[-1] - 0.25):
diff = v_now - (SPECS.OCV_Y[-1] - 0.6)
i_real = max(0.1, i_target * np.exp(-4.5 * max(0, diff)))
else:
i_real = i_target
delta_ah = i_real * (dt / 60.0) * 0.98
distancia = ah_objetivo - ah_actual
if delta_ah >= distancia:
delta_ah = distancia
t_step = (delta_ah / (i_real * 0.98)) * 60.0 if i_real > 0 else 0
ah_actual += delta_ah
e_wh += (delta_ah * v_now)
t_min += t_step
break
ah_actual += delta_ah
e_wh += (delta_ah * v_now)
t_min += dt
return {
"estado": "OK",
"soh": soh,
"drift": salud["drift"],
"tiempo": t_min,
"energia": e_wh,
"cap_final_wh": ah_actual * SPECS.VOLTAJE_NOMINAL
}
def generar_interfaz_final(km_val: float, temp_trastero: float, temp_ruta: float, elev_val: float, peso_piloto: float, ciclos_drift: int, inicio_val: float, fin_val: float) -> str:
res = simulador_master_v53(float(km_val), int(ciclos_drift), float(inicio_val), float(fin_val), float(temp_trastero))
if res["estado"] == "ERROR_TEMP":
return "<div class='error-box'>⛔ ERROR: Temperatura insegura. Riesgo de cristalización de litio.</div>"
drift_pct = res["drift"]
soh = res["soh"]
pct_objetivo = float(fin_val)
if res["estado"] == "CARGADO":
tiempo_display = "LISTA"
energia_display = "0 Wh"
else:
cap_bruta = res['cap_final_wh']
h, m = divmod(int(res["tiempo"]) + (res["tiempo"] % 1 > 0), 60)
tiempo_display = f"{h}h {m}m"
energia_display = f"+{int(res['energia'])} Wh"
cap_bruta = res['cap_final_wh'] if res["estado"] != "CARGADO" else (SPECS.CAPACIDAD_NOMINAL_AH * soh * SPECS.VOLTAJE_NOMINAL) * (float(inicio_val) / 100.0)
cap_util_drift = cap_bruta * (1.0 - SPECS.BUFFER_SEGURIDAD_BMS) * (1.0 - drift_pct)
f_clima = factor_clima_ruta(float(temp_ruta))
cap_rueda = max(0.0, cap_util_drift * f_clima)
masa_total = SPECS.PESO_BICI_KG + float(peso_piloto) + SPECS.PESO_EQUIPO_KG
wh_gravedad = (masa_total * 9.81 * float(elev_val)) / 3600.0
act_s = "active" if 30 <= pct_objetivo <= 60 else ""
act_d = "active" if 60 < pct_objetivo <= 90 else ""
act_b = "active" if pct_objetivo > 90 else ""
html = f"""
<div class="ui-container">
<div class="hero-card">
<div class="hero-title">TIEMPO DE CARGA ({int(temp_trastero)}°C)</div>
<div class="hero-time">{tiempo_display}</div>
<div class="hero-badge">⚡ {energia_display}</div>
</div>
<div class="cards-row">
<div class="strategy-card storage {act_s}">
<div class="strategy-title">📦 Hibernación</div>
<div class="strategy-pct">40-60%</div>
<div class="strategy-desc">Para guardar la bici meses sin estrés.</div>
</div>
<div class="strategy-card daily {act_d}">
<div class="strategy-title">🔋 Diario</div>
<div class="strategy-pct">80-90%</div>
<div class="strategy-desc">Vida útil máxima. Rutas normales.</div>
</div>
<div class="strategy-card balance {act_b}">
<div class="strategy-title">⚖️ Balanceo</div>
<div class="strategy-pct">100%</div>
<div class="strategy-desc">Cada 10 cargas (+45min).</div>
</div>
</div>
"""
if drift_pct > 0.015:
html += f"""
<div class="warning-box">
<div class="warning-title">⚠️ MANTENIMIENTO REQUERIDO</div>
<div class="warning-text">Acumulas {int(ciclos_drift)} cargas rápidas. Desajuste de celdas estimado: <b>{drift_pct*100:.1f}%</b>.<br><i>Solución: Realiza una carga al 100% hoy.</i></div>
</div>
"""
if f_clima < 0.98:
html += f"""
<div class="info-box">
<span class="info-icon">❄️</span>
<div><b>Termodinámica ({float(temp_ruta)}°C):</b> Capacidad disponible reducida en <b>{int((1.0 - f_clima) * 100)}%</b>.</div>
</div>"""
html += """
<div class="results-container">
<div class="results-header">PREDICCIÓN DE AUTONOMÍA REAL (MOTOR EP6)</div>
"""
for modo, specs_modo in SPECS.PERFILES_TORQUE.items():
consumo_llano = specs_modo[1] * (masa_total / 105.0)
coste_subida = wh_gravedad * specs_modo[2] * (1.0 / specs_modo[3])
wh_rodadura = cap_rueda - coste_subida
pct_barra = min(100.0, max(0.0, (coste_subida / cap_rueda * 100.0))) if cap_rueda > 0 else 100.0
if wh_rodadura > 0:
distancia = int(wh_rodadura / consumo_llano) if consumo_llano > 0 else 0
color = "#15803d" if distancia > 25 else "#b45309" if distancia > 10 else "#b91c1c"
html += f"""
<div class="mode-row">
<div class="mode-header">
<div class="mode-name">{modo}</div>
<div class="mode-dist" style="color: {color};">{distancia} km</div>
</div>
<div class="progress-bar">
<div class="progress-used" style="width: {pct_barra}%;"></div>
<div style="flex-grow: 1; background: {color};"></div>
</div>
<div class="mode-details">
<div>Elevación: -{int(coste_subida)}Wh</div>
<div>Llano</div>
</div>
</div>"""
else:
max_m = int(float(elev_val) * (cap_rueda / coste_subida)) if coste_subida > 0 else 0
html += f"""
<div class="mode-row exhausted">
<div class="mode-header">
<div class="mode-name exhausted">{modo}</div>
<div class="mode-dist exhausted">BATERÍA AGOTADA</div>
</div>
<div style="font-size: 10px; color: #b91c1c; margin-top:4px;">⚠️ Límite termodinámico superado: tope en {max_m}m de desnivel positivo.</div>
</div>"""
html += "</div></div>"
return html
with gr.Blocks(title="Husqvarna HC3 BMS", css=CUSTOM_CSS) as app:
gr.Markdown("### ⚡ BMS Analytics | Husqvarna HC3")
with gr.Row():
with gr.Column():
with gr.Accordion("Parámetros Físicos y Desgaste", open=True):
inp_km = gr.Number(label="Odómetro (km)", value=1500)
inp_ciclos = gr.Slider(0, 50, value=20, label="Cargas sin balancear", step=1)
inp_peso = gr.Slider(50, 100, value=68, label="Peso Piloto (kg)", step=1)
inp_elev = gr.Slider(0, 3000, value=1000, label="Desnivel Objetivo (m)", step=50)
with gr.Accordion("Condiciones Térmicas", open=False):
inp_t_trastero = gr.Slider(-5, 40, value=20, label="T. Carga (°C)")
inp_t_ruta = gr.Slider(-10, 40, value=5, label="T. Ruta (°C)")
with gr.Group():
inp_inicio = gr.Slider(0, 100, value=20, step=5, label="% Batería Actual")
inp_fin = gr.Slider(5, 100, value=80, step=5, label="% Objetivo Carga (Recomendado 80%)")
btn = gr.Button("EJECUTAR SIMULACIÓN", variant="primary")
with gr.Column():
out = gr.HTML(label="Output")
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()
|