model-arena-sdk 0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- model_arena/__init__.py +7 -0
- model_arena/_mac_runtime/BUILD_MONITOR.json +1 -0
- model_arena/_mac_runtime/abrir_monitor.py +95 -0
- model_arena/_mac_runtime/app.py +12 -0
- model_arena/_mac_runtime/entrenamiento/arena_estudio.py +219 -0
- model_arena/_mac_runtime/entrenamiento/curvas_contrato.py +5 -0
- model_arena/_mac_runtime/entrenamiento/curvas_metricas.py +101 -0
- model_arena/_mac_runtime/entrenamiento/curvas_modelo.py +2 -0
- model_arena/_mac_runtime/entrenamiento/e2e_worker.py +50 -0
- model_arena/_mac_runtime/entrenamiento/entrenar_curvas.py +235 -0
- model_arena/_mac_runtime/entrenamiento/libraries/accountability_observatory/src/accountability_observatory/__init__.py +3 -0
- model_arena/_mac_runtime/entrenamiento/libraries/accountability_observatory/src/accountability_observatory/application.py +63 -0
- model_arena/_mac_runtime/entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/__init__.py +3 -0
- model_arena/_mac_runtime/entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/aws.py +620 -0
- model_arena/_mac_runtime/entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/calendar.py +25 -0
- model_arena/_mac_runtime/entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/sampling.py +70 -0
- model_arena/_mac_runtime/entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/source_audit.py +45 -0
- model_arena/_mac_runtime/entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/universe.py +277 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/__init__.py +19 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/api.py +45 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/backbones.py +59 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/calendar.py +41 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/contracts.py +164 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/curve_models.py +146 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/data.py +197 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/engine.py +476 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/full_tft.py +72 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/models.py +214 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/percentage_metrics.py +13 -0
- model_arena/_mac_runtime/entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/surfaces.py +78 -0
- model_arena/_mac_runtime/entrenamiento/monitor_learning.py +56 -0
- model_arena/_mac_runtime/entrenamiento/visor/workspace.py +109 -0
- model_arena/_mac_runtime/flujo_completo.py +157 -0
- model_arena/_mac_runtime/observatorio_athena/__init__.py +1 -0
- model_arena/_mac_runtime/observatorio_athena/account_previews.py +35 -0
- model_arena/_mac_runtime/observatorio_athena/alert_taxonomy.py +56 -0
- model_arena/_mac_runtime/observatorio_athena/alerts_view.py +241 -0
- model_arena/_mac_runtime/observatorio_athena/analysis.py +47 -0
- model_arena/_mac_runtime/observatorio_athena/aws.py +146 -0
- model_arena/_mac_runtime/observatorio_athena/classic_charts.py +19 -0
- model_arena/_mac_runtime/observatorio_athena/common.py +50 -0
- model_arena/_mac_runtime/observatorio_athena/historical_sigma.py +85 -0
- model_arena/_mac_runtime/observatorio_athena/mac_rules_reference.py +261 -0
- model_arena/_mac_runtime/observatorio_athena/monitor_c2.py +89 -0
- model_arena/_mac_runtime/observatorio_athena/observed_quantiles.py +14 -0
- model_arena/_mac_runtime/observatorio_athena/prepare.py +292 -0
- model_arena/_mac_runtime/observatorio_athena/repository.py +103 -0
- model_arena/_mac_runtime/observatorio_athena/schemas.py +41 -0
- model_arena/_mac_runtime/observatorio_athena/theme.py +1 -0
- model_arena/_mac_runtime/observatorio_athena/training_charts.py +24 -0
- model_arena/_mac_runtime/observatorio_athena/ui.py +242 -0
- model_arena/_mac_runtime/publicar.py +17 -0
- model_arena/_mac_runtime/scripts/runtime_bootstrap.py +168 -0
- model_arena/_version.py +2 -0
- model_arena/arena.py +405 -0
- model_arena/aws.py +111 -0
- model_arena/cli.py +23 -0
- model_arena/contracts.py +151 -0
- model_arena/dashboard.py +155 -0
- model_arena/data.py +100 -0
- model_arena/models/base.py +31 -0
- model_arena/models/naive.py +33 -0
- model_arena/models/tft.py +237 -0
- model_arena/observatory.py +88 -0
- model_arena/profiles/__init__.py +2 -0
- model_arena/profiles/mac.py +133 -0
- model_arena/profiles/mac_worker.py +103 -0
- model_arena/results.py +59 -0
- model_arena/storage.py +95 -0
- model_arena/winner_selection.py +33 -0
- model_arena_sdk-0.1.dist-info/METADATA +107 -0
- model_arena_sdk-0.1.dist-info/RECORD +75 -0
- model_arena_sdk-0.1.dist-info/WHEEL +4 -0
- model_arena_sdk-0.1.dist-info/entry_points.txt +2 -0
- model_arena_sdk-0.1.dist-info/licenses/LICENSE +22 -0
model_arena/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Model Arena. Training and UI dependencies are loaded only when requested."""
|
|
2
|
+
from .contracts import ArenaSpec, ModelSpec, PanelSchema, TemporalCV
|
|
3
|
+
from .arena import ModelArena
|
|
4
|
+
|
|
5
|
+
from ._version import __version__ as __version__
|
|
6
|
+
__all__ = ["ModelArena", "ArenaSpec", "ModelSpec", "PanelSchema", "TemporalCV"]
|
|
7
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"build_id": "OBS-ENTRENAR-PUBLICAR-MONITOR-0121", "version": "0.13.1-compat", "files": {"abrir_monitor.py": "2626017ff23d904c7a751519f669f693b6d53340f8889b971942ba6995dc840c", "app.py": "8b7c9318a443d9287e49c4d86acb970698956f989bc6523c0365c009d262fe66", "flujo_completo.py": "6cb41d822b84d7397abbb8f261b84f211016b367c4e94cefdfdfe41ec1fb858a", "publicar.py": "f55e3450c881eb3b00af581227484d4d22412b65f532582f134602c8e6aab498", "observatorio_athena/schemas.py": "684cf265a55821af8dfaebe993f5829abbfa5608b40f13414eff41cb4515dac5", "observatorio_athena/__init__.py": "3c0b8123c23a17d62effce978c8db26969fc42609df59bcaeed9192d6bc483e4", "observatorio_athena/repository.py": "fcbea1822ddafdcde607c6d3fdef82136eb58a4ad626979cf79cfa5b0c10a82d", "observatorio_athena/aws.py": "e77a148c24a060ad9059c85b16a129d71122371ec862d4ce7857d310766c0b21", "observatorio_athena/account_previews.py": "78cf27649c525ddfc303a8886f80d4e3b8b4c933702ae154b62be79aef63e7ab", "observatorio_athena/alerts_view.py": "4f3f7959b5cece799b72dfd8a64fbf09d7e0ac166280c99e078c2986a09ef27a", "observatorio_athena/classic_charts.py": "2d84eea897ede16d6ed52488b13b32056c986ec17834e31ffea82a23f978273c", "observatorio_athena/analysis.py": "822be73e5d8fa6da0c5637d3c8a3c413af351470520ad693d1883c97488d4ebb", "observatorio_athena/common.py": "f8b96eef342c5acb49c204564be3035a1fd163768a177800cbd3719a78ca23eb", "observatorio_athena/theme.py": "3462d240e3ffc5cc74aebe5c511074efaa31d34959a1e843672533aa9079af78", "observatorio_athena/observed_quantiles.py": "63bb624b27372ec7a5d658260ee1108b940d194c16f13aa02b18acd5e1cdc6a5", "observatorio_athena/historical_sigma.py": "1b8143a19c687097c34868b16f507abca6b41342e81074bfafe7d067aca1a628", "observatorio_athena/mac_rules_reference.py": "943c8fe98eef9000ed0262e919e432245ef84f3b3639b0beb9cf60fcc925a460", "observatorio_athena/prepare.py": "ded3a9fd681b99cb93332e9e26c6efa3a99d8dde5bd389bb43b0ad5e80fb4256", "observatorio_athena/monitor_c2.py": "18e61714d0f7b09c84dca0178620db671f473c064736649d48d98a2d950955a9", "observatorio_athena/training_charts.py": "eed2323e5ead80858f72dba217a41d42b7d08679668de66fe2e19c11d0f4e136", "observatorio_athena/ui.py": "481625b0b3ba41a9f45f6ddbb3b9858175895d88aa295e6bdf60c64727ef8ff3", "observatorio_athena/alert_taxonomy.py": "91f7fc15108a4e5e8471a406dcf259a1d24a5d26da55d8665111afa022ac4821", "entrenamiento/curvas_metricas.py": "1211a29e754ccce0cf516293766b691f3c699d015a4c55b43d54192f35089004", "entrenamiento/monitor_learning.py": "26f10f9c35a9c904b32320907df65f2d245676f2527386092347a05556d45769", "entrenamiento/entrenar_curvas.py": "ae20a99d5c45e670dd8b748fa8539da0005df7954b40d63fa1d493be698bd36b", "entrenamiento/curvas_modelo.py": "5c7fefd775afae5a5bc3cebe4a4d45aee6f7d8531fe532910ddc3c80f2e8f761", "entrenamiento/arena_estudio.py": "0d63a904dceb423e3300340d27d64bcc07d07544f4f76359951216a055374ced", "entrenamiento/curvas_contrato.py": "699f6d00d40413a929c4b2227c6a5585a1ab0575b133303ed05c827c39c208a3", "entrenamiento/e2e_worker.py": "8cc75a404e8b9eadcb5076449f9c872514e9ad190cc415880fcc835b6b6c66a9", "scripts/runtime_bootstrap.py": "a3ede52df2e9b0bb66e8f253143261c9bff9e3b4c6c44124d90e6866e0583ff5", "entrenamiento/visor/workspace.py": "be19f307ed2d72d3741d47279f5615a714f4cc84f280259358f408a654fc26aa", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/__init__.py": "62d449a323e1d92edb3ddcc5b0b9a93a0ea43807c9f5b450013f9c274d1ab295", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/contracts.py": "6c4acba8504a2a771b444631e1f2609bec20ce16c3df163958f2a8c0da65a36d", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/calendar.py": "6e9ac33fa2f2ff90ed4d9797262b0167add6ee41b550be3b8ec6b69d2da91413", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/data.py": "6376abcef801cc8f89a1d0da592fe8957d5b25f45718cff449559d18536b1b42", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/full_tft.py": "84e63868d33eed5751ce0f2543962a5a0f030779a10f16ff573cdfad2ac6b078", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/backbones.py": "bc34ca9d9dd11709d5b9c9bee2844c3716eb1cd03a9f909c5e71a890163f688b", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/engine.py": "3d161d7ef118c0cf966ac196397acfeae9cd05f62181a1033dee8b5f1962df98", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/percentage_metrics.py": "0b813483114b6f02d991e5d45ba25bf1ee371fd014a16d3c685d28c946015906", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/models.py": "62ca4f4032add98f7f30c3a9f9cc9ed4cd3a624a1dabc273b4440b5bc8b3e1f3", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/curve_models.py": "6e8d6c8bbb16c6358f725775813e7bdc264b18002d512e592cd7247c8190a6f3", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/surfaces.py": "654d53e8d08c2c3da3532eeb32e4de171767a3a669d6eef38068882bb249704f", "entrenamiento/libraries/agentic_forecasting/src/agentic_forecasting/api.py": "6c45ae36262c4799982cf20d32ee56328df52a0a4ba4dd9399a9a3df45d0e3a8", "entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/__init__.py": "f1a4318e60395f8a1b38f4036afbd5d26087b25457dccd27185d3b62aaa758e2", "entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/aws.py": "b71cc095708a31f3cbf5b09f49ddbda29d434e1dd5bf37acb16e128d5172a63e", "entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/calendar.py": "eac3ebe389cb8148cde5507a7ac7e5f9515542ef3cd3424fbfbb98305e99f4b0", "entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/universe.py": "86544246e82d4e289358661e6cd1663e34d670bd4b5f519a7d73ba55a54d36ac", "entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/sampling.py": "3288f4019930f0c246bdb008b0194ecd435c928851cf35bb978748cb79009a45", "entrenamiento/libraries/accountability_observatory/src/observatorio_cuentas/source_audit.py": "e2df8e12efb3bfc01272dad03fd0a3504df4fe54027eff7f815373f390893e00", "entrenamiento/libraries/accountability_observatory/src/accountability_observatory/__init__.py": "63dca83148d5f8c3fd7ef5b62112d3f20db55b8490df0af262169c9fe13298e9", "entrenamiento/libraries/accountability_observatory/src/accountability_observatory/application.py": "e71795bfa30ffb1737c70d4cbe0e16b107fad06ad653ac3ec52719eeda6ccb5d"}}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Only launches the exact native Streamlit/Athena app shipped here."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import importlib.metadata,importlib.util,json,os,socket,subprocess,sys,time,urllib.request,hashlib
|
|
4
|
+
ROOT=Path(__file__).resolve().parent
|
|
5
|
+
BUILD='OBS-ENTRENAR-PUBLICAR-MONITOR-0121'
|
|
6
|
+
_WORKER_ENVS={}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def verify(root):
|
|
10
|
+
root=Path(root).resolve();manifest=json.loads((root/'BUILD_MONITOR.json').read_text())
|
|
11
|
+
if manifest.get('build_id')!=BUILD:raise ValueError('La carpeta no corresponde al monitor Streamlit Athena 0.12.1')
|
|
12
|
+
for name,digest in manifest['files'].items():
|
|
13
|
+
path=root/name
|
|
14
|
+
if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest()!=digest:raise ValueError('Archivo de otra entrega: '+str(path))
|
|
15
|
+
return root
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def find_bundle(cwd=None,explicit=None):
|
|
19
|
+
if explicit:return verify(explicit)
|
|
20
|
+
cwd=Path(cwd or Path.cwd()).resolve();found=[]
|
|
21
|
+
for base in [cwd,*list(cwd.parents)[:3]]:
|
|
22
|
+
for root in [base,base/'Observatorio_Entrenar_Publicar_Monitor_0121']:
|
|
23
|
+
if (root/'BUILD_MONITOR.json').is_file():
|
|
24
|
+
try:checked=verify(root)
|
|
25
|
+
except (ValueError,KeyError,FileNotFoundError):continue
|
|
26
|
+
if checked not in found:found.append(checked)
|
|
27
|
+
if len(found)!=1:raise ValueError('Indica BUNDLE_PATH: se encontraron '+str(len(found))+' copias verificadas')
|
|
28
|
+
return found[0]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def worker_env(python):
|
|
32
|
+
cached=_WORKER_ENVS.get(str(python))
|
|
33
|
+
if cached is not None:return dict(cached)
|
|
34
|
+
path=ROOT/'scripts/runtime_bootstrap.py'
|
|
35
|
+
spec=importlib.util.spec_from_file_location('_obs_athena_runtime_environment',path)
|
|
36
|
+
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
|
|
37
|
+
return module.native_library_environment(module.worker_environment(),prefixes=(Path(python).parent.parent,sys.prefix,sys.base_prefix,'/opt/conda'))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def runtime(root,explicit=None):
|
|
41
|
+
candidates=[Path(explicit).expanduser()] if explicit else [Path(sys.executable),*sorted(Path(root).glob('.venv*/bin/python')),*sorted(Path(root).parent.glob('*/.venv*/bin/python'))]
|
|
42
|
+
failures=[]
|
|
43
|
+
for path in dict.fromkeys(candidates):
|
|
44
|
+
if not path.is_file():continue
|
|
45
|
+
native=worker_env(path);variants=[native]
|
|
46
|
+
# A monitor may reuse packages installed at user level in an existing runtime.
|
|
47
|
+
# Test the inherited environment as well; accept it only after real imports pass.
|
|
48
|
+
inherited=dict(os.environ)
|
|
49
|
+
inherited['LD_LIBRARY_PATH']=native.get('LD_LIBRARY_PATH','')
|
|
50
|
+
if inherited!=native:variants.append(inherited)
|
|
51
|
+
for env in variants:
|
|
52
|
+
checked=subprocess.run([str(path),'-c','import streamlit,polars,pyarrow,pandas,numpy,plotly,boto3'],capture_output=True,text=True,timeout=30,env=env)
|
|
53
|
+
if checked.returncode==0:
|
|
54
|
+
_WORKER_ENVS[str(path)]=env
|
|
55
|
+
return str(path)
|
|
56
|
+
failures.append(str(path)+' · '+checked.stderr[-300:])
|
|
57
|
+
raise RuntimeError('Indica WORKER_PYTHON con las dependencias del visor.\n'+'\n'.join(failures))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def monitor_runtime(root,provided=None):
|
|
61
|
+
if provided:return runtime(root,provided)
|
|
62
|
+
local=Path(root)/'.venv-monitor'/ 'bin/python'
|
|
63
|
+
for candidate in (local,Path(sys.executable)):
|
|
64
|
+
if candidate.is_file():
|
|
65
|
+
try:return runtime(root,str(candidate))
|
|
66
|
+
except RuntimeError:pass
|
|
67
|
+
import venv
|
|
68
|
+
print('Preparando entorno privado del monitor; no requiere GPU ni entrenamientos anteriores.',flush=True)
|
|
69
|
+
venv.EnvBuilder(with_pip=True,system_site_packages=True).create(local.parent.parent)
|
|
70
|
+
subprocess.run([str(local),'-m','pip','install','-r',str(Path(root)/'requirements.txt')],check=True,env=worker_env(local))
|
|
71
|
+
return runtime(root,str(local))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def launch(config=None,python=None):
|
|
75
|
+
verify(ROOT);python=runtime(ROOT,python)
|
|
76
|
+
config=Path(config or ROOT/'config/ada.json').resolve()
|
|
77
|
+
with socket.socket() as sock:sock.bind(('127.0.0.1',0));port=sock.getsockname()[1]
|
|
78
|
+
prefix=os.environ.get('JUPYTERHUB_SERVICE_PREFIX','/jupyterlab/default/').rstrip('/')+f'/proxy/absolute/{port}'
|
|
79
|
+
logpath=ROOT/f'monitor_athena_{port}.log'
|
|
80
|
+
with logpath.open('w') as log:
|
|
81
|
+
proc=subprocess.Popen([python,'-m','streamlit','run',str(ROOT/'app.py'),'--server.address','127.0.0.1','--server.port',str(port),'--server.baseUrlPath',prefix.lstrip('/'),'--server.headless','true','--browser.gatherUsageStats','false','--theme.base','light'],cwd=ROOT,env=dict(worker_env(python),OBS_CONFIG=str(config)),stdout=log,stderr=subprocess.STDOUT)
|
|
82
|
+
for _ in range(100):
|
|
83
|
+
if proc.poll() is not None:raise RuntimeError(logpath.read_text()[-4000:])
|
|
84
|
+
try:
|
|
85
|
+
with urllib.request.urlopen(f'http://127.0.0.1:{port}{prefix}/_stcore/health',timeout=1) as response:
|
|
86
|
+
if response.status==200:break
|
|
87
|
+
except OSError:time.sleep(.25)
|
|
88
|
+
else:
|
|
89
|
+
proc.terminate();raise TimeoutError(logpath.read_text()[-4000:])
|
|
90
|
+
proc.health_url=f'http://127.0.0.1:{port}{prefix}/_stcore/health';proc.logpath=logpath
|
|
91
|
+
from IPython.display import display,HTML
|
|
92
|
+
display(HTML(f'<a href="{prefix}/" target="_blank" rel="noopener" style="display:inline-block;background:#072146;color:white;padding:16px 28px;border-radius:10px;text-decoration:none;font:600 16px Arial;box-shadow:0 4px 14px #07214630;border-left:5px solid #02a5a5">Abrir Observatorio ↗</a>'))
|
|
93
|
+
print('Build:',BUILD,'· Carpeta:',ROOT,'· PID:',proc.pid)
|
|
94
|
+
print('La salud HTTP confirma el servidor; la interfaz requiere conexión del navegador.')
|
|
95
|
+
return proc
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
import os
|
|
3
|
+
import streamlit as st
|
|
4
|
+
from observatorio_athena.common import Config
|
|
5
|
+
from observatorio_athena.aws import Athena
|
|
6
|
+
from observatorio_athena.ui import render_app
|
|
7
|
+
ROOT=Path(__file__).resolve().parent
|
|
8
|
+
config=Config.read(os.environ.get('OBS_CONFIG',str(ROOT/'config/ada.json')))
|
|
9
|
+
@st.cache_resource
|
|
10
|
+
def query_client(settings):
|
|
11
|
+
return Athena(settings)
|
|
12
|
+
render_app(config,query_client(config))
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Temporal competition, persisted candidates, and winner-only inference."""
|
|
2
|
+
from dataclasses import asdict, replace
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from types import SimpleNamespace
|
|
5
|
+
import csv
|
|
6
|
+
import json
|
|
7
|
+
import pickle
|
|
8
|
+
import numpy as np
|
|
9
|
+
import optuna
|
|
10
|
+
import polars as pl
|
|
11
|
+
import torch
|
|
12
|
+
from entrenar_curvas import (ROOT, read, write, spec_for, execute, sha, make_frame)
|
|
13
|
+
from agentic_forecasting import Series
|
|
14
|
+
from agentic_forecasting.data import weighted_entropy
|
|
15
|
+
from model_arena.winner_selection import assignments
|
|
16
|
+
from curvas_modelo import CurveTFT, fit_curves, predict_curves
|
|
17
|
+
from curvas_metricas import REFERENCE
|
|
18
|
+
from curvas_contrato import KIND, RESULT
|
|
19
|
+
from observatorio_cuentas.calendar import read_calendar
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def population(run, config, spec):
|
|
23
|
+
axis = read(run/'source/operational_axis.json')['dates']
|
|
24
|
+
axis = axis[-config['observations']:] if config.get('observations') else axis
|
|
25
|
+
initial = len(axis)-3*spec.horizon
|
|
26
|
+
if initial < spec.window+spec.horizon:
|
|
27
|
+
raise ValueError('Historia insuficiente para tres folds')
|
|
28
|
+
data = pl.read_parquet(run/'source/engine1.parquet').filter(pl.col('date').is_in(axis)).sort('account_id','date')
|
|
29
|
+
seen, atypical, inventory, exclusions = [], [], [], []
|
|
30
|
+
for (aid,), group in data.group_by('account_id', maintain_order=True):
|
|
31
|
+
tax = group['taxonomy'][0]
|
|
32
|
+
if tax not in ('cuentas_entrenamiento','cuentas_atipicos'):
|
|
33
|
+
continue
|
|
34
|
+
values = group.select('balance','variation').to_numpy()
|
|
35
|
+
if group['date'].to_list() != axis or not np.isfinite(values).all():
|
|
36
|
+
exclusions.append(dict(account_id=aid,taxonomy=tax,reason='EJE_INCOMPLETO_O_NO_FINITO'))
|
|
37
|
+
continue
|
|
38
|
+
budget = min(10,int(weighted_entropy(values[:initial,0])*10)+1)
|
|
39
|
+
cohort = 'seen' if tax == 'cuentas_entrenamiento' else 'zero_shot'
|
|
40
|
+
item = Series(aid,axis,values,group['currency'][0],budget,cohort)
|
|
41
|
+
(seen if cohort == 'seen' else atypical).append(item)
|
|
42
|
+
inventory.append(dict(account_id=aid,currency=item.currency,budget=budget,cohort=cohort,taxonomy=tax))
|
|
43
|
+
write(run/'elegibilidad.json',dict(exclusiones=exclusions,entrenables=len(seen),atipicas=len(atypical)))
|
|
44
|
+
if not seen:
|
|
45
|
+
raise ValueError('Sin entrenables elegibles, revisar elegibilidad.json')
|
|
46
|
+
return axis, seen, atypical, pl.DataFrame(inventory)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def candidate_for(trial, inp, cfg):
|
|
50
|
+
return SimpleNamespace(id=trial.user_attrs.get('resume_candidate_id', f'{inp}_T{trial.number:04d}'),inputs=inp,
|
|
51
|
+
encoder_design=trial.suggest_categorical('encoder',cfg['encoders']),
|
|
52
|
+
depth=trial.suggest_categorical('encoder_depth',cfg['depths']),
|
|
53
|
+
decoder_depth=trial.suggest_categorical('decoder_depth',cfg['decoder_depths']),
|
|
54
|
+
width=trial.suggest_categorical('width',cfg['widths']),
|
|
55
|
+
activation=trial.suggest_categorical('activation',cfg['activations']),
|
|
56
|
+
lr=trial.suggest_float('lr',*cfg['lr_range'],log=True),
|
|
57
|
+
weight_decay=trial.suggest_float('weight_decay',*cfg['wd_range'],log=True))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def loss_rows(frame, candidate, inventory):
|
|
61
|
+
error = (pl.col('observed')-pl.col('forecast'))/pl.col('scale')
|
|
62
|
+
tau = pl.col('component').replace_strict({'Q2.5':.025,'Q50':.5,'Q97.5':.975})
|
|
63
|
+
return (frame.filter(pl.col('method') != REFERENCE)
|
|
64
|
+
.with_columns(pl.max_horizontal(tau*error,(tau-1)*error).alias('pinball'))
|
|
65
|
+
.group_by('account_id','currency','target','fold').agg(pl.col('pinball').mean().alias('score'))
|
|
66
|
+
.join(inventory.select('account_id','budget','cohort'),on='account_id',validate='m:1')
|
|
67
|
+
.with_columns(pl.lit(candidate.id).alias('candidate'),pl.lit(candidate.inputs).alias('input')))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def persist_history(root, candidate, fold, rows):
|
|
71
|
+
directory = root/'loss';directory.mkdir(exist_ok=True)
|
|
72
|
+
path = directory/f'{candidate}_{fold}.csv';temp=path.with_suffix('.tmp')
|
|
73
|
+
with temp.open('w', newline='') as stream:
|
|
74
|
+
writer=csv.DictWriter(stream, fieldnames=['candidate','fold','epoch','train_loss','validation_loss','train_loss_saldo','train_loss_variacion','fixed_train_saldo','fixed_train_variacion','fixed_validation_saldo','fixed_validation_variacion'])
|
|
75
|
+
writer.writeheader()
|
|
76
|
+
writer.writerows(dict(candidate=candidate,fold=fold,**row) for row in rows)
|
|
77
|
+
temp.replace(path)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def combine_history(root):
|
|
81
|
+
frames=[pl.read_csv(path,schema_overrides={k:pl.Float64 for k in ['validation_loss','fixed_train_saldo','fixed_train_variacion','fixed_validation_saldo','fixed_validation_variacion']}) for path in sorted((root/'loss').glob('*.csv'))]
|
|
82
|
+
if not frames:raise ValueError('No se generaron curvas de entrenamiento')
|
|
83
|
+
combined=pl.concat(frames).sort('candidate','fold','epoch')
|
|
84
|
+
path=root/'training_history.parquet';temp=path.with_suffix('.tmp')
|
|
85
|
+
combined.write_parquet(temp,compression='zstd');temp.replace(path)
|
|
86
|
+
return path
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def fit_saved(root, seen, dates, end, spec, candidate, fold, device, calendar, cfg):
|
|
90
|
+
if fold=='FUTURO':spec=replace(spec,epochs=int(cfg.get('final_epochs',spec.epochs)))
|
|
91
|
+
if spec.epochs<1:raise ValueError('Épocas debe ser positivo')
|
|
92
|
+
path = root/'modelos'/f'{candidate.id}_{fold}.pt'
|
|
93
|
+
path.parent.mkdir(exist_ok=True)
|
|
94
|
+
if path.exists():
|
|
95
|
+
saved = torch.load(path,map_location=device,weights_only=False)
|
|
96
|
+
model = CurveTFT(spec,candidate,cfg['dropout']).to(device)
|
|
97
|
+
model.load_state_dict(saved['state_dict'])
|
|
98
|
+
history = saved.get('training_history')
|
|
99
|
+
if not history:
|
|
100
|
+
raise ValueError('El checkpoint no contiene curvas de pérdida; usa una corrida de esta entrega')
|
|
101
|
+
persist_history(root, candidate.id, fold, history)
|
|
102
|
+
return model
|
|
103
|
+
known = [Series(s.id,dates,s.values[:end],s.currency,s.budget,s.cohort) for s in seen]
|
|
104
|
+
history = []
|
|
105
|
+
def on_epoch(row):
|
|
106
|
+
history.append(row)
|
|
107
|
+
persist_history(root, candidate.id, fold, history)
|
|
108
|
+
print(f'Ajustando {candidate.id} · {fold} · {len(known)} cuentas', flush=True)
|
|
109
|
+
from monitor_learning import build_monitor
|
|
110
|
+
monitor=build_monitor(known,seen,end,spec,candidate,device,calendar,fold,cfg,detail_path=root/"loss_entities"/f"{candidate.id}_{fold}.csv")
|
|
111
|
+
model = fit_curves(known,end,spec,candidate,device,calendar,cfg,on_epoch=on_epoch,monitor=monitor)
|
|
112
|
+
temp = path.with_suffix('.tmp')
|
|
113
|
+
torch.save(dict(state_dict=model.state_dict(),candidate=vars(candidate),spec=asdict(spec),
|
|
114
|
+
training_history=history,loss_monitor=monitor.selection,end=end,fold=fold,scaling='asinh(history/scale); forecast*scale',version='0.11.0',training_account_ids=[s.id for s in seen]),temp)
|
|
115
|
+
temp.replace(path)
|
|
116
|
+
return model
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def emit(model, series, dates, end, spec, candidate, fold, device, calendar):
|
|
120
|
+
known = [Series(s.id,dates,s.values[:end],s.currency,s.budget,s.cohort) for s in series]
|
|
121
|
+
forecast, baseline = predict_curves(model,known,end,spec,candidate,device,calendar)
|
|
122
|
+
observed = None if fold == 'FUTURO' else np.stack([s.values[end:end+spec.horizon] for s in series])
|
|
123
|
+
history = np.stack([s.values[end-spec.window:end] for s in series])
|
|
124
|
+
scales = np.maximum(np.maximum(np.median(np.abs(history),axis=1),np.quantile(history,.75,axis=1)-np.quantile(history,.25,axis=1)),1.)
|
|
125
|
+
return make_frame(forecast,baseline,observed,series,dates[end:end+spec.horizon],candidate,fold,dates[end-1],scales)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def run_study(run, config_path, device, *, stage="all"):
|
|
130
|
+
config = read(config_path)
|
|
131
|
+
if config["requested_accounts"] != 0:
|
|
132
|
+
raise ValueError("Esta versión entrena el universo elegible completo. Usa requested_accounts=0")
|
|
133
|
+
spec = spec_for(config)
|
|
134
|
+
torch.set_num_threads(spec.cpu_threads)
|
|
135
|
+
device = torch.device(device)
|
|
136
|
+
root = run/'curvas';root.mkdir(exist_ok=True)
|
|
137
|
+
identity = dict(config=config,codigo={str(p.relative_to(ROOT)):sha(p) for p in [ROOT/'arena_estudio.py',ROOT/'curvas_modelo.py',*list((ROOT/'libraries').rglob('*.py'))]})
|
|
138
|
+
if (root/'identidad.json').exists() and read(root/'identidad.json')!=identity:
|
|
139
|
+
raise ValueError('Usa una corrida nueva, cambió configuración o código')
|
|
140
|
+
write(root/'identidad.json',identity)
|
|
141
|
+
execute(run,config_path,'ingesta',str(device))
|
|
142
|
+
axis, seen, atypical, inventory = population(run,config,spec)
|
|
143
|
+
inventory.write_parquet(root/'inventory.parquet')
|
|
144
|
+
calendar = read_calendar(ROOT/'data/calendar_authoritative.csv')
|
|
145
|
+
dates = axis+calendar.after(axis[-1],spec.horizon)
|
|
146
|
+
calendar.take(dates)
|
|
147
|
+
folds = [(f'F{i+1}',len(axis)-(3-i)*spec.horizon) for i in range(3)]
|
|
148
|
+
cfg=config['curvas'];candidates=[];score_frames=[];trials=[]
|
|
149
|
+
(root/'predicciones').mkdir(exist_ok=True)
|
|
150
|
+
for inp in cfg['inputs']:
|
|
151
|
+
sampler_path=root/f'{inp}_sampler.pkl'
|
|
152
|
+
sampler=pickle.loads(sampler_path.read_bytes()) if sampler_path.exists() else optuna.samplers.TPESampler(seed=spec.seed+cfg['inputs'].index(inp))
|
|
153
|
+
study=optuna.create_study(study_name=inp,storage='sqlite:///'+str(root/'hpo.sqlite3'),load_if_exists=True,direction='minimize',sampler=sampler,pruner=optuna.pruners.NopPruner())
|
|
154
|
+
def objective(trial):
|
|
155
|
+
candidate=candidate_for(trial,inp,cfg)
|
|
156
|
+
trial.set_user_attr('candidate_id',candidate.id)
|
|
157
|
+
write(root/f'{candidate.id}.json',vars(candidate))
|
|
158
|
+
scores=[]
|
|
159
|
+
for fold,end in folds:
|
|
160
|
+
path=root/'predicciones'/f'{candidate.id}_{fold}.parquet'
|
|
161
|
+
if path.exists():
|
|
162
|
+
frame=pl.read_parquet(path)
|
|
163
|
+
else:
|
|
164
|
+
model=fit_saved(root,seen,dates,end,spec,candidate,fold,device,calendar,cfg)
|
|
165
|
+
frame=emit(model,seen,dates,end,spec,candidate,fold,device,calendar)
|
|
166
|
+
temp=path.with_suffix('.tmp');frame.write_parquet(temp);temp.replace(path)
|
|
167
|
+
scores.append(loss_rows(frame,candidate,inventory))
|
|
168
|
+
table=pl.concat(scores);table.write_parquet(root/f'{candidate.id}_scores.parquet')
|
|
169
|
+
return table['score'].mean()
|
|
170
|
+
# Interrupted trials can be retried with their exact parameters and paths.
|
|
171
|
+
for trial in study.get_trials(states=(optuna.trial.TrialState.RUNNING,)):
|
|
172
|
+
study.tell(trial.number,state=optuna.trial.TrialState.FAIL)
|
|
173
|
+
study.enqueue_trial(trial.params,user_attrs={'resume_candidate_id':trial.user_attrs.get('candidate_id',f'{inp}_T{trial.number:04d}')})
|
|
174
|
+
remaining=cfg['trials']-len(study.get_trials(states=(optuna.trial.TrialState.COMPLETE,)))
|
|
175
|
+
def persist_sampler(study, trial):
|
|
176
|
+
temp=sampler_path.with_suffix('.tmp')
|
|
177
|
+
temp.write_bytes(pickle.dumps(study.sampler));temp.replace(sampler_path)
|
|
178
|
+
if remaining>0:study.optimize(objective,n_trials=remaining,callbacks=[persist_sampler])
|
|
179
|
+
for trial in study.get_trials(states=(optuna.trial.TrialState.COMPLETE,)):
|
|
180
|
+
candidate_id=trial.user_attrs.get('candidate_id',f'{inp}_T{trial.number:04d}')
|
|
181
|
+
candidate=SimpleNamespace(**read(root/f'{candidate_id}.json'))
|
|
182
|
+
candidates.append(candidate)
|
|
183
|
+
score_frames.append(pl.read_parquet(root/f'{candidate.id}_scores.parquet'))
|
|
184
|
+
trials.append(dict(**vars(candidate),score=trial.value))
|
|
185
|
+
write(run/'estado_curvas.json',dict(estado='HPO',input=inp,trials_completos=len(trials)))
|
|
186
|
+
scores=pl.concat(score_frames);scores.write_parquet(root/'scores.parquet')
|
|
187
|
+
write(root/'candidatos.json',trials)
|
|
188
|
+
for name, groups in [('finalists_budget.parquet',['budget','input']),('finalists_total.parquet',['input'])]:
|
|
189
|
+
finalists=scores.group_by(*groups,'candidate').agg(pl.col('score').mean()).sort(*groups,'score','candidate').unique(groups,keep='first')
|
|
190
|
+
finalists.write_parquet(root/name)
|
|
191
|
+
if stage == "tune":
|
|
192
|
+
combine_history(root)
|
|
193
|
+
return root
|
|
194
|
+
records=[];prior=[]
|
|
195
|
+
for fold,end in [*folds,('FUTURO',len(axis))]:
|
|
196
|
+
chosen=assignments(scores,inventory,candidates,prior)
|
|
197
|
+
chosen.write_parquet(root/f'winners_{fold}.parquet')
|
|
198
|
+
pieces=[]
|
|
199
|
+
for candidate in candidates:
|
|
200
|
+
ids=set(chosen.filter(pl.col('candidate')==candidate.id)['account_id'])
|
|
201
|
+
if not ids:continue
|
|
202
|
+
model=fit_saved(root,seen,dates,end,spec,candidate,fold,device,calendar,cfg)
|
|
203
|
+
group=[s for s in [*seen,*atypical] if s.id in ids]
|
|
204
|
+
frame=emit(model,group,dates,end,spec,candidate,fold,device,calendar)
|
|
205
|
+
pieces.append(frame.with_columns(pl.col('method').alias('candidate_model'),
|
|
206
|
+
pl.when(pl.col('method')==REFERENCE).then(pl.lit(REFERENCE)).otherwise(pl.lit('Winner')).alias('method')))
|
|
207
|
+
output=root/'predicciones'/f'Winner_{fold}.parquet'
|
|
208
|
+
pl.concat(pieces).write_parquet(output)
|
|
209
|
+
records.append(dict(modelo='Winner',fold=fold,origen=dates[end-1],desde=dates[end],hasta=dates[end+spec.horizon-1],predicciones=str(output.relative_to(root))))
|
|
210
|
+
prior.append(fold)
|
|
211
|
+
training_history=combine_history(root)
|
|
212
|
+
report=dict(version='0.11.0',training_history=str(training_history.relative_to(root)),loss_function='pinball normalizado; tres cuantiles y dos objetivos',validation_loss_available=False,corrida=run.name,horizonte=spec.horizon,
|
|
213
|
+
muestra=dict(entrenadas=len(seen),atipicas_zero_shot=len(atypical)),ajustes=records[:-1],futuro=records[-1],
|
|
214
|
+
seleccion=dict(mejor_tft='Winner',referencia_recomendada_en_esta_prueba='Winner'),config=config)
|
|
215
|
+
write(root/RESULT,report)
|
|
216
|
+
write(root/'manifest.json',dict(kind=KIND,run_id=run.name,accounts=inventory.height,horizonte=spec.horizon))
|
|
217
|
+
write(ROOT/'active_curvas.json',dict(run=str(root)))
|
|
218
|
+
write(run/'estado_curvas.json',dict(estado='COMPLETO',reporte=str(root/RESULT)))
|
|
219
|
+
return root/RESULT
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Evaluación pareada y selección cronológica de las ocho curvas."""
|
|
2
|
+
|
|
3
|
+
import polars as pl
|
|
4
|
+
from curvas_contrato import COMPONENTS, TARGETS
|
|
5
|
+
|
|
6
|
+
REFERENCE = 'Persistencia'
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def paired(frame):
|
|
10
|
+
by_day = [
|
|
11
|
+
'input','encoder','fold','origin','date','h','account_id',
|
|
12
|
+
'currency','target','component',
|
|
13
|
+
]
|
|
14
|
+
evaluated = frame.filter(pl.col('observed').is_not_null())
|
|
15
|
+
original = evaluated.filter(pl.col('method') != REFERENCE)
|
|
16
|
+
reference = evaluated.filter(pl.col('method') == REFERENCE).select(
|
|
17
|
+
*by_day, pl.col('forecast').alias('reference')
|
|
18
|
+
)
|
|
19
|
+
points = original.join(reference, on=by_day, validate='1:1')
|
|
20
|
+
if points.height != original.height or points.height != reference.height:
|
|
21
|
+
raise ValueError('Predicciones y referencia incompletas')
|
|
22
|
+
daily = points.with_columns(
|
|
23
|
+
(pl.col('forecast')-pl.col('observed')).abs().alias('error'),
|
|
24
|
+
(pl.col('reference')-pl.col('observed')).abs().alias('error_ref'),
|
|
25
|
+
(pl.col('forecast')-pl.col('observed')).alias('signed_error'),
|
|
26
|
+
)
|
|
27
|
+
account = daily.group_by(
|
|
28
|
+
'input','encoder','fold','account_id','currency','target','component'
|
|
29
|
+
).agg(
|
|
30
|
+
mae=pl.col('error').mean(), mae_ref=pl.col('error_ref').mean(),
|
|
31
|
+
sesgo=pl.col('signed_error').mean(), fechas=pl.len(),
|
|
32
|
+
).with_columns(
|
|
33
|
+
(pl.col('mae')-pl.col('mae_ref')).alias('delta'),
|
|
34
|
+
((pl.col('mae')-pl.col('mae_ref'))/(pl.col('mae')+pl.col('mae_ref'))).fill_nan(0.).alias('delta_simetrico'),
|
|
35
|
+
)
|
|
36
|
+
return account, daily
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def aggregate(frame):
|
|
40
|
+
account, daily = paired(frame)
|
|
41
|
+
totals = account.group_by('target','component').agg(
|
|
42
|
+
cuentas=pl.len(),
|
|
43
|
+
ganan=(pl.col('delta') < -1e-6).sum(),
|
|
44
|
+
empatan=(pl.col('delta').abs() <= 1e-6).sum(),
|
|
45
|
+
persistencia_exacta=(pl.col('mae_ref') == 0).sum(),
|
|
46
|
+
cambio_simetrico_medio=pl.col('delta_simetrico').mean(),
|
|
47
|
+
mediana_cambio_mae_pct=(
|
|
48
|
+
100*pl.col('delta')/pl.when(pl.col('mae_ref')>0).then(pl.col('mae_ref'))
|
|
49
|
+
).median(),
|
|
50
|
+
).sort('target','component')
|
|
51
|
+
by_currency = account.group_by('currency','target','component').agg(
|
|
52
|
+
cuentas=pl.len(),ganan=(pl.col('delta') < -1e-6).sum(),
|
|
53
|
+
mediana_mae_modelo=pl.col('mae').median(),mediana_mae_persistencia=pl.col('mae_ref').median(),
|
|
54
|
+
mediana_delta=pl.col('delta').median(),p90_delta=pl.col('delta').quantile(.9,interpolation='linear'),
|
|
55
|
+
mediana_sesgo=pl.col('sesgo').median(),
|
|
56
|
+
).sort('currency','target','component')
|
|
57
|
+
by_step = daily.with_columns(
|
|
58
|
+
((pl.col('error')-pl.col('error_ref'))/(pl.col('error')+pl.col('error_ref'))).fill_nan(0.).alias('delta'),
|
|
59
|
+
).group_by('h','target','component').agg(
|
|
60
|
+
cuentas=pl.len(),ganan=(pl.col('error') < pl.col('error_ref') - 1e-6).sum(),
|
|
61
|
+
cambio_simetrico_medio=pl.col('delta').mean(),
|
|
62
|
+
).sort('h','target','component')
|
|
63
|
+
diagnostics = []
|
|
64
|
+
for target in TARGETS:
|
|
65
|
+
subset = frame.filter(pl.col('target') == target)
|
|
66
|
+
for method in subset['method'].unique().sort():
|
|
67
|
+
wide = subset.filter(pl.col('method') == method).pivot(
|
|
68
|
+
on='component', index=['account_id','date'], values='forecast')
|
|
69
|
+
actual = subset.filter((pl.col('method') == method) & (pl.col('component') == 'Q50')).select(
|
|
70
|
+
'account_id','date',pl.col('observed').alias('y'))
|
|
71
|
+
wide = wide.join(actual,on=['account_id','date']).sort('account_id','date')
|
|
72
|
+
loss = {}
|
|
73
|
+
for name,q in [('Q2.5',.025),('Q50',.5),('Q97.5',.975)]:
|
|
74
|
+
e = pl.col('y')-pl.col(name)
|
|
75
|
+
loss[name] = pl.max_horizontal(q*e,(q-1)*e).mean()
|
|
76
|
+
per = wide.group_by('account_id').agg(
|
|
77
|
+
rmse_q50=((pl.col('y')-pl.col('Q50'))**2).mean().sqrt(),
|
|
78
|
+
coverage=pl.col('y').is_between(pl.col('Q2.5'),pl.col('Q97.5')).mean(),
|
|
79
|
+
width=(pl.col('Q97.5')-pl.col('Q2.5')).mean(), **loss).sort('account_id')
|
|
80
|
+
diagnostics.append(dict(target=target,method=method,**per.drop('account_id').mean().row(0,named=True)))
|
|
81
|
+
return {**selection_loss(frame),'diagnostico_predictivo':diagnostics,'por_curva':totals.to_dicts(),'por_divisa':by_currency.to_dicts(),'por_paso':by_step.to_dicts()}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def curve_score(evaluation):
|
|
85
|
+
return evaluation['score']
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def selection_loss(frame):
|
|
89
|
+
"""Score por observado real, normalizado con historia anterior al corte."""
|
|
90
|
+
import numpy as np
|
|
91
|
+
components = {}
|
|
92
|
+
for target in TARGETS:
|
|
93
|
+
rows = frame.filter((pl.col('target') == target) & (pl.col('method') != REFERENCE))
|
|
94
|
+
losses = []
|
|
95
|
+
for name, q in [('Q2.5', .025), ('Q50', .5), ('Q97.5', .975)]:
|
|
96
|
+
error = (pl.col('observed') - pl.col('forecast')) / pl.col('scale')
|
|
97
|
+
item = rows.filter(pl.col('component') == name)
|
|
98
|
+
losses.append(item.select(pl.max_horizontal(q*error, (q-1)*error).mean()).item())
|
|
99
|
+
pinball = float(np.mean(losses))
|
|
100
|
+
components[target] = dict(pinball_normalizado=pinball, loss=pinball)
|
|
101
|
+
return dict(score=float(np.mean([v['loss'] for v in components.values()])), loss_components=components)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Ingesta original Engine 1, aislada de los monitores y entrenadores anteriores."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import hashlib,json,sys,time
|
|
4
|
+
ROOT=Path(__file__).resolve().parent
|
|
5
|
+
sys.path[:0]=[str(ROOT/'visor'),*(str(p) for p in (ROOT/'libraries').glob('*/src'))]
|
|
6
|
+
from workspace import dump,canonical_history
|
|
7
|
+
|
|
8
|
+
def sha(path):
|
|
9
|
+
with Path(path).open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
|
|
10
|
+
|
|
11
|
+
def execute(run,config,stage,device='cuda',resume=True):
|
|
12
|
+
if stage!='ingesta':raise ValueError('Este adaptador solamente ingiere Engine 1')
|
|
13
|
+
import polars as pl
|
|
14
|
+
import numpy as np
|
|
15
|
+
from observatorio_cuentas.calendar import read_calendar
|
|
16
|
+
run=Path(run).resolve();run.mkdir(parents=True,exist_ok=True)
|
|
17
|
+
cfg=json.loads(Path(config).read_text())
|
|
18
|
+
files=[*ROOT.glob('*.py'),*ROOT.rglob('libraries/**/*.py'),ROOT/'visor/workspace.py']
|
|
19
|
+
identity=dict(config=cfg,code_sha256={str(p.relative_to(ROOT)):sha(p) for p in sorted(set(files))},calendar_sha256=sha(ROOT/'data/calendar_authoritative.csv'))
|
|
20
|
+
if cfg.get('engine1_path'):identity['input_sha256']=sha(Path(cfg['engine1_path']).expanduser().resolve())
|
|
21
|
+
lock=run/'configuration.json'
|
|
22
|
+
if lock.exists():
|
|
23
|
+
if json.loads(lock.read_text())!=identity:raise ValueError('Cambió el código, configuración o Engine1. Crea una corrida nueva.')
|
|
24
|
+
else:dump(lock,identity)
|
|
25
|
+
receipt=run/'receipts/ingesta.json'
|
|
26
|
+
if resume and receipt.exists():
|
|
27
|
+
rec=json.loads(receipt.read_text())
|
|
28
|
+
if rec['configuration_sha256']!=sha(lock):raise ValueError('Identidad de ingesta distinta')
|
|
29
|
+
for name,digest in rec['outputs'].items():
|
|
30
|
+
if not (run/name).is_file() or sha(run/name)!=digest:raise ValueError('Ingesta modificada o incompleta: '+name)
|
|
31
|
+
print('Ingesta reutilizada · hashes verificados',flush=True);return
|
|
32
|
+
start=time.time();cal=read_calendar(ROOT/'data/calendar_authoritative.csv')
|
|
33
|
+
if cfg.get('engine1_path'):
|
|
34
|
+
source=Path(cfg['engine1_path']).expanduser().resolve()
|
|
35
|
+
frame,_=canonical_history(source,cfg.get('snapshot'))
|
|
36
|
+
dump(run/'source/file_origin.json',dict(path=str(source),sha256=sha(source)))
|
|
37
|
+
axis=sorted(frame['date'].unique().to_list())
|
|
38
|
+
dump(run/'source/account_plan.json',dict(status='FILE_INPUT_NO_PLAN_QUERY'))
|
|
39
|
+
else:
|
|
40
|
+
from observatorio_cuentas.aws import AwsAdapter,AwsSettings
|
|
41
|
+
adapter=AwsAdapter(AwsSettings(**cfg['aws']),run)
|
|
42
|
+
adapter.preflight();frame=adapter.ingest(cal);adapter.account_plan();axis=adapter.operational_dates(cal)
|
|
43
|
+
cal.take(axis);cal.after(axis[-1],cfg['model']['horizon'])
|
|
44
|
+
if not np.isfinite(frame.select('balance','variation','fx').to_numpy()).all() or frame.filter(pl.col('fx')<=0).height:raise ValueError('Importe, variación o FX inválido')
|
|
45
|
+
frame=frame.sort('account_id','date');(run/'source').mkdir(exist_ok=True)
|
|
46
|
+
frame.write_parquet(run/'source/engine1.parquet',compression='zstd')
|
|
47
|
+
dump(run/'source/operational_axis.json',dict(dates=axis,source='authoritative calendar intersect Engine1 operational dates before selection'))
|
|
48
|
+
outputs=[p for p in (run/'source').glob('*') if p.is_file()]
|
|
49
|
+
dump(receipt,dict(stage=stage,status='PASS',seconds=time.time()-start,configuration_sha256=sha(lock),outputs={str(p.relative_to(run)):sha(p) for p in outputs}))
|
|
50
|
+
print('Ingesta PASS ·',frame.height,'filas',flush=True)
|