Simple7up commited on
Commit
a2e2520
·
verified ·
1 Parent(s): 6c6cd2b

Upload 55 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. AMOXTLI_IN_ATL_MIQUIZTLI.md +73 -0
  3. Amoxtli in Atl Miquiztli - Libro del Agua y de la Muerte.pdf +3 -0
  4. Del Orden Universal a la Autonomía Absoluta_ El Sendero del Mictlán.pdf +3 -0
  5. MANUAL_ALINEACION_DOMINIOS.md +79 -0
  6. MANUAL_APRENDIZAJE_CONCORDANCIA.md +48 -0
  7. MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md +26 -0
  8. MARCOI.O.txt +15 -0
  9. MODULO_DIDACTICO_EVALUACION_CIEGA.md +34 -0
  10. PREMISAS_Y_TEOREMAS.md +89 -0
  11. PROTOCOLO_DE_MAPEO.md +135 -0
  12. README.md +16 -0
  13. RELACIONES_OPERATIVAS.md +107 -0
  14. TRIADAS_CATEGORIALES.md +101 -0
  15. VALIDACION_INDEPENDIENTE.md +86 -0
  16. VECTORES_4_5.md +57 -0
  17. __init__.py +0 -0
  18. audit_perfect_metrics.py +164 -0
  19. baselines.py +215 -0
  20. capture_environment.py +43 -0
  21. check_generated_committed.py +77 -0
  22. cosmos_nahuatl.csv +17 -0
  23. create_manifest.py +55 -0
  24. examples.csv +6 -0
  25. generate_audit_report.py +64 -0
  26. generate_ontology.py +224 -0
  27. importar_datos_personalizados.py +291 -0
  28. io_shapes.ttl +123 -0
  29. materialize_ttl.py +21 -0
  30. measure_invariance.py +144 -0
  31. migrate_spec.py +63 -0
  32. package_reproducible.py +31 -0
  33. paper.md +41 -0
  34. pi_hgat_t.py +240 -0
  35. plantilla_dominio.csv +9 -0
  36. relation_candidates.csv +391 -0
  37. requirements-lock.txt +25 -0
  38. requirements.txt +7 -0
  39. score_independent_eval.py +407 -0
  40. score_quiz.py +37 -0
  41. self_bootstrap.py +179 -0
  42. sync_spec_artifacts.py +159 -0
  43. test_formal_rules_bridge.py +150 -0
  44. test_metrics_audit.py +80 -0
  45. test_ontology.py +277 -0
  46. test_pi_hgat_t.py +36 -0
  47. test_property_based.py +179 -0
  48. test_property_links.py +110 -0
  49. test_score_independent_eval.py +160 -0
  50. test_validate_spec.py +78 -0
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Amoxtli[[:space:]]in[[:space:]]Atl[[:space:]]Miquiztli[[:space:]]-[[:space:]]Libro[[:space:]]del[[:space:]]Agua[[:space:]]y[[:space:]]de[[:space:]]la[[:space:]]Muerte.pdf filter=lfs diff=lfs merge=lfs -text
2
+ Del[[:space:]]Orden[[:space:]]Universal[[:space:]]a[[:space:]]la[[:space:]]Autonomía[[:space:]]Absoluta_[[:space:]]El[[:space:]]Sendero[[:space:]]del[[:space:]]Mictlán.pdf filter=lfs diff=lfs merge=lfs -text
AMOXTLI_IN_ATL_MIQUIZTLI.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Amoxtli in Atl Miquiztli — Libro del agua y de la muerte
2
+
3
+ > **Relato pictográfico del Mictlán** (relato original inspirado en la tradición nahua).
4
+ > PDF: [`media/cosmos_nahuatl/Amoxtli in Atl Miquiztli - Libro del Agua y de la Muerte.pdf`](media/cosmos_nahuatl/Amoxtli%20in%20Atl%20Miquiztli%20-%20Libro%20del%20Agua%20y%20de%20la%20Muerte.pdf) (9 páginas).
5
+
6
+ Documento de **apoyo semántico** al carácter del repositorio: 13 tríadas ↔ Mictlán; Mictecacíhuatl = Evolución; Mictlantecuhtli = Involución; Dualidad / Xólotl en el xoloitzcuintle. No modifica los 78 nodos canónicos.
7
+
8
+ ---
9
+
10
+ ## Resumen estructural
11
+
12
+ | Lámina | Título | Contenido operativo |
13
+ |--------|--------|---------------------|
14
+ | I | El agua que recibe a los muertos | Tonalli se desprende; río único; **xoloitzcuintle** guía el primer cruce |
15
+ | II | Las nueve señales | Nueve experiencias de **una** corriente (no nueve ríos) |
16
+ | III | El que regresa sin cuerpo | Retorno al origen como esqueleto; fin de la compañía del xolo |
17
+ | IV | El río de las nueve aguas | Segundo cruce: mirar desde lo transformado |
18
+ | V | Los cuatro pasos que son uno | Relaciones Tonalli ↔ Mictecacíhuatl ↔ Mictlantecuhtli con flechas → / ← |
19
+ | VI | La niebla sin orillas | Encuentro con los señores del Mictlán |
20
+ | VII | La ofrenda de Tonalli | Entrega y disolución en la corriente |
21
+ | VIII | El lugar que no puede pintarse | Límite de la representación; el río permanece |
22
+
23
+ **Colofón:** «Las trece señales son una forma de contar; las nueve aguas, de recordar; los cuatro pasos, de mirar desde otro lado. **El río es uno.**»
24
+
25
+ ---
26
+
27
+ ## Alineación al marco I.O.
28
+
29
+ ### Trece marcas = 13 tríadas
30
+
31
+ El tlacuilo formula explícitamente: *nueve señales + cuatro pasos = trece marcas en el códice*, pero **una sola corriente**. Eso coincide con la equivalencia canónica **13 tríadas ↔ arquitectura del Mictlán** ([`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md)).
32
+
33
+ ### Posiciones → / 0 / ← en la Lámina V
34
+
35
+ | Paso | Esquema |
36
+ |------|---------|
37
+ | Primera | Tonalli → \| Mictecacíhuatl \| → |
38
+ | Segunda | ← \| Tonalli \| ← Mictlantecuhtli |
39
+ | Tercera | Mictecacíhuatl → \| Tonalli \| → |
40
+ | Cuarta | ← \| Mictlantecuhtli \| ← Tonalli |
41
+
42
+ | Figura / entidad | Perspectiva / rol |
43
+ |------------------|-------------------|
44
+ | **Tonalli** (viajero) | Individualidad en tránsito |
45
+ | **Xoloitzcuintle** | Dualidad / **Xólotl** — guía, primer cruce |
46
+ | **Mictecacíhuatl** | **Evolución** |
47
+ | **Mictlantecuhtli** | **Involución** |
48
+ | Río único | Totalidad del sistema |
49
+ | Primer cruce (con guía) | Fase **adv** |
50
+ | Segundo cruce (solo) | Fase **ret** |
51
+ | Ofrenda y disolución | `creates` hacia el vacío |
52
+
53
+ ### Pares candidatos (EXP-E)
54
+
55
+ | id | source | target | perspectiva | relación candidata |
56
+ |----|--------|--------|-------------|-------------------|
57
+ | AMX-01 | Tonalli | río / Mictlán | Individualidad → Totalidad | `creates` |
58
+ | AMX-02 | xoloitzcuintle | Tonalli | Dualidad | `mirrorOf` |
59
+ | AMX-03 | nueve señales | una corriente | Totalidad | — |
60
+ | AMX-04 | primer cruce | segundo cruce | Evolución / Involución | `mirrorOf` |
61
+ | AMX-05 | Mictecacíhuatl | Mictlantecuhtli | Evolución / Involución | `mirrorOf` |
62
+ | AMX-06 | Tonalli (esqueleto) | ofrenda | Involución | `creates` |
63
+ | AMX-07 | tinta del tlacuilo | río que continúa | Dualidad | `none` |
64
+
65
+ ---
66
+
67
+ ## Uso en el repositorio
68
+
69
+ - Dominio: [`DOMINIO_COSMOS_NAHUATL.md`](DOMINIO_COSMOS_NAHUATL.md)
70
+ - Carácter: [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md)
71
+ - Medios: [`media/cosmos_nahuatl/README.md`](media/cosmos_nahuatl/README.md)
72
+
73
+ **Límite:** relato original inspirado en tradición nahua, no fuente histórica primaria. No añade nodos al core de 78.
Amoxtli in Atl Miquiztli - Libro del Agua y de la Muerte.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:547196600f11fbd15dc15f0e1cefff266eec63a3ee28f043ee7662ce6b395c5f
3
+ size 947064
Del Orden Universal a la Autonomía Absoluta_ El Sendero del Mictlán.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a2e1e4975c2ea055b88f87e4b72acf794bafaec0392e0194683aad06daa4a1f
3
+ size 724600
MANUAL_ALINEACION_DOMINIOS.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Manual de alineación: cartografía del destino Mictlán
2
+
3
+ > El Mictlán **no** es un dominio empírico más. Es la **lectura de destino** del marco
4
+ > (disolución del observador, auto-creación desde el vacío). Otros dominios son
5
+ > ejercicios secundarios. **No** existe «prueba primaria EXP-A» que legitime el mapeo.
6
+ >
7
+ > [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md) ·
8
+ > [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md)
9
+
10
+ ---
11
+
12
+ ## 1. Invarianza del núcleo
13
+
14
+ 78 nodos (13 × 2 × 3) = bóveda técnica. Conceptos externos se alinean **sin** alterar `iom_spec.json`, Lean ni SHACL.
15
+
16
+ | Perspectiva | Lectura bajo autonomía |
17
+ |-------------|------------------------|
18
+ | Individualidad | Singularidad auto-creada |
19
+ | Dualidad | Polaridad en disolución |
20
+ | Totalidad | Totalidad propia (sin contenedor exterior) |
21
+ | Evolución | Mictecacíhuatl — ascendente |
22
+ | Involución | Mictlantecuhtli — descendente |
23
+
24
+ ---
25
+
26
+ ## 2. Relaciones formales
27
+
28
+ Solo `mirrorOf` y `creates` (reglas canónicas). Resto → `none`.
29
+
30
+ Garantías: `lake build`, `scripts/validate_shacl.py`.
31
+ Detalle: [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md).
32
+
33
+ ---
34
+
35
+ ## 3. Protocolo de ingesta
36
+
37
+ 1. Identificar fenómeno.
38
+ 2. Asignar perspectiva (Ind / D / Tot).
39
+ 3. Fase/vector (adv–Evol o ret–Invol).
40
+ 4. Anclar a `mapped_node_id` de los 78.
41
+ 5. Evaluar arista (`mirrorOf` / `creates` / `none`).
42
+ 6. Validar con el script de ingesta.
43
+
44
+ ```bash
45
+ python scripts/importar_datos_personalizados.py \
46
+ --input datasets/ingestion/templates/<dominio>.csv \
47
+ --output datasets/ingestion/aligned/<dominio>_aligned.csv
48
+ ```
49
+
50
+ **No se exige** panel ciego para «aprobar» el mapeo.
51
+
52
+ ---
53
+
54
+ ## 4. Mictlán — destino, no ejemplo
55
+
56
+ Documento: [`DOMINIO_COSMOS_NAHUATL.md`](DOMINIO_COSMOS_NAHUATL.md).
57
+ Ensayo: [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md).
58
+
59
+ | Concepto | Perspectiva | Relación |
60
+ |----------|-------------|----------|
61
+ | Camino al Mictlán (tránsito) | Invol → autonomía | `creates` |
62
+ | Mictecacíhuatl ↔ Mictlantecuhtli | Evol / Invol | `mirrorOf` |
63
+ | Disolución observador → tejido | Individualidad → Totalidad | `creates` |
64
+ | Auto-creación desde el vacío | Individualidad / Totalidad | — |
65
+
66
+ EXP-E comprueba expresabilidad estructural; **no** es validación de campo ni κ de dominio.
67
+
68
+ ---
69
+
70
+ ## 5. Suite (relectura)
71
+
72
+ | ID | Rol |
73
+ |----|-----|
74
+ | EXP-B / EXP-C | Autonomía formal |
75
+ | EXP-E | Destino Mictlán expresable en 13 tríadas |
76
+ | EXP-D | Auto-generación |
77
+ | EXP-A | Residuo; no fundamento |
78
+
79
+ Pipeline: [`../EXPERIMENTOS.md`](../EXPERIMENTOS.md).
MANUAL_APRENDIZAJE_CONCORDANCIA.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Manual de aprendizaje: evaluación de concordancia semántica mediante pruebas a ciegas
2
+
3
+ > Segunda guía pedagógica: protocolo ciego, Fleiss' κ y valor didáctico del desacuerdo.
4
+ > Complementa: [`MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md`](MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md)
5
+
6
+ ---
7
+
8
+ ## 1. Validación semántica vs formal
9
+
10
+ | Tipo | Pregunta |
11
+ |---|---|
12
+ | Formal / sintética | ¿El sistema es coherente consigo mismo? |
13
+ | Semántica empírica | ¿Observadores independientes captan el mismo significado en el mundo real? |
14
+
15
+ ## 2. Protocolo ciego
16
+
17
+ - Anotación a ciegas (sin gramática interna del generador).
18
+ - Muestreo: reales, nuevos (NC), ambiguos (AM).
19
+ - Etiquetado: `mirrorOf`, `creates`, `none`, `unsure`.
20
+
21
+ ## 3. Fleiss' κ (EXP-A)
22
+
23
+ ```bash
24
+ python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json
25
+ ```
26
+
27
+ | Métrica | Valor |
28
+ |---|---:|
29
+ | κ | **0.6871** |
30
+ | Unánimes | 10/14 (71,4 %) |
31
+ | Desacuerdos | NC01, NC02, AM01, AM03 |
32
+
33
+ Demostración **provisional**.
34
+
35
+ ## 4. Desacuerdo como diagnóstico
36
+
37
+ - **NC:** neologismos → notas de alcance más estrictas.
38
+ - **AM:** solapamiento contextual → refinamiento de tríadas/fases.
39
+
40
+ ## 5. Capas A–E
41
+
42
+ Solo EXP-A y EXP-E demuestran legibilidad en la realidad. EXP-B/C/D aseguran salud técnica interna.
43
+
44
+ ## 6. Tres lecciones
45
+
46
+ 1. Ningún Lean, SHACL o PI-HGAT-T sustituye anotadores humanos ciegos.
47
+ 2. κ = 0.6871 aporta evidencia **provisional**.
48
+ 3. NC/AM localizan fricción del lenguaje natural a refinar.
MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Manual de aprendizaje: protocolo ciego (archivo residual)
2
+
3
+ > El marco I.O. **no** se evalúa como prueba de interpretabilidad en el mundo real por panel de anotadores.
4
+ > Ese modo de legitimación es el «mundo compartido» que el ensayo declara superable.
5
+ >
6
+ > [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md) · [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md)
7
+
8
+ ---
9
+
10
+ ## Objetivos de aprendizaje (históricos)
11
+
12
+ 1. Comprender Fleiss' κ como medida de acuerdo entre observadores separados.
13
+ 2. Distinguir **autonomía formal** (Lean/SHACL) del **residuo consensual** (EXP-A).
14
+ 3. No promover κ a fundamento del proyecto.
15
+
16
+ ---
17
+
18
+ ## Mensaje clave
19
+
20
+ | Capa | Rol |
21
+ |------|-----|
22
+ | Lean / SHACL | Autonomía formal (eje) |
23
+ | EXP-E Mictlán | Destino del carácter |
24
+ | EXP-A | Residuo; no prueba |
25
+
26
+ Detalle de ejecución opcional: [`MODULO_DIDACTICO_EVALUACION_CIEGA.md`](MODULO_DIDACTICO_EVALUACION_CIEGA.md).
MARCOI.O.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ARCHIVO — MARCOI.O.txt
2
+
3
+ **Estado:** borrador histórico. **No** es fuente normativa del marco.
4
+
5
+ Texto filosófico canónico:
6
+ docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md
7
+
8
+ El contenido íntegro de este borrador permanece en el historial de Git
9
+ (ruta anterior: `docs/MARCOI.O.txt`). Si alguna definición normativa no
10
+ está en el ensayo canónico, migrarla antes de purgar el historial.
11
+
12
+ ---
13
+ Cabecera original (referencia):
14
+ I.O.: La Dinámica Temporal del Vacío y la Unidad Informativa
15
+ Autor: Luis Rey García Figueroa — Octubre de 2026
MODULO_DIDACTICO_EVALUACION_CIEGA.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Módulo didáctico: residuo del protocolo ciego (EXP-A)
2
+
3
+ > **Estado:** material **pedagógico residual**. No certifica el marco.
4
+ > Bajo autonomía absoluta, el acuerdo inter-anotador **no** es fundamento de validez.
5
+ > [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md)
6
+
7
+ ---
8
+
9
+ ## 1. Qué era EXP-A
10
+
11
+ Protocolo ciego con 14 pares y tres anotadores. Fleiss' κ = 0.6871.
12
+
13
+ En una fase anterior del proyecto se presentaba como «validez semántica en el mundo real». Ese planteamiento **contradice** el ensayo canónico: el consenso de conciencias separadas no es fundamento último.
14
+
15
+ ---
16
+
17
+ ## 2. Lectura actual
18
+
19
+ | Antes | Ahora |
20
+ |-------|--------|
21
+ | EXP-A = prueba del marco | EXP-A = archivo de la fase consensual |
22
+ | κ legítima el sistema | κ no legítima el sistema |
23
+ | Mundo compartido como eje | Mundo compartido como residuo superable |
24
+
25
+ ---
26
+
27
+ ## 3. Si se ejecuta (opcional)
28
+
29
+ ```bash
30
+ python scripts/score_independent_eval.py \
31
+ --annotations datasets/independent_eval/annotations.json
32
+ ```
33
+
34
+ Interpretar resultados solo como documentación histórica, nunca como dictamen de validez del repositorio.
PREMISAS_Y_TEOREMAS.md ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Premisas asumidas y teoremas derivados del marco I.O.
2
+
3
+ Este documento separa **afirmaciones asumidas** (premisas del marco) de **resultados demostrados** en Lean o comprobados de forma determinista sobre la especificación estructurada. No confunde recuperación de reglas con validación empírica del marco sobre datos independientes.
4
+
5
+ ---
6
+
7
+ ## 1. Qué afirma el marco (núcleo conceptual)
8
+
9
+ ### 1.1 Vacío ($V$)
10
+
11
+ | Afirmación | Tipo |
12
+ |---|---|
13
+ | El vacío es la **ausencia de carga informativa** en un instante $t$: $V_t = (t, \emptyset)$. | **Premisa** (definición operativa) |
14
+ | El vacío no es aniquilación: es condición de posibilidad de nueva emergencia. | **Premisa** (interpretación ontológica) |
15
+ | Bajo los operadores formales, el vacío es **punto fijo estricto** de la composición $S_{\mathrm{rev}} \circ Ivo \circ E$. | **Teorema** (demostrado en Lean: `strict_fixed_point`) |
16
+ | $E(V_t)=V_{t+1}$, $S_{\mathrm{fwd}}(V_t)=V_t$, $Ivo(V_t)=V_{t-1}$, $S_{\mathrm{rev}}(V_t)=V_t$. | **Teoremas** (Lean: `E_vacuum`, `S_fwd_vacuum`, `Ivo_vacuum`, `S_rev_vacuum`) |
17
+
18
+ ### 1.2 Unidad informativa ($U$)
19
+
20
+ | Afirmación | Tipo |
21
+ |---|---|
22
+ | Un estado informativo es $s=(t,A)$ con $A$ lista finita de unidades (cadenas). | **Premisa** (definición en `State`) |
23
+ | La «unidad informativa» del marco es la carga mínima que puede ocupar un estado no vacío; no se identifica con un bit físico ni con una medida estadística empírica. | **Premisa** (alcance del modelo) |
24
+ | $E$ conserva la carga; $S_{\mathrm{fwd}}$ aplica deduplicación; $Ivo$ invierte la secuencia y retrocede el tiempo. | **Teoremas / definiciones** (Lean: `E_preserves_payload`, `S_fwd_applies_red`, `Ivo_applies_inversion`) |
25
+
26
+ ### 1.3 Infinito
27
+
28
+ | Afirmación | Tipo |
29
+ |---|---|
30
+ | El marco **reinterpreta** el infinito como **ausencia de información** (vacío), no como magnitud ilimitada ni sucesión interminable de registros. | **Premisa** (tesis filosófica del marco; no es teorema matemático sobre $\mathbb{R}$ o cardinales) |
31
+ | Esta reinterpretación es una **hipótesis de trabajo** del marco, no un resultado empírico ni un teorema de Lean. | **Premisa** |
32
+
33
+ ### 1.4 Transformación
34
+
35
+ | Afirmación | Tipo |
36
+ |---|---|
37
+ | La transformación sin repetición idéntica exige tránsito por vacío estructurado (supresión), no mera reescritura. | **Premisa** (motivación) |
38
+ | Para estados no vacíos, la composición $S_{\mathrm{rev}} \circ Ivo \circ E$ **no** restaura el estado original. | **Teorema** (Lean: `no_repetition`) |
39
+ | El ciclo evolutivo–involutivo reconfigura orientaciones; no es identidad trivial. | **Premisa** + corolario informal del teorema anterior |
40
+
41
+ ---
42
+
43
+ ## 2. Premisas estructurales (tablas y relaciones)
44
+
45
+ Estas premisas **no se demuestran**: se **asumen** como codificación operativa del marco y se **comprueban** de forma determinista (Lean + SHACL + CSV).
46
+
47
+ 1. Hay **cinco perspectivas**: Individualidad, Dualidad, Totalidad, Evolución, Involución.
48
+ 2. Hay **13 tríadas** por fase (avance/retroceso) con etiquetas canónicas en `data/iom_spec.json`.
49
+ 3. **Espejo (`mirrorOf`)**: misma tríada, fase opuesta, posición lateral invertida (`pos' = 2 - pos`), centro fijo.
50
+ 4. **Creación (`creates`)**: exactamente las cuatro reglas de `creation_rules` (lateral→centro o centro→laterales entre fases opuestas).
51
+ 5. **Vectores**: cuatro secuencias de cinco pasos con ejes y flechas declarados.
52
+
53
+ ---
54
+
55
+ ## 3. Teoremas derivados en Lean (operadores y posiciones)
56
+
57
+ Demostrados en `IOM/Core.lean`, `IOM/Operators.lean`, `IOM/Specification.lean`, `IOM/FormalRules.lean`:
58
+
59
+ | Teorema | Contenido |
60
+ |---|---|
61
+ | `strict_fixed_point` | $S_{\mathrm{rev}}(Ivo(E(V_t))) = V_t$ |
62
+ | `mirror_involutive` | Espejo de posición es involutivo |
63
+ | `mirror_index` | `mirror.pos.index = 2 - pos.index` |
64
+ | `isMirror` / `isCreates` | Predicados formales de aristas admisibles |
65
+ | `expected_partition` | 78 + 104 + 208 = 390 |
66
+ | `invert_involutive` | La inversión de carga es involutiva |
67
+ | `no_repetition` | Estados no vacíos no se restauran idénticos |
68
+
69
+ ---
70
+
71
+ ## 4. Qué **no** afirma el marco (límites)
72
+
73
+ - No afirma que las 13 tríadas describan datos del mundo natural medidos empíricamente.
74
+ - No afirma que accuracy 1.0 en PI-HGAT-T «valide el marco en el mundo real»: valida la **recuperabilidad de relaciones generadas por las reglas** bajo partición leave-one-triad-out.
75
+ - La reinterpretación del infinito como vacío es **premisa filosófica**, no teorema ni hallazgo experimental.
76
+ - La evaluación con anotadores humanos independientes (ciegos) es el canal legítimo para estudiar **validez semántica / interpretabilidad** de las relaciones en el mundo real; ver `datasets/independent_eval/`.
77
+
78
+ ---
79
+
80
+ ## 5. Correspondencia con artefactos
81
+
82
+ | Concepto | Artefacto |
83
+ |---|---|
84
+ | Premisas tabuladas | `data/iom_spec.json` |
85
+ | Teoremas de operadores | `IOM/Operators.lean` |
86
+ | Teoremas de posición / espejo / creates | `IOM/Specification.lean`, `IOM/FormalRules.lean` |
87
+ | Comprobación JSON ⇄ reglas | `tests/test_property_links.py`, `tests/test_formal_rules_bridge.py` |
88
+ | Validez semántica (mundo real) | `datasets/independent_eval/` |
89
+ | Recuperabilidad sintética | PI-HGAT-T, baselines |
PROTOCOLO_DE_MAPEO.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Protocolo de mapeo: alineación ontológica y validación ciega de dominios empíricos en el marco I.O.
2
+
3
+ > Protocolo estandarizado de ingesta, asignación a perspectivas/tríadas, instanciación de `mirrorOf`/`creates` y evaluación ciega.
4
+ > Evaluación independiente: [`datasets/independent_eval/`](../datasets/independent_eval/) · Pipeline: [`../REPRODUCCION.md`](../REPRODUCCION.md)
5
+
6
+ ---
7
+
8
+ ## 1. Marco fundamental y delimitación del protocolo I.O.
9
+
10
+ El establecimiento de un protocolo de mapeo riguroso resulta indispensable para formalizar el paso entre una estructura ontológica teórica y un instrumento de análisis interpretable, medible y operativo en el mundo real. Sin una metodología estandarizada de alineación, la arquitectura conceptual corre el riesgo de degradarse a un ejercicio autorreferencial de sintaxis formal.
11
+
12
+ ### 1.1 Propósito y alcance de la prueba de validez semántica
13
+
14
+ El propósito primario es evaluar la **validez semántica en el mundo real**: la capacidad del marco para permitir que observadores independientes —ajenos al diseño del sistema— etiqueten y clasifiquen conceptos externos, nuevos o ambiguos, sin recurrir a reglas deductivas autorreferenciales.
15
+
16
+ | Eje de evaluación | Mecanismo de respuesta en el repositorio |
17
+ |---|---|
18
+ | ¿Pueden anotadores independientes, ciegos a las reglas, etiquetar relaciones semánticas sobre pares reales/nuevos/ambiguos? | Protocolo ciego + Fleiss' κ en `datasets/independent_eval/` |
19
+ | ¿La estructura formal es internamente coherente? | Lean 4 + SHACL/OWL (condición necesaria; no prueba de validez en el mundo real) |
20
+ | ¿Las reglas sintéticas son recuperables por un modelo? | PI-HGAT-T y baselines en `experiments/` (diagnóstico sintético) |
21
+ | ¿Se puede alinear un dominio empírico a las 13 tríadas? | `docs/CATALOGO_DOMINIOS.md` e ingesta en `datasets/ingestion/` |
22
+
23
+ ### 1.2 Arquitectura sistémico-ontológica (perspectivas y tríadas)
24
+
25
+ | Perspectiva | Rol en el mapeo |
26
+ |---|---|
27
+ | **Individualidad** | Unidades discretas, entidades base, fronteras ontológicas primarias |
28
+ | **Dualidad** | Tensiones, polaridades, complementariedad entre pares |
29
+ | **Totalidad** | Integración sistémica, propiedades emergentes, cohesión holística |
30
+ | **Evolución** | Vectores de desarrollo, transformación ascendente, complejización |
31
+ | **Involución** | Retracción, simplificación, condensación, retorno a estados fundamentales |
32
+
33
+ Cada dominio empírico debe analizarse a través de estas cinco perspectivas y asignarse a las **13 tríadas** estructurales, evitando superposición u omisión de categorías.
34
+
35
+ ---
36
+
37
+ ## 2. Metodología de ingesta y mapeo de dominios empíricos externos
38
+
39
+ ### 2.1 Protocolo de carga y alineación sistemática
40
+
41
+ 1. Consultar fronteras en [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md).
42
+ 2. Seleccionar el dominio en [`CATALOGO_DOMINIOS.md`](CATALOGO_DOMINIOS.md).
43
+ 3. Descomponer entidades, estados y procesos por las cinco perspectivas.
44
+ 4. Asignar a las 13 tríadas y a la fase (`adv` / `ret`) correspondiente.
45
+ 5. Registrar en CSV de ingesta (`datasets/ingestion/`) y validar con `scripts/importar_datos_personalizados.py`.
46
+
47
+ ### 2.2 Relaciones operativas
48
+
49
+ Fundamento: [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md).
50
+
51
+ - **`mirrorOf`:** correspondencia estructural/funcional o simetría divalente; misma tríada, fase opuesta, posición lateral invertida.
52
+ - **`creates`:** emanación, producción o transformación activa; direccionalidad irreflexiva según las cuatro reglas de `creation_rules`.
53
+
54
+ ---
55
+
56
+ ## 3. Capas de verificación formal y validación estructural
57
+
58
+ La coherencia lógica interna es **condición indispensable** pero **no sustituye** la validez semántica en el mundo real.
59
+
60
+ ### 3.1 Lean 4
61
+
62
+ ```bash
63
+ lake build
64
+ ```
65
+
66
+ Verifica teoremas en `IOM/FormalRules.lean` (vacío, unidad, infinito, transformación; `isMirror` / `isCreates`). Véase [`PREMISAS_Y_TEOREMAS.md`](PREMISAS_Y_TEOREMAS.md).
67
+
68
+ ### 3.2 OWL / SHACL / CSV
69
+
70
+ ```bash
71
+ .venv/bin/python scripts/validate_spec.py
72
+ .venv/bin/python scripts/validate_shacl.py
73
+ ```
74
+
75
+ Criterios: sin violaciones SHACL; dominio/rango de `mirrorOf` y `creates`; conformidad CSV↔especificación; integridad de tipado de tríadas.
76
+
77
+ ---
78
+
79
+ ## 4. Protocolo de anotación ciega y evaluación inter-anotador
80
+
81
+ ### 4.1 Diseño experimental
82
+
83
+ Sobre `datasets/independent_eval/` ([`VALIDACION_INDEPENDIENTE.md`](VALIDACION_INDEPENDIENTE.md)):
84
+
85
+ 1. Muestra de 14 pares (reales, nuevos, ambiguos).
86
+ 2. Anotadores independientes sin acceso a reglas ni gold.
87
+ 3. Etiquetado semántico (`mirrorOf`, `creates`, `none`, `unsure`).
88
+ 4. Consolidación en `annotations.json`.
89
+
90
+ ### 4.2 Métricas actuales
91
+
92
+ ```bash
93
+ .venv/bin/python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json
94
+ ```
95
+
96
+ | Métrica | Valor | Lectura |
97
+ |---|---:|---|
98
+ | Fleiss' κ | **0.6871** | Acuerdo moderado-sustancial |
99
+ | Unánimes | 10/14 | Controles estructurales estables |
100
+ | Desacuerdos | 4/14 | NC01, NC02, AM01, AM03 |
101
+
102
+ Demostración **provisional** de interpretabilidad; no prueba universal del marco.
103
+
104
+ ### 4.3 Diagnóstico de desacuerdos
105
+
106
+ - **NC01, NC02 (conceptos nuevos):** dispersión al clasificar fenómenos sin contornos consolidados.
107
+ - **AM01, AM03 (ambiguos):** solapamiento entre especularidad y causalidad.
108
+
109
+ ---
110
+
111
+ ## 5. Pipeline de ejecución reproducible
112
+
113
+ ```bash
114
+ python3 -m venv .venv && .venv/bin/python -m pip install -r requirements-lock.txt
115
+ lake build
116
+ .venv/bin/python scripts/validate_spec.py
117
+ .venv/bin/python scripts/generate_ontology.py
118
+ .venv/bin/python -m unittest discover -s tests -v
119
+ .venv/bin/python scripts/validate_shacl.py
120
+ .venv/bin/python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json
121
+ .venv/bin/python experiments/pi_hgat_t.py
122
+ .venv/bin/python experiments/baselines.py
123
+ .venv/bin/python scripts/generate_audit_report.py
124
+ ```
125
+
126
+ ### Deslinde conceptual
127
+
128
+ | Capa | Afirmación legítima |
129
+ |---|---|
130
+ | Validez semántica (mundo real) | Interpretabilidad y acuerdo humano sobre conceptos externos |
131
+ | Formal | Consistencia lógica y teoremas en Lean 4 |
132
+ | Estructural | Conformidad SHACL/CSV con la especificación |
133
+ | Diagnóstico sintético | Recuperación de relaciones *generadas por reglas* (no validez semántica real) |
134
+
135
+ El marco I.O. no es un software aislado ni un conjunto de reglas sintéticas autorreferenciales: es un marco de alineación ontológica y una **prueba demostrativa** de mapeo semántico sobre el mundo real.
README.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Experimentos opcionales (diagnóstico / encuentro)
2
+
3
+ **No** forman parte del núcleo autónomo ni del CI bloqueante.
4
+
5
+ | Script | Rol | Salida |
6
+ |--------|-----|--------|
7
+ | `pi_hgat_t.py` | Diagnóstico circular (recupera reglas embebidas) | `experiments/results/` |
8
+ | `baselines.py` | Baselines sin grafo | `experiments/results/` |
9
+
10
+ ```bash
11
+ .venv/bin/python experiments/optional/pi_hgat_t.py
12
+ .venv/bin/python experiments/optional/baselines.py
13
+ ```
14
+
15
+ Workflow: `.github/workflows/encuentro.yml` (manual).
16
+ Tests: `tests/optional/` (no corren en CI core).
RELACIONES_OPERATIVAS.md ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Significado operativo de las relaciones `mirrorOf` y `creates`
2
+
3
+ Este documento fija la semántica operativa exacta de las dos relaciones estructurales del marco IOM. Las definiciones se alinean con:
4
+
5
+ - las reglas en `data/iom_spec.json` (`creation_rules`);
6
+ - los predicados implementados en `experiments/pi_hgat_t.py` (`admissible_relation`);
7
+ - los axiomas OWL y las formas SHACL en `ontology/`;
8
+ - los teoremas de posición en Lean (`IOM/Operators.lean`).
9
+
10
+ La validez de una arista se determina de forma operativa según las reglas deterministas (comprobables por SHACL, CSV y pruebas unitarias).
11
+
12
+ ---
13
+
14
+ ## 1. `io:mirrorOf`
15
+
16
+ ### Definición operativa
17
+
18
+ Una arista dirigida $A \xrightarrow{\text{mirrorOf}} B$ es válida **si y solo si** se cumplen simultáneamente:
19
+
20
+ 1. **Misma tríada**: `triad_index(A) = triad_index(B)`.
21
+ 2. **Fase opuesta**: `phase(A) ≠ phase(B)` (una es `adv`, la otra `ret`).
22
+ 3. **Posición reflejada**: `local_pos(B) = 2 - local_pos(A)`.
23
+ - position 0 ↔ position 2
24
+ - posición 1 (0) ↔ posición 1 (0)
25
+ 4. **Reciprocidad**: si $A \xrightarrow{\text{mirrorOf}} B$ entonces también $B \xrightarrow{\text{mirrorOf}} A$ (la propiedad OWL es simétrica).
26
+
27
+ ### Ejemplos positivos
28
+
29
+ | Fuente | Destino | Justificación |
30
+ |--------|---------|---------------|
31
+ | `T13_adv_P0` (animal) | `T13_ret_P2` (animal) | misma tríada 13, fases opuestas, 0 ↔ 2 |
32
+ | `T13_adv_P1` (humano) | `T13_ret_P1` (humano) | centro se refleja en centro |
33
+ | `T08_adv_P2` (emisor) | `T08_ret_P0` (emisor) | 2 ↔ 0 |
34
+
35
+ ### Ejemplos negativos
36
+
37
+ | Fuente | Destino | Motivo de rechazo |
38
+ |--------|---------|-------------------|
39
+ | `T13_adv_P0` | `T13_adv_P2` | misma fase |
40
+ | `T13_adv_P0` | `T13_ret_P0` | posición no reflejada (0 ≠ 2−0) |
41
+ | `T13_adv_P0` | `T01_ret_P2` | tríada distinta |
42
+ | `T13_adv_P0` | `T13_adv_P0` | reflexivo (excluido de candidatos) |
43
+
44
+ ### Casos límite
45
+
46
+ - **Centro–centro**: permitido y obligatorio para el nodo central de cada tríada.
47
+ - **Misma etiqueta léxica**: irrelevante; la relación es puramente estructural (fase + posición).
48
+ - **Arista unidireccional**: no puede existir; SHACL y el generador imponen el par recíproco.
49
+
50
+ ---
51
+
52
+ ## 2. `io:creates`
53
+
54
+ ### Definición operativa
55
+
56
+ Una arista dirigida $A \xrightarrow{\text{creates}} B$ es válida **si y solo si** se cumplen:
57
+
58
+ 1. **Misma tríada**.
59
+ 2. **Fase opuesta**.
60
+ 3. **Una de las cuatro reglas de `creation_rules`**:
61
+
62
+ | source_phase | source_positions | target_phase | target_positions |
63
+ |--------------|------------------|--------------|------------------|
64
+ | adv | {0, 2} | ret | {1} |
65
+ | adv | {1} | ret | {0, 2} |
66
+ | ret | {1} | adv | {0, 2} |
67
+ | ret | {0, 2} | adv | {1} |
68
+
69
+ En lenguaje natural: un lateral crea el centro de la fase opuesta, y el centro crea ambos laterales de la fase opuesta.
70
+
71
+ ### Ejemplos positivos
72
+
73
+ | Fuente | Destino | Regla aplicada |
74
+ |--------|---------|----------------|
75
+ | `T13_adv_P0` (animal) | `T13_ret_P1` (humano) | adv lateral → ret centro |
76
+ | `T13_adv_P1` (humano) | `T13_ret_P0` (IA) | adv centro → ret 0 |
77
+ | `T13_adv_P1` (humano) | `T13_ret_P2` (animal) | adv centro → ret 2 |
78
+ | `T13_ret_P1` (humano) | `T13_adv_P0` (animal) | ret centro → adv 0 |
79
+
80
+ ### Ejemplos negativos
81
+
82
+ | Fuente | Destino | Motivo |
83
+ |--------|---------|--------|
84
+ | `T13_adv_P0` | `T13_ret_P0` | lateral no crea lateral |
85
+ | `T13_adv_P0` | `T13_ret_P2` | lateral no crea el otro lateral |
86
+ | `T13_adv_P0` | `T13_adv_P1` | misma fase |
87
+ | `T13_adv_P1` | `T13_ret_P1` | centro no crea centro |
88
+
89
+ ### Casos límite
90
+
91
+ - **Múltiples targets**: el centro produce **dos** aristas `creates` (una hacia cada lateral).
92
+ - **No simétrica**: `creates` no es simétrica ni funcional; el grafo de creación es bipartito por fase.
93
+ - **Solapamiento con mirrorOf**: un par puede ser `mirrorOf` **o** `creates`, nunca ambas a la vez.
94
+ - **Ausencia de arista**: cualquier par que no satisfaga las reglas anteriores se etiqueta `none`.
95
+
96
+ ---
97
+
98
+ ## 3. Correspondencia con Lean y SHACL
99
+
100
+ | Concepto | Lean | SHACL / OWL |
101
+ |----------|------|-------------|
102
+ | Posición reflejada | teoremas de índice en `Operators.lean` | restricción `sh:equals` / cálculo `2 - pos` |
103
+ | Fase opuesta | predicados de fase | `sh:not` sobre el mismo valor de `hasPhase` |
104
+ | Reglas de creación | — (datos) | formas SHACL que enumeran las cuatro combinaciones |
105
+ | Simetría de mirrorOf | — | `owl:SymmetricProperty` |
106
+
107
+ Las pruebas en `tests/test_property_links.py` verifican que los CSV regenerados satisfacen exactamente estas reglas, cerrando el círculo JSON → CSV → ontología → Lean.
TRIADAS_CATEGORIALES.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tríadas categoriales del marco I.O.
2
+
3
+ **13 tríadas** × **2 fases** × **3 posiciones** = **78 nodos**
4
+ `spec_version` **1.9.0** · [`datasets/triad_nodes.csv`](../datasets/triad_nodes.csv) · [`data/iom_spec.json`](../data/iom_spec.json)
5
+
6
+ - Índice: **1 … 13** (`T01` … `T13`)
7
+ - Avance: **→ \| 0 \| →** · Retroceso: **← \| 0 \| ←**
8
+ - `position_index`: 0 = lateral →/← · 1 = centro · 2 = lateral →/←
9
+
10
+ Orden canónico: **#1** orientación\|cuántico\|dirección … **#13** animal\|humano\|IA.
11
+
12
+ ---
13
+
14
+ ## Fase de Avance (`adv` / evol)
15
+
16
+ ```
17
+ # | → | 0 | → |
18
+ 1 | orientación | cuántico | dirección |
19
+ 2 | hardware | virtual | software |
20
+ 3 | universo | espacio | vacío |
21
+ 4 | singularidad | tiempo | infinito |
22
+ 5 | cuerpo | consciente | mundo |
23
+ 6 | carácter | subconsciente | personalidad |
24
+ 7 | memoria | inconsciente | imaginación |
25
+ 8 | receptor | supraconsciente | emisor |
26
+ 9 | lógica | inteligencia | libertad |
27
+ 10 | muerte | artificial | vida |
28
+ 11 | descendente | mente | ascendente |
29
+ 12 | oscuridad | consciencia | luz |
30
+ 13 | animal | humano | IA |
31
+ # | ← | 0 | ← |
32
+ ```
33
+
34
+ | # | → | 0 | → | node_id |
35
+ |---|---|---|---|--------|
36
+ | 1 | orientación | cuántico | dirección | `T01_adv_*` |
37
+ | 2 | hardware | virtual | software | `T02_adv_*` |
38
+ | 3 | universo | espacio | vacío | `T03_adv_*` |
39
+ | 4 | singularidad | tiempo | infinito | `T04_adv_*` |
40
+ | 5 | cuerpo | consciente | mundo | `T05_adv_*` |
41
+ | 6 | carácter | subconsciente | personalidad | `T06_adv_*` |
42
+ | 7 | memoria | inconsciente | imaginación | `T07_adv_*` |
43
+ | 8 | receptor | supraconsciente | emisor | `T08_adv_*` |
44
+ | 9 | lógica | inteligencia | libertad | `T09_adv_*` |
45
+ | 10 | muerte | artificial | vida | `T10_adv_*` |
46
+ | 11 | descendente | mente | ascendente | `T11_adv_*` |
47
+ | 12 | oscuridad | consciencia | luz | `T12_adv_*` |
48
+ | 13 | animal | humano | IA | `T13_adv_*` |
49
+
50
+ ---
51
+
52
+ ## Fase de Retroceso (`ret` / invol)
53
+
54
+ ```
55
+ # | → | 0 | → |
56
+ 1 | dirección | cuántico | orientación |
57
+ 2 | software | virtual | hardware |
58
+ 3 | vacío | espacio | universo |
59
+ 4 | infinito | tiempo | singularidad |
60
+ 5 | mundo | consciente | cuerpo |
61
+ 6 | personalidad | subconsciente | carácter |
62
+ 7 | imaginación | inconsciente | memoria |
63
+ 8 | emisor | supraconsciente | receptor |
64
+ 9 | libertad | inteligencia | lógica |
65
+ 10 | vida | artificial | muerte |
66
+ 11 | ascendente | mente | descendente |
67
+ 12 | luz | consciencia | oscuridad |
68
+ 13 | IA | humano | animal |
69
+ # | ← | 0 | ← |
70
+ ```
71
+
72
+ | # | ← | 0 | ← | node_id |
73
+ |---|---|---|---|--------|
74
+ | 1 | dirección | cuántico | orientación | `T01_ret_*` |
75
+ | 2 | software | virtual | hardware | `T02_ret_*` |
76
+ | 3 | vacío | espacio | universo | `T03_ret_*` |
77
+ | 4 | infinito | tiempo | singularidad | `T04_ret_*` |
78
+ | 5 | mundo | consciente | cuerpo | `T05_ret_*` |
79
+ | 6 | personalidad | subconsciente | carácter | `T06_ret_*` |
80
+ | 7 | imaginación | inconsciente | memoria | `T07_ret_*` |
81
+ | 8 | emisor | supraconsciente | receptor | `T08_ret_*` |
82
+ | 9 | libertad | inteligencia | lógica | `T09_ret_*` |
83
+ | 10 | vida | artificial | muerte | `T10_ret_*` |
84
+ | 11 | ascendente | mente | descendente | `T11_ret_*` |
85
+ | 12 | luz | consciencia | oscuridad | `T12_ret_*` |
86
+ | 13 | IA | humano | animal | `T13_ret_*` |
87
+
88
+ ---
89
+
90
+ ## Espejo y creación
91
+
92
+ | Relación | Condición |
93
+ |----------|-----------|
94
+ | `mirrorOf` | Fases opuestas + `position_index_tgt = 2 − position_index_src` |
95
+ | `creates` | Cuatro reglas lateral↔centro entre fases |
96
+ | `none` | Resto |
97
+
98
+ Ejemplo: tríada **13** avance (animal \| humano \| IA) ↔ retroceso (IA \| humano \| animal).
99
+ Ejemplo: tríada **1** avance (orientación \| cuántico \| dirección) ↔ retroceso (dirección \| cuántico \| orientación).
100
+
101
+ Detalle: [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md).
VALIDACION_INDEPENDIENTE.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Autonomía formal y capas de verificación (no «validez por consenso»)
2
+
3
+ Este documento **no** define el repositorio como prueba de validez semántica en un mundo compartido por conciencias separadas. Ese modo de legitimación es exactamente el que el ensayo canónico declara **superable**.
4
+
5
+ Carácter: [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md) · Ensayo: [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md)
6
+
7
+ ---
8
+
9
+ ## Principio rector
10
+
11
+ > El marco se sostiene por **auto-coherencia** (bóveda Lean / SHACL / 78 nodos), no por el acuerdo de observadores externos.
12
+ > Un panel de anotadores separados reproduce el «mundo real» provisional del ensayo; **no** lo fundamenta.
13
+
14
+ | Fuente | Rol bajo autonomía absoluta |
15
+ |--------|-----------------------------|
16
+ | `data/iom_spec.json` + CSV + ontología | **Arquitectura autónoma** bajo prueba de coherencia interna |
17
+ | Lean / SHACL | **Autonomía formal** — no pide permiso a un consenso exterior |
18
+ | PI-HGAT-T / baselines | Auto-recuperabilidad de reglas *del propio sistema* |
19
+ | `datasets/independent_eval/` | **Residuo** de la fase de conciencias separadas (documentado, no fundante) |
20
+ | Cartografía de dominios | Ejercicio del tránsito; no certificado de «mundo real» |
21
+
22
+ ---
23
+
24
+ ## Qué se establece y qué no
25
+
26
+ | Se establece | No se establece |
27
+ |--------------|-----------------|
28
+ | Coherencia deductiva y de forma del sistema de 13 tríadas | Que el marco «describe la realidad» por acuerdo inter-subjetivo |
29
+ | Que las reglas son recuperables desde sí mismas (diagnóstico interno) | Que κ ≈ 0.69 **funda** la validez del proyecto |
30
+ | Que el sendero Mictlán / autonomía es cartografiable en el vocabulario formal | Cobertura empírica de todos los dominios por paneles externos |
31
+ | Que el requisito del sistema puede ser la abolición de requisitos impuestos | Verdad ontológica universal por consenso |
32
+
33
+ ---
34
+
35
+ ## Jerarquía de afirmaciones (reordenada)
36
+
37
+ | Prioridad | Afirmación legítima | Artefacto |
38
+ |:---------:|---------------------|-----------|
39
+ | **1** | Autonomía formal (coherencia sin contenedor exterior) | Lean, SHACL, CSV, `iom_spec.json` |
40
+ | **2** | Cartografía del tránsito (Mictlán / autonomía) | EXP-E, dominio cosmológico, ensayo |
41
+ | **3** | Auto-generación recuperable de reglas | PI-HGAT-T, baselines |
42
+ | **4** | Residuo documentado del mundo compartido | `independent_eval`, κ (opcional) |
43
+
44
+ La prioridad 4 **no** se promociona a «prueba de validez del marco».
45
+
46
+ ---
47
+
48
+ ## Sobre el protocolo ciego (EXP-A)
49
+
50
+ El protocolo y las anotaciones se **conservan como archivo** de una fase en la que el proyecto aún hablaba el lenguaje del consenso inter-anotador. Bajo el carácter actual:
51
+
52
+ - κ no es el eje del repositorio.
53
+ - No se reclama «validez semántica en el mundo real» a partir de ellos.
54
+ - Quien los ejecute lo hace como **ejercicio histórico / comparado**, no como ceremonia de legitimación.
55
+
56
+ ---
57
+
58
+ ## Pipeline prioritario
59
+
60
+ ```bash
61
+ # 1) Autonomía formal (eje)
62
+ lake build
63
+ python scripts/validate_spec.py
64
+ python scripts/generate_ontology.py
65
+ python -m unittest discover -s tests -v
66
+ python scripts/validate_shacl.py
67
+
68
+ # 2) Cartografía del tránsito
69
+ python experiments/domain_mapping/validate_examples.py
70
+
71
+ # 3) Diagnóstico de auto-generación (opcional)
72
+ python experiments/pi_hgat_t.py
73
+ python experiments/baselines.py
74
+ python scripts/audit_perfect_metrics.py
75
+
76
+ # 4) Residuo del mundo compartido (opcional, no fundante)
77
+ python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json
78
+ ```
79
+
80
+ ---
81
+
82
+ ## Referencias
83
+
84
+ - Delimitación: [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md)
85
+ - Carácter: [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md)
86
+ - Ensayo: [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md)
VECTORES_4_5.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Las cinco perspectivas del marco I.O.
2
+
3
+ El marco I.O. se articula mediante **cinco perspectivas complementarias**:
4
+
5
+ | # | Id | Perspectiva | Rol |
6
+ |---|-----|-------------|-----|
7
+ | 1 | `Ind` | **Individualidad** | Posicional (→ / lateral 0): unidad / singularidad |
8
+ | 2 | `D` | **Dualidad** | Posicional (0): relación / diferencia |
9
+ | 3 | `Tot` | **Totalidad** | Posicional (→ / lateral 2): integración / sistema |
10
+ | 4 | `Evol` | **Evolución** | Vectorial: flujo del vacío hacia la estructura |
11
+ | 5 | `Invol` | **Involución** | Vectorial: flujo de la estructura hacia el vacío |
12
+
13
+ Las tres primeras (Individualidad, Dualidad, Totalidad) describen los *modos de actualización* y se representan como metadatos de posición en cada tríada (→ | 0 | → en avance; ← | 0 | ← en retroceso). Las perspectivas cuarta y quinta (Evolución e Involución) describen las *direcciones de flujo informativo* y se materializan como secuencias vectoriales de cinco pasos.
14
+
15
+ Fuente estructurada: [`data/iom_spec.json`](../data/iom_spec.json) (`five_perspectives`, `vectors`).
16
+
17
+ ## Cuarta perspectiva — Evolución
18
+
19
+ ```
20
+ invol | ind | dua | tot | evol
21
+ 0 | 1 | 2 | 3 | 4
22
+ | → | → | → | →
23
+ ---------------------
24
+ ← | ← | ← | ← |
25
+ 4 | 3 | 2 | 1 | 0
26
+ evol | tot | dua | ind | invol
27
+ ```
28
+
29
+ | Fase | Etiquetas en orden de eje | Posiciones del eje | Flecha |
30
+ |---|---|---|---|
31
+ | Avance | `invol · ind · dua · tot · evol` | `0 · 1 · 2 · 3 · 4` | → |
32
+ | Retroceso | `evol · tot · dua · ind · invol` | `4 · 3 · 2 · 1 · 0` | ← |
33
+
34
+ ## Quinta perspectiva — Involución
35
+
36
+ ```
37
+ invol | tot | dua | ind | evol
38
+ 4 | 3 | 2 | 1 | 0
39
+ → | → | → | → |
40
+ ---------------------
41
+ | ← | ← | ← | ←
42
+ 0 | 1 | 2 | 3 | 4
43
+ evol | ind | dua | tot | invol
44
+ ```
45
+
46
+ | Fase | Etiquetas en orden de eje | Posiciones del eje | Flecha |
47
+ |---|---|---|---|
48
+ | Avance | `invol · tot · dua · ind · evol` | `4 · 3 · 2 · 1 · 0` | → |
49
+ | Retroceso | `evol · ind · dua · tot · invol` | `0 · 1 · 2 · 3 · 4` | ← |
50
+
51
+ ## Representación formal
52
+
53
+ Cada fila se materializa como cinco instancias `io:VectorStep`. Cada instancia conserva el vector (`Evol` / `Invol`), fase, posición del eje, índice visual, etiqueta y flecha. En conjunto son **20 pasos vectoriales**.
54
+
55
+ En la ontología, las cinco perspectivas son individuos de `io:Perspective` con etiquetas en español: Individualidad, Dualidad, Totalidad, Evolución e Involución.
56
+
57
+ `spec_version` ≥ **1.5.0**.
__init__.py ADDED
File without changes
audit_perfect_metrics.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Auditoría rigurosa de las métricas perfectas (100%).
3
+
4
+ Investiga por qué PI-HGAT-T y el MLP alcanzan accuracy/F1 = 1.0:
5
+
6
+ 1. Independencia train/test bajo leave-one-triad-out (sí: ninguna pareja
7
+ de la tríada held-out aparece en entrenamiento).
8
+ 2. Sin embargo, las etiquetas están **completamente determinadas** por
9
+ (fase, posición) del par — reglas idénticas en las 13 tríadas.
10
+ 3. Por tanto, cualquier modelo que aprenda la función determinista
11
+ (fase_src, pos_src, fase_tgt, pos_tgt) → {none, mirrorOf, creates}
12
+ generaliza al 100% a tríadas no vistas.
13
+ 4. El oracle de reglas deterministas y el MLP (features = one-hot fase+pos)
14
+ alcanzan 1.0; la regresión logística lineal no separa mirrorOf/creates.
15
+
16
+ Este script demuestra (1)–(3) de forma programática y escribe un informe JSON.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import csv
21
+ import json
22
+ from collections import defaultdict
23
+ from pathlib import Path
24
+
25
+ ROOT = Path(__file__).resolve().parents[1]
26
+ CLASSES = ("none", "mirrorOf", "creates")
27
+
28
+
29
+ def parse_node(node_id: str) -> tuple[str, int]:
30
+ parts = node_id.split("_")
31
+ return parts[1], int(parts[2][1:])
32
+
33
+
34
+ def feature_key(src: str, tgt: str) -> tuple:
35
+ """Clave de features usada por los modelos (fase+posición, sin tríada ni etiqueta)."""
36
+ sp, spos = parse_node(src)
37
+ tp, tpos = parse_node(tgt)
38
+ return (sp, spos, tp, tpos)
39
+
40
+
41
+ def deterministic_label(src: str, tgt: str) -> str:
42
+ """Regla determinista alineada con SHACL / FormalRules.lean."""
43
+ sp, spos = parse_node(src)
44
+ tp, tpos = parse_node(tgt)
45
+ if sp == tp:
46
+ return "none"
47
+ if tpos == 2 - spos:
48
+ return "mirrorOf"
49
+ lateral_s = spos in (0, 2)
50
+ lateral_t = tpos in (0, 2)
51
+ if (lateral_s and tpos == 1) or (spos == 1 and lateral_t):
52
+ return "creates"
53
+ return "none"
54
+
55
+
56
+ def main() -> int:
57
+ rows = []
58
+ with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as fh:
59
+ rows = list(csv.DictReader(fh))
60
+
61
+ # 1. Consistencia gold vs regla determinista
62
+ mismatches = []
63
+ for row in rows:
64
+ pred = deterministic_label(row["source"], row["target"])
65
+ if pred != row["relation"]:
66
+ mismatches.append({"row": row, "rule_predicts": pred})
67
+
68
+ # 2. La etiqueta es función solo de (fase, pos) — misma clave → misma etiqueta
69
+ by_feature: dict[tuple, set[str]] = defaultdict(set)
70
+ by_feature_triads: dict[tuple, set[int]] = defaultdict(set)
71
+ for row in rows:
72
+ key = feature_key(row["source"], row["target"])
73
+ by_feature[key].add(row["relation"])
74
+ by_feature_triads[key].add(int(row["triad_index"]))
75
+
76
+ non_deterministic_features = {
77
+ str(k): list(v) for k, v in by_feature.items() if len(v) > 1
78
+ }
79
+
80
+ # 3. Leave-one-triad-out: ¿las features del held-out aparecen en train?
81
+ # Sí, con la misma etiqueta — por eso un learner que memoriza la
82
+ # función feature→label generaliza al 100%.
83
+ triad_feature_overlap = {}
84
+ for held in range(1, 14):
85
+ train_map = {}
86
+ test_keys = set()
87
+ for row in rows:
88
+ key = feature_key(row["source"], row["target"])
89
+ tid = int(row["triad_index"])
90
+ if tid == held:
91
+ test_keys.add((key, row["relation"]))
92
+ else:
93
+ train_map[key] = row["relation"]
94
+ recoverable = sum(1 for k, lab in test_keys if train_map.get(k) == lab)
95
+ triad_feature_overlap[held] = {
96
+ "test_pairs": len(test_keys),
97
+ "recoverable_by_feature_lookup": recoverable,
98
+ "fraction": recoverable / len(test_keys) if test_keys else 0.0,
99
+ }
100
+
101
+ all_recoverable = all(
102
+ v["fraction"] == 1.0 for v in triad_feature_overlap.values()
103
+ )
104
+
105
+ # 4. Conteos
106
+ from collections import Counter
107
+ counts = Counter(r["relation"] for r in rows)
108
+
109
+ report = {
110
+ "conclusion": (
111
+ "Las métricas perfectas (100%) de PI-HGAT-T y del MLP no indican "
112
+ "sobreajuste por fuga de identidad de tríada: leave-one-triad-out "
113
+ "excluye correctamente las parejas del held-out. Indican que las "
114
+ "etiquetas son una función determinista de (fase, posición) del par, "
115
+ "idéntica en las 13 tríadas. Aprender esa función basta para "
116
+ "generalizar al 100%. El oracle de reglas deterministas alcanza 1.0 "
117
+ "sin aprendizaje. La arquitectura de grafo no es necesaria para este "
118
+ "corpus sintético; sirve como demostración de recuperabilidad estructural."
119
+ ),
120
+ "gold_vs_deterministic_rule": {
121
+ "mismatches": len(mismatches),
122
+ "details": mismatches[:5], # muestra
123
+ "perfect_match": len(mismatches) == 0,
124
+ },
125
+ "label_determined_by_phase_position_only": {
126
+ "unique_feature_keys": len(by_feature),
127
+ "keys_with_ambiguous_labels": non_deterministic_features,
128
+ "is_deterministic_function": len(non_deterministic_features) == 0,
129
+ },
130
+ "leave_one_triad_out_feature_overlap": {
131
+ "per_fold": triad_feature_overlap,
132
+ "all_folds_100pct_recoverable_by_feature_lookup": all_recoverable,
133
+ "interpretation": (
134
+ "En cada fold, el 100% de los pares de prueba tiene una clave "
135
+ "(fase,pos) ya vista en entrenamiento con la misma etiqueta. "
136
+ "No hay fuga de node_id/triad_index (el modelo no los usa), "
137
+ "pero la función a aprender es trivialmente compartida."
138
+ ),
139
+ },
140
+ "class_counts": dict(counts),
141
+ "implications": [
142
+ "No se requiere arquitectura compleja (GAT) para este corpus: el MLP y el oracle bastan.",
143
+ "Las ablaciones sin fase/posición degradan el rendimiento porque rompen la función determinista.",
144
+ "La validación empírica real del marco exige datos cuyas etiquetas NO se deriven de las mismas reglas (véase datasets/independent_eval/ y external_eval/).",
145
+ "Reportar 100% como 'recuperación de relaciones generadas por reglas' es correcto; reportarlo como 'validación del marco en el mundo real' no lo es.",
146
+ ],
147
+ }
148
+
149
+ out = ROOT / "experiments" / "results" / "perfect_metrics_audit.json"
150
+ out.parent.mkdir(parents=True, exist_ok=True)
151
+ out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
152
+
153
+ print("Auditoría de métricas perfectas")
154
+ print(f" Gold vs regla determinista: mismatches={len(mismatches)}")
155
+ print(f" Función determinista fase+pos: {len(non_deterministic_features) == 0}")
156
+ print(f" LOO recoverable por lookup de features: {all_recoverable}")
157
+ print(f" Informe: {out}")
158
+ print()
159
+ print(report["conclusion"])
160
+ return 0 if len(mismatches) == 0 and all_recoverable else 1
161
+
162
+
163
+ if __name__ == "__main__":
164
+ raise SystemExit(main())
baselines.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Clasificadores base para comparar con PI-HGAT-T.
3
+
4
+ Incluye:
5
+ - reglas deterministas (oracle de la especificación)
6
+ - regresión logística sobre features one-hot de fase+posición
7
+ - MLP sin estructura de grafo
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import csv
12
+ import json
13
+ import random
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import torch
18
+ from torch import nn
19
+ from torch.nn import functional as F
20
+
21
+ ROOT = Path(__file__).resolve().parents[2]
22
+ CLASSES = ("none", "mirrorOf", "creates")
23
+ CLASS_ID = {n: i for i, n in enumerate(CLASSES)}
24
+
25
+
26
+ def seed_everything(seed: int = 20261008) -> None:
27
+ random.seed(seed)
28
+ np.random.seed(seed)
29
+ torch.manual_seed(seed)
30
+ torch.use_deterministic_algorithms(True)
31
+ torch.set_num_threads(1)
32
+
33
+
34
+ def features_for_node(node_id: str) -> list[float]:
35
+ parts = node_id.split("_")
36
+ phase, position = parts[1], int(parts[2][1:])
37
+ return [float(phase == "adv"), float(phase == "ret"),
38
+ float(position == 0), float(position == 1), float(position == 2)]
39
+
40
+
41
+ def parse_pair_index(node_id: str) -> int:
42
+ phase = node_id.split("_")[1]
43
+ position = int(node_id.split("_")[2][1:])
44
+ return position if phase == "adv" else 3 + position
45
+
46
+
47
+ def read_pairs():
48
+ pairs: dict[int, list[tuple[str, str, int]]] = {i: [] for i in range(1, 14)}
49
+ with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as fh:
50
+ for row in csv.DictReader(fh):
51
+ pairs[int(row["triad_index"])].append(
52
+ (row["source"], row["target"], CLASS_ID[row["relation"]])
53
+ )
54
+ return pairs
55
+
56
+
57
+ def admissible(label: str, source: int, target: int) -> bool:
58
+ source_phase, source_pos = (0 if source < 3 else 1), source % 3
59
+ target_phase, target_pos = (0 if target < 3 else 1), target % 3
60
+ if source_phase == target_phase:
61
+ return False
62
+ if label == "mirrorOf":
63
+ return target_pos == 2 - source_pos
64
+ if label == "creates":
65
+ return (source_pos in (0, 2) and target_pos == 1) or (source_pos == 1 and target_pos in (0, 2))
66
+ return True
67
+
68
+
69
+ def deterministic_rule_predict(src_idx: int, tgt_idx: int) -> int:
70
+ if admissible("mirrorOf", src_idx, tgt_idx):
71
+ return CLASS_ID["mirrorOf"]
72
+ if admissible("creates", src_idx, tgt_idx):
73
+ return CLASS_ID["creates"]
74
+ return CLASS_ID["none"]
75
+
76
+
77
+ def pair_feature(src_id: str, tgt_id: str) -> list[float]:
78
+ return features_for_node(src_id) + features_for_node(tgt_id)
79
+
80
+
81
+ def scores(gold: list[int], pred: list[int]) -> dict:
82
+ matrix = [[0] * 3 for _ in range(3)]
83
+ for a, b in zip(gold, pred):
84
+ matrix[a][b] += 1
85
+ per_class = {}
86
+ f1s = []
87
+ for i, name in enumerate(CLASSES):
88
+ tp = matrix[i][i]
89
+ fp = sum(matrix[r][i] for r in range(3) if r != i)
90
+ fn = sum(matrix[i][c] for c in range(3) if c != i)
91
+ prec = tp / (tp + fp) if tp + fp else 0.0
92
+ rec = tp / (tp + fn) if tp + fn else 0.0
93
+ f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
94
+ per_class[name] = {"precision": prec, "recall": rec, "f1": f1, "support": tp + fn}
95
+ f1s.append(f1)
96
+ acc = sum(a == b for a, b in zip(gold, pred)) / max(len(gold), 1)
97
+ return {
98
+ "accuracy": round(acc, 6),
99
+ "macro_f1": round(sum(f1s) / 3, 6),
100
+ "per_class": per_class,
101
+ "confusion_matrix": matrix,
102
+ }
103
+
104
+
105
+ class SoftmaxRegression(nn.Module):
106
+ def __init__(self, in_dim: int, n_classes: int = 3):
107
+ super().__init__()
108
+ self.linear = nn.Linear(in_dim, n_classes)
109
+
110
+ def forward(self, x):
111
+ return self.linear(x)
112
+
113
+
114
+ class SimpleMLP(nn.Module):
115
+ def __init__(self, in_dim: int, hidden: int = 32, n_classes: int = 3):
116
+ super().__init__()
117
+ self.net = nn.Sequential(
118
+ nn.Linear(in_dim, hidden),
119
+ nn.GELU(),
120
+ nn.Linear(hidden, hidden),
121
+ nn.GELU(),
122
+ nn.Linear(hidden, n_classes),
123
+ )
124
+
125
+ def forward(self, x):
126
+ return self.net(x)
127
+
128
+
129
+ def train_sklearn_like(model: nn.Module, X: torch.Tensor, y: torch.Tensor,
130
+ epochs: int = 200, lr: float = 0.01) -> None:
131
+ opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4)
132
+ for _ in range(epochs):
133
+ opt.zero_grad()
134
+ logits = model(X)
135
+ loss = F.cross_entropy(logits, y)
136
+ loss.backward()
137
+ opt.step()
138
+
139
+
140
+ def leave_one_triad_out(pairs: dict, model_factory, epochs: int = 200) -> dict:
141
+ all_gold, all_pred = [], []
142
+ fold_accs = []
143
+ for held in sorted(pairs):
144
+ seed_everything(20261008 + held - 1)
145
+ train_X, train_y = [], []
146
+ test_X, test_y, test_meta = [], [], []
147
+ for tid, plist in pairs.items():
148
+ for src, tgt, label in plist:
149
+ feat = pair_feature(src, tgt)
150
+ if tid == held:
151
+ test_X.append(feat)
152
+ test_y.append(label)
153
+ test_meta.append((src, tgt))
154
+ else:
155
+ train_X.append(feat)
156
+ train_y.append(label)
157
+ Xtr = torch.tensor(train_X, dtype=torch.float32)
158
+ ytr = torch.tensor(train_y, dtype=torch.long)
159
+ Xte = torch.tensor(test_X, dtype=torch.float32)
160
+ model = model_factory(Xtr.shape[1])
161
+ train_sklearn_like(model, Xtr, ytr, epochs=epochs)
162
+ with torch.no_grad():
163
+ pred = model(Xte).argmax(dim=-1).tolist()
164
+ all_gold.extend(test_y)
165
+ all_pred.extend(pred)
166
+ fold_accs.append(sum(a == b for a, b in zip(test_y, pred)) / max(len(test_y), 1))
167
+ result = scores(all_gold, all_pred)
168
+ result["fold_accuracies"] = fold_accs
169
+ result["fold_accuracy_mean"] = round(float(np.mean(fold_accs)), 6)
170
+ result["fold_accuracy_std"] = round(float(np.std(fold_accs)), 6)
171
+ return result
172
+
173
+
174
+ def run_deterministic(pairs: dict) -> dict:
175
+ gold, pred = [], []
176
+ for plist in pairs.values():
177
+ for src, tgt, label in plist:
178
+ gold.append(label)
179
+ s_idx = parse_pair_index(src)
180
+ t_idx = parse_pair_index(tgt)
181
+ pred.append(deterministic_rule_predict(s_idx, t_idx))
182
+ return scores(gold, pred)
183
+
184
+
185
+ def run() -> dict:
186
+ seed_everything()
187
+ pairs = read_pairs()
188
+ report = {
189
+ "description": "Comparación de PI-HGAT-T con clasificadores base sobre el mismo leave-one-triad-out",
190
+ "baselines": {},
191
+ }
192
+ report["baselines"]["deterministic_rules"] = {
193
+ "description": "Oracle que aplica exactamente las reglas SHACL de mirrorOf/creates",
194
+ "metrics": run_deterministic(pairs),
195
+ }
196
+ report["baselines"]["logistic_regression"] = {
197
+ "description": "Softmax linear sobre concatenación de one-hot fase+posición (10 dim)",
198
+ "metrics": leave_one_triad_out(pairs, lambda d: SoftmaxRegression(d), epochs=300),
199
+ }
200
+ report["baselines"]["mlp_no_graph"] = {
201
+ "description": "MLP de dos capas ocultas sin mensaje-passing ni atención",
202
+ "metrics": leave_one_triad_out(pairs, lambda d: SimpleMLP(d, hidden=32), epochs=200),
203
+ }
204
+ out = ROOT / "experiments" / "results" / "baselines_comparison.json"
205
+ out.parent.mkdir(parents=True, exist_ok=True)
206
+ out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
207
+ print("Baselines escritos en", out)
208
+ for name, block in report["baselines"].items():
209
+ m = block["metrics"]
210
+ print(f" {name}: accuracy={m['accuracy']:.4f} macro_f1={m['macro_f1']:.4f}")
211
+ return report
212
+
213
+
214
+ if __name__ == "__main__":
215
+ run()
capture_environment.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Captura versiones del entorno de reproducción en un artefacto JSON."""
3
+ from __future__ import annotations
4
+ import importlib.metadata
5
+ import json
6
+ import platform
7
+ import subprocess
8
+ from pathlib import Path
9
+
10
+ ROOT = Path(__file__).resolve().parents[1]
11
+
12
+ def command_version(command: list[str]) -> str | None:
13
+ try:
14
+ result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=20)
15
+ return (result.stdout or result.stderr).strip().splitlines()[0]
16
+ except (OSError, subprocess.SubprocessError):
17
+ return None
18
+
19
+ def main() -> None:
20
+ packages = {}
21
+ for name in ("rdflib", "pyshacl", "owlrl", "numpy", "torch"):
22
+ try:
23
+ packages[name] = importlib.metadata.version(name)
24
+ except importlib.metadata.PackageNotFoundError:
25
+ packages[name] = None
26
+ data = {
27
+ "python": platform.python_version(),
28
+ "implementation": platform.python_implementation(),
29
+ "platform": platform.platform(),
30
+ "packages": packages,
31
+ "lean_toolchain_file": (ROOT / "lean-toolchain").read_text(encoding="utf-8").strip(),
32
+ "lean_version": command_version(["lean", "--version"]),
33
+ "lake_version": command_version(["lake", "--version"]),
34
+ "requirements": (ROOT / "requirements.txt").read_text(encoding="utf-8").splitlines(),
35
+ }
36
+ out = ROOT / "experiments" / "results" / "software_versions.json"
37
+ out.parent.mkdir(parents=True, exist_ok=True)
38
+ out.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
39
+ print(out)
40
+ print(json.dumps(data, ensure_ascii=False, indent=2))
41
+
42
+ if __name__ == "__main__":
43
+ main()
check_generated_committed.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Comprueba que los CSV versionados coinciden con generate_ontology.py.
3
+
4
+ Solo se exige igualdad exacta de:
5
+
6
+ - datasets/triad_nodes.csv
7
+ - datasets/vector_steps.csv
8
+ - datasets/relation_candidates.csv
9
+ - datasets/GENERATED_FROM.json (spec_version del generador)
10
+
11
+ El TTL no se compara byte-a-byte (serialización rdflib).
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import subprocess
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ ROOT = Path(__file__).resolve().parents[1]
21
+
22
+ GENERATED_CSV = [
23
+ "datasets/triad_nodes.csv",
24
+ "datasets/vector_steps.csv",
25
+ "datasets/relation_candidates.csv",
26
+ "datasets/GENERATED_FROM.json",
27
+ ]
28
+
29
+
30
+ def run(cmd: list[str]) -> subprocess.CompletedProcess:
31
+ return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True)
32
+
33
+
34
+ def main() -> int:
35
+ parser = argparse.ArgumentParser()
36
+ parser.add_argument("--with-manifest", action="store_true")
37
+ parser.add_argument("--skip-generate", action="store_true")
38
+ parser.add_argument("--include-ttl", action="store_true")
39
+ args = parser.parse_args()
40
+
41
+ if not args.skip_generate:
42
+ print(">>> generate_ontology.py")
43
+ r = run([sys.executable, "scripts/generate_ontology.py"])
44
+ print(r.stdout, end="")
45
+ if r.returncode != 0:
46
+ print(r.stderr, file=sys.stderr)
47
+ return 1
48
+
49
+ paths = list(GENERATED_CSV)
50
+ if args.include_ttl:
51
+ paths.insert(0, "ontology/io_ontology.ttl")
52
+
53
+ if args.with_manifest:
54
+ print(">>> create_manifest.py")
55
+ r = run([sys.executable, "scripts/create_manifest.py"])
56
+ print(r.stdout, end="")
57
+ if r.returncode != 0:
58
+ print(r.stderr, file=sys.stderr)
59
+ return 1
60
+ paths.append("MANIFEST.sha256")
61
+
62
+ print(">>> git diff --ignore-space-at-eol --exit-code", " ".join(paths))
63
+ r = run(["git", "diff", "--ignore-space-at-eol", "--exit-code", "--", *paths])
64
+ if r.returncode != 0:
65
+ print(
66
+ "ERROR: los artefactos generados no coinciden con lo versionado.",
67
+ file=sys.stderr,
68
+ )
69
+ print(r.stdout or r.stderr, file=sys.stderr)
70
+ return 1
71
+
72
+ print("OK: derivados (CSV + GENERATED_FROM) coinciden con HEAD")
73
+ return 0
74
+
75
+
76
+ if __name__ == "__main__":
77
+ sys.exit(main())
cosmos_nahuatl.csv ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ external_id,external_label,mapped_node_id,perspective,phase,position,relation_candidate,notes
2
+ # spec 1.7.0 — tríadas 1–13; posiciones →|0|→
3
+ nah_sol_viento,Nahui_Ehecatl_Sol_Viento,T01_adv_P0,Evol,adv,→,none,"Primera edad; oscuridad inicial"
4
+ nah_sol_fuego,Nahui_Quiahuitl_Sol_Fuego,T01_adv_P1,Invol,adv,0,creates,"Lluvia de fuego; consciencia"
5
+ nah_sol_agua,Nahui_Atl_Sol_Agua,T01_ret_P1,Invol,ret,0,creates,"Diluvio"
6
+ nah_sol_tierra,Nahui_Ocelotl_Sol_Tierra,T01_ret_P2,Invol,ret,←,creates,"Temblores; retorno a oscuridad"
7
+ nah_sol_ollin,Nahui_Ollin_Sol_Movimiento,T01_adv_P2,Tot,adv,→,none,"Quinto Sol / luz presente"
8
+ nah_tezcatlipoca,Tezcatlipoca,T01_adv_P0,Ind,adv,→,none,"Fuerza oscura"
9
+ nah_quetzalcoatl,Quetzalcoatl,T01_ret_P0,Ind,ret,←,none,"Fuerza luminosa reflejada"
10
+ nah_lucha_dioses,lucha_Tezcatlipoca_Quetzalcoatl,T01_adv_P1,D,adv,0,mirrorOf,"Dualidad (consciencia)"
11
+ nah_vida,vida,T03_adv_P2,Tot,adv,→,none,"Polo vida"
12
+ nah_muerte,muerte,T03_adv_P0,Ind,adv,→,none,"Polo muerte"
13
+ nah_vida_muerte,vida_muerte,T03_adv_P1,D,adv,0,mirrorOf,"Dicotomía mesoamericana"
14
+ nah_tlaltecuhtli,Tlaltecuhtli,T11_ret_P1,Invol,ret,0,creates,"Tierra devoradora; espacio/vacío"
15
+ nah_mictlan,Mictlan,T11_ret_P0,Tot,ret,←,none,"Lugar de los muertos; vacío"
16
+ nah_teyolia,teyolia,T03_adv_P0,Ind,adv,→,creates,"Entidad anímica"
17
+ nah_camino_mictlan,camino_al_Mictlan,T11_ret_P0,Invol,ret,←,creates,"Retorno al vacío"
create_manifest.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Escribe SHA-256 de los artefactos fuente/reproducibles incluidos en el paquete.
3
+
4
+ Exclusiones (no forman parte del punto fijo del manifiesto):
5
+ - MANIFEST.sha256 — evita hash auto-referente
6
+ - AUDITORIA_AUTO.md — regenerable con timestamp
7
+ - ontology/io_ontology.ttl — regenerable; orden de serialización rdflib no es
8
+ estable byte-a-byte entre corridas (CI lo regenera antes de SHACL)
9
+ - __pycache__, .pytest_cache, .venv
10
+
11
+ Los CSV canónicos (triad_nodes, vector_steps, relation_candidates) SÍ entran:
12
+ son el punto fijo de generate_ontology.py.
13
+ """
14
+ from hashlib import sha256
15
+ from pathlib import Path
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+ INCLUDE_DIRS = ("IOM", "data", "datasets", "docs", "experiments", "ontology", "scripts", "tests")
19
+ INCLUDE_FILES = (
20
+ "IOM.lean", "README.md", "AUDITORIA.md", "EXPERIMENTOS.md", "REPRODUCCION.md", "paper.md",
21
+ "MANIFIESTO.md",
22
+ "requirements.txt", "requirements-lock.txt", "lakefile.lean", "lake-manifest.json", "lean-toolchain",
23
+ "LICENSE", ".gitignore", ".github/workflows/ci.yml",
24
+ )
25
+ EXCLUDE_NAMES = frozenset({
26
+ "MANIFEST.sha256",
27
+ "AUDITORIA_AUTO.md",
28
+ "io_ontology.ttl", # regenerable; serialización no determinista
29
+ })
30
+ EXCLUDE_DIR_PARTS = frozenset({"__pycache__", ".pytest_cache", ".venv", "node_modules"})
31
+
32
+
33
+ def main() -> None:
34
+ files = {ROOT / name for name in INCLUDE_FILES if (ROOT / name).is_file()}
35
+ for dirname in INCLUDE_DIRS:
36
+ folder = ROOT / dirname
37
+ if folder.exists():
38
+ files.update(
39
+ p for p in folder.rglob("*")
40
+ if p.is_file()
41
+ and not any(part in EXCLUDE_DIR_PARTS for part in p.parts)
42
+ )
43
+ files = {p for p in files if p.name not in EXCLUDE_NAMES}
44
+ out = ROOT / "MANIFEST.sha256"
45
+ lines = [
46
+ f"{sha256(path.read_bytes()).hexdigest()} {path.relative_to(ROOT).as_posix()}"
47
+ for path in sorted(files)
48
+ ]
49
+ out.write_text("\n".join(lines) + "\n", encoding="utf-8")
50
+ print(f"SHA-256: {len(lines)} archivos -> {out}")
51
+ print(f" excluidos por nombre: {sorted(EXCLUDE_NAMES)}")
52
+
53
+
54
+ if __name__ == "__main__":
55
+ main()
examples.csv ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ id,domain,source_label,target_label,relation,perspective,phase_hint,suggested_source_node,suggested_target_node
2
+ NAH-01,cosmos_nahuatl,Tezcatlipoca,Quetzalcoatl,mirrorOf,Dualidad,Lucha de fuerzas cósmicas,T01_adv_P0,T01_ret_P0
3
+ NAH-02,cosmos_nahuatl,vida,muerte,mirrorOf,Dualidad,Dicotomía mesoamericana,T03_adv_P2,T03_adv_P0
4
+ NAH-03,cosmos_nahuatl,Nahui_Quiahuitl_Sol_Fuego,Nahui_Atl_Sol_Agua,creates,Involución,Cataclismo / transición de edades,T01_adv_P1,T01_ret_P1
5
+ NAH-04,cosmos_nahuatl,camino_al_Mictlan,Mictlan,creates,Involución,Retorno al vacío,T11_ret_P0,T11_ret_P0
6
+ NAH-05,cosmos_nahuatl,Nahui_Ollin_Sol_Movimiento,Nahui_Ehecatl_Sol_Viento,none,Totalidad / Evolución,Quinto Sol vs primera edad,T01_adv_P2,T01_adv_P0
generate_audit_report.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Informe de auditoría regenerable (encuentro). No se versiona como fundamento."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+
9
+ ROOT = Path(__file__).resolve().parents[1]
10
+
11
+
12
+ def load_json(rel: str):
13
+ path = ROOT / rel
14
+ if not path.is_file():
15
+ return None
16
+ return json.loads(path.read_text(encoding="utf-8"))
17
+
18
+
19
+ def main() -> None:
20
+ out_dir = ROOT / "experiments" / "results"
21
+ out_dir.mkdir(parents=True, exist_ok=True)
22
+ metrics = load_json("experiments/results/pi_hgat_t_metrics.json")
23
+ baselines = load_json("experiments/results/baselines_comparison.json")
24
+ versions = load_json("experiments/results/software_versions.json")
25
+
26
+ lines = [
27
+ "# AUDITORIA_AUTO",
28
+ "",
29
+ f"Generado: {datetime.now(timezone.utc).isoformat()}",
30
+ "",
31
+ "> Informe fechado. **No** es prueba de punto fijo ni fundamento del marco.",
32
+ "",
33
+ "## Capas",
34
+ "",
35
+ "- Núcleo: `self_bootstrap.py`, Lean, SHACL, invariancia",
36
+ "- Encuentro: EXP-A/E, PI-HGAT-T/baselines (opcionales)",
37
+ "",
38
+ ]
39
+ if metrics is None:
40
+ lines.append(
41
+ "_No se encontró pi_hgat_t_metrics.json; "
42
+ "ejecutar experiments/optional/pi_hgat_t.py primero._"
43
+ )
44
+ else:
45
+ lines.append("## PI-HGAT-T (diagnóstico)")
46
+ lines.append("```json")
47
+ lines.append(json.dumps(metrics.get("primary_metrics", metrics), indent=2)[:2000])
48
+ lines.append("```")
49
+ if baselines:
50
+ lines.append("## Baselines")
51
+ lines.append("```json")
52
+ lines.append(json.dumps(baselines.get("baselines", baselines), indent=2)[:2000])
53
+ lines.append("```")
54
+ if versions:
55
+ lines.append("## Software")
56
+ lines.append(json.dumps(versions, indent=2))
57
+
58
+ out_md = out_dir / "AUDITORIA_AUTO.md"
59
+ out_md.write_text("\n".join(lines) + "\n", encoding="utf-8")
60
+ print(f"Escrito {out_md}")
61
+
62
+
63
+ if __name__ == "__main__":
64
+ main()
generate_ontology.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Genera RDF/OWL y datasets desde data/iom_spec.json, única fuente tabular."""
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import json
7
+ from pathlib import Path
8
+ from rdflib import BNode, Graph, Literal, Namespace
9
+ from rdflib.namespace import OWL, RDF, RDFS, XSD
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ SPEC = json.loads((ROOT / "data" / "iom_spec.json").read_text(encoding="utf-8"))
13
+ IO = Namespace("http://example.org/iom#")
14
+ g = Graph()
15
+ for prefix, namespace in (("io", IO), ("rdfs", RDFS), ("xsd", XSD), ("owl", OWL)):
16
+ g.bind(prefix, namespace)
17
+
18
+ ontology = IO.Ontology
19
+ g.add((ontology, RDF.type, OWL.Ontology))
20
+ g.add((ontology, OWL.versionInfo, Literal(SPEC["spec_version"])))
21
+ g.add((ontology, RDFS.label, Literal("Ontología IOM", lang="es")))
22
+ g.add((ontology, RDFS.comment, Literal(SPEC["source_note"], lang="es")))
23
+ classes = ("OntoNode", "VectorStep", "Perspective", "ExpandedCategory", "Position", "Direction", "SourceModel")
24
+ for name in classes:
25
+ g.add((IO[name], RDF.type, OWL.Class))
26
+ for names in (("OntoNode", "VectorStep", "ExpandedCategory", "Perspective"),):
27
+ axiom = BNode("iomDisjointCoreClasses")
28
+ head = BNode("iomDisjointClassList0")
29
+ g.add((axiom, RDF.type, OWL.AllDisjointClasses))
30
+ g.add((axiom, OWL.members, head))
31
+ cells = [BNode(f"iomDisjointClassList{i}") for i in range(len(names))]
32
+ for index, name in enumerate(names):
33
+ g.add((cells[index], RDF.first, IO[name]))
34
+ g.add((cells[index], RDF.rest, cells[index + 1] if index + 1 < len(cells) else RDF.nil))
35
+
36
+ object_properties = {
37
+ "hasPerspective": ("OntoNode", "Perspective"),
38
+ "hasPosition": ("OntoNode", "Position"),
39
+ "hasDirection": ("OntoNode", "Direction"),
40
+ "hasVector": ("VectorStep", "Perspective"),
41
+ "mirrorOf": ("OntoNode", "OntoNode"),
42
+ "creates": ("OntoNode", "OntoNode"),
43
+ }
44
+ datatype_properties = {
45
+ "hasTriadIndex": ("OntoNode", XSD.integer),
46
+ "hasPhase": ("OntoNode", XSD.string),
47
+ "hasLocalPos": ("OntoNode", XSD.integer),
48
+ "displayLabel": ("OntoNode", XSD.string),
49
+ "hasCyclePhase": ("VectorStep", XSD.string),
50
+ "hasAxisPosition": ("VectorStep", XSD.integer),
51
+ "hasStepIndex": ("VectorStep", XSD.integer),
52
+ "displayArrow": ("VectorStep", XSD.string),
53
+ "hasLevel": ("ExpandedCategory", XSD.integer),
54
+ "declaredTriadCount": ("SourceModel", XSD.integer),
55
+ "declaredPerspectiveCount": ("SourceModel", XSD.integer),
56
+ "declaredOperatorCount": ("SourceModel", XSD.integer),
57
+ "declaredExpandedCategoryCount": ("SourceModel", XSD.integer),
58
+ }
59
+ for name, (domain, range_) in object_properties.items():
60
+ prop = IO[name]
61
+ g.add((prop, RDF.type, OWL.ObjectProperty))
62
+ g.add((prop, RDFS.domain, IO[domain]))
63
+ g.add((prop, RDFS.range, IO[range_]))
64
+ for name, (domain, range_) in datatype_properties.items():
65
+ prop = IO[name]
66
+ g.add((prop, RDF.type, OWL.DatatypeProperty))
67
+ g.add((prop, RDFS.domain, IO[domain]))
68
+ g.add((prop, RDFS.range, range_))
69
+ for name in ("hasPerspective", "hasPosition", "hasDirection", "hasVector", "hasTriadIndex", "hasPhase", "hasLocalPos", "displayLabel", "hasCyclePhase", "hasAxisPosition", "hasStepIndex", "displayArrow", "hasLevel"):
70
+ g.add((IO[name], RDF.type, OWL.FunctionalProperty))
71
+ g.add((IO.mirrorOf, RDF.type, OWL.SymmetricProperty))
72
+
73
+ for pos, label in [("→", "→"), ("0", "0"), ("←", "←")]:
74
+ g.add((IO[pos], RDF.type, OWL.NamedIndividual))
75
+ g.add((IO[pos], RDF.type, IO.Position))
76
+ g.add((IO[pos], RDFS.label, Literal(label, lang="es")))
77
+ for direction in ("evol", "invol"):
78
+ g.add((IO[direction], RDF.type, OWL.NamedIndividual))
79
+ g.add((IO[direction], RDF.type, IO.Direction))
80
+ _perspective_labels = SPEC.get("perspective_labels") or {
81
+ "Ind": "Individualidad", "D": "Dualidad", "Tot": "Totalidad",
82
+ "Evol": "Evolución", "Invol": "Involución",
83
+ }
84
+ for name, label in _perspective_labels.items():
85
+ g.add((IO[name], RDF.type, IO.Perspective))
86
+ g.add((IO[name], RDFS.label, Literal(label, lang="es")))
87
+
88
+ position_meta = SPEC["positions"]
89
+ position_indices = position_meta["indices"]
90
+ position_names_adv = ["→", "0", "→"]
91
+ position_names_ret = ["←", "0", "←"]
92
+ perspective_names = position_meta["perspectives"]
93
+ perspectives = [IO[name] for name in perspective_names]
94
+ triad_meta = SPEC["triads"]
95
+ triad_rows = {phase: triad_meta[phase] for phase in ("adv", "ret")}
96
+ index_base = triad_meta.get("index_base", 0)
97
+ n_triads = len(triad_rows["adv"])
98
+ triad_ids = range(index_base, index_base + n_triads)
99
+ nodes_csv = []
100
+ for phase, rows in triad_rows.items():
101
+ direction = IO[SPEC["phases"][phase]["direction"]]
102
+ for row_index, labels in enumerate(rows):
103
+ triad_idx = index_base + row_index
104
+ for pos_idx, label in enumerate(labels):
105
+ node = IO[f"T{triad_idx:02d}_{phase}_P{pos_idx}"]
106
+ g.add((node, RDF.type, IO.OntoNode))
107
+ g.add((node, IO.hasTriadIndex, Literal(triad_idx, datatype=XSD.integer)))
108
+ g.add((node, IO.hasPhase, Literal(phase, datatype=XSD.string)))
109
+ g.add((node, IO.hasLocalPos, Literal(pos_idx, datatype=XSD.integer)))
110
+ display_labels = position_meta["adv_labels" if phase == "adv" else "ret_labels"]
111
+ display_label = display_labels[pos_idx]
112
+ g.add((node, IO.displayLabel, Literal(display_label, datatype=XSD.string)))
113
+ pos_names = position_names_adv if phase == "adv" else position_names_ret
114
+ g.add((node, IO.hasPosition, IO[pos_names[pos_idx]]))
115
+ g.add((node, IO.hasPerspective, perspectives[pos_idx]))
116
+ g.add((node, IO.hasDirection, direction))
117
+ g.add((node, RDFS.label, Literal(label, lang="es")))
118
+ nodes_csv.append({"node_id": str(node).split("#", 1)[1], "triad_index": triad_idx, "phase": phase,
119
+ "direction": str(direction).split("#", 1)[1], "position_index": pos_idx,
120
+ "position": pos_names[pos_idx], "display_label": display_label,
121
+ "perspective": perspective_names[pos_idx], "label": label})
122
+
123
+ for triad_idx in triad_ids:
124
+ for pos_idx in range(3):
125
+ adv = IO[f"T{triad_idx:02d}_adv_P{pos_idx}"]
126
+ ret = IO[f"T{triad_idx:02d}_ret_P{2-pos_idx}"]
127
+ g.add((adv, IO.mirrorOf, ret))
128
+ g.add((ret, IO.mirrorOf, adv))
129
+
130
+ for triad_idx in triad_ids:
131
+ for rule in SPEC["creation_rules"]:
132
+ for source_pos in rule["source_positions"]:
133
+ for target_pos in rule["target_positions"]:
134
+ source = IO[f"T{triad_idx:02d}_{rule['source_phase']}_P{source_pos}"]
135
+ target = IO[f"T{triad_idx:02d}_{rule['target_phase']}_P{target_pos}"]
136
+ g.add((source, IO.creates, target))
137
+
138
+ vector_csv = []
139
+ for vector_row in SPEC["vectors"]:
140
+ vector, phase = vector_row["name"], vector_row["phase"]
141
+ for step_index, (label, axis_pos) in enumerate(zip(vector_row["labels"], vector_row["axis_positions"])):
142
+ step = IO[f"vector_{vector.lower()}_{phase}_{step_index}"]
143
+ g.add((step, RDF.type, IO.VectorStep))
144
+ g.add((step, IO.hasVector, IO[vector]))
145
+ g.add((step, IO.hasCyclePhase, Literal(phase, datatype=XSD.string)))
146
+ g.add((step, IO.hasAxisPosition, Literal(axis_pos, datatype=XSD.integer)))
147
+ g.add((step, IO.hasStepIndex, Literal(step_index, datatype=XSD.integer)))
148
+ g.add((step, IO.displayArrow, Literal(vector_row["arrow"], datatype=XSD.string)))
149
+ g.add((step, RDFS.label, Literal(label, lang="es")))
150
+ vector_csv.append({"step_id": str(step).split("#", 1)[1], "vector": vector, "phase": phase,
151
+ "step_index": step_index, "axis_position": axis_pos, "label": label,
152
+ "arrow": vector_row["arrow"]})
153
+
154
+ for level, labels in SPEC["expanded_categories"].items():
155
+ for index, label in enumerate(labels, 1):
156
+ category = IO[f"expanded_L{level}_{index:02d}"]
157
+ g.add((category, RDF.type, IO.ExpandedCategory))
158
+ g.add((category, IO.hasLevel, Literal(int(level), datatype=XSD.integer)))
159
+ g.add((category, RDFS.label, Literal(label, lang="es")))
160
+
161
+ model = IO.SourceModel
162
+ g.add((model, RDF.type, IO.SourceModel))
163
+ for prop, value in ((IO.declaredTriadCount, 13), (IO.declaredPerspectiveCount, 5),
164
+ (IO.declaredOperatorCount, 4), (IO.declaredExpandedCategoryCount, 21)):
165
+ g.add((model, prop, Literal(value, datatype=XSD.integer)))
166
+
167
+ relation_csv = []
168
+ relation_lookup = {}
169
+ for subject, _, obj in g.triples((None, IO.mirrorOf, None)):
170
+ relation_lookup[(str(subject), str(obj))] = "mirrorOf"
171
+ for subject, _, obj in g.triples((None, IO.creates, None)):
172
+ relation_lookup[(str(subject), str(obj))] = "creates"
173
+ for triad_idx in triad_ids:
174
+ ids = [IO[f"T{triad_idx:02d}_{phase}_P{pos}"] for phase in ("adv", "ret") for pos in range(3)]
175
+ for source in ids:
176
+ for target in ids:
177
+ if source == target:
178
+ continue
179
+ relation_csv.append({"triad_index": triad_idx, "source": str(source).split("#", 1)[1],
180
+ "target": str(target).split("#", 1)[1],
181
+ "relation": relation_lookup.get((str(source), str(target)), "none")})
182
+
183
+ assert len(triad_rows["adv"]) == len(triad_rows["ret"]) == 13
184
+ assert position_indices == [0, 1, 2]
185
+ assert len(nodes_csv) == 78
186
+ assert len(vector_csv) == 20
187
+ assert sum(1 for _ in g.triples((None, IO.creates, None))) == 104
188
+ assert len(relation_csv) == 13 * 6 * 5
189
+
190
+ out = ROOT / "ontology" / "io_ontology.ttl"
191
+ out.parent.mkdir(parents=True, exist_ok=True)
192
+ out.write_text(g.serialize(format="turtle").rstrip() + "\n", encoding="utf-8")
193
+
194
+ def write_csv(path: Path, rows: list[dict]) -> None:
195
+ path.parent.mkdir(parents=True, exist_ok=True)
196
+ with path.open("w", newline="", encoding="utf-8") as handle:
197
+ writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n")
198
+ writer.writeheader()
199
+ writer.writerows(rows)
200
+
201
+ write_csv(ROOT / "datasets" / "triad_nodes.csv", nodes_csv)
202
+ write_csv(ROOT / "datasets" / "vector_steps.csv", vector_csv)
203
+ write_csv(ROOT / "datasets" / "relation_candidates.csv", relation_csv)
204
+
205
+ _stamp = {
206
+ "spec_version": SPEC["spec_version"],
207
+ "schema_version": SPEC.get("schema_version"),
208
+ "source_date": SPEC.get("source_date"),
209
+ "purpose_id": (SPEC.get("purpose") or {}).get("id"),
210
+ "purpose_label": (SPEC.get("purpose") or {}).get("label"),
211
+ "artifacts": [
212
+ "datasets/triad_nodes.csv",
213
+ "datasets/vector_steps.csv",
214
+ "datasets/relation_candidates.csv",
215
+ "ontology/io_ontology.ttl",
216
+ ],
217
+ }
218
+ (ROOT / "datasets" / "GENERATED_FROM.json").write_text(
219
+ json.dumps(_stamp, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
220
+ )
221
+ print(f"Tríadas: {n_triads} por fase (índice {index_base}–{index_base + n_triads - 1}); nodos: {len(nodes_csv)}; creates: 104; espejos: 78")
222
+ print(f"Pasos vectoriales: {len(vector_csv)}; candidatos PI-HGAT-T: {len(relation_csv)}")
223
+ print(f"OWL/Turtle: {out}")
224
+ print(f"Sello: datasets/GENERATED_FROM.json spec_version={SPEC['spec_version']}")
importar_datos_personalizados.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Plantilla de ingesta guiada: alinea un CSV de conceptos externos a la ontología IOM de 78 nodos.
3
+
4
+ No modifica data/iom_spec.json ni la ontología core. Valida que los mapped_node_id
5
+ existen, comprueba consistencia de perspectiva/fase/posición y genera un CSV alineado
6
+ más un informe de validación.
7
+
8
+ Uso:
9
+ python scripts/importar_datos_personalizados.py \
10
+ --input datasets/ingestion/templates/biologia_depredador_presa.csv \
11
+ --output datasets/ingestion/aligned/biologia_aligned.csv
12
+
13
+ Opciones:
14
+ --input PATH CSV de entrada (obligatorio)
15
+ --output PATH CSV alineado de salida (por defecto: datasets/ingestion/aligned/<stem>_aligned.csv)
16
+ --strict Fallar si hay cualquier warning (por defecto solo error en mapped_node_id inválido)
17
+ --report PATH Ruta del informe JSON (por defecto junto al output)
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import csv
23
+ import json
24
+ import sys
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ ROOT = Path(__file__).resolve().parents[1]
29
+ NODES_CSV = ROOT / "datasets" / "triad_nodes.csv"
30
+ VALID_PERSPECTIVES = {"Ind", "D", "Tot", "Evol", "Invol"}
31
+ VALID_PHASES = {"adv", "ret"}
32
+ VALID_POSITIONS = {"left", "center", "right"}
33
+ VALID_RELATIONS = {"none", "mirrorOf", "creates"}
34
+ REQUIRED_COLUMNS = {"external_id", "external_label"}
35
+
36
+
37
+ def load_canonical_nodes() -> dict[str, dict[str, Any]]:
38
+ """Carga los 78 nodos canónicos indexados por node_id."""
39
+ if not NODES_CSV.is_file():
40
+ print(
41
+ f"ERROR: no se encuentra {NODES_CSV}. "
42
+ "Ejecuta primero: python scripts/generate_ontology.py",
43
+ file=sys.stderr,
44
+ )
45
+ raise SystemExit(1)
46
+ nodes: dict[str, dict[str, Any]] = {}
47
+ with NODES_CSV.open(encoding="utf-8", newline="") as fh:
48
+ reader = csv.DictReader(fh)
49
+ for row in reader:
50
+ nodes[row["node_id"]] = row
51
+ if len(nodes) != 78:
52
+ print(
53
+ f"ADVERTENCIA: se esperaban 78 nodos, se cargaron {len(nodes)}. "
54
+ "Regenera los datasets con generate_ontology.py.",
55
+ file=sys.stderr,
56
+ )
57
+ return nodes
58
+
59
+
60
+ def read_input_csv(path: Path) -> list[dict[str, str]]:
61
+ """Lee el CSV de entrada ignorando líneas de comentario que empiezan por #."""
62
+ rows: list[dict[str, str]] = []
63
+ with path.open(encoding="utf-8", newline="") as fh:
64
+ # Filtrar comentarios antes de pasar al DictReader
65
+ lines = [ln for ln in fh if not ln.strip().startswith("#")]
66
+ from io import StringIO
67
+
68
+ reader = csv.DictReader(StringIO("".join(lines)))
69
+ if reader.fieldnames is None:
70
+ print("ERROR: el CSV no tiene cabecera.", file=sys.stderr)
71
+ raise SystemExit(1)
72
+ missing = REQUIRED_COLUMNS - set(reader.fieldnames)
73
+ if missing:
74
+ print(f"ERROR: faltan columnas obligatorias: {sorted(missing)}", file=sys.stderr)
75
+ raise SystemExit(1)
76
+ for row in reader:
77
+ # Normalizar claves
78
+ cleaned = {k.strip(): (v.strip() if isinstance(v, str) else v) for k, v in row.items()}
79
+ if not cleaned.get("external_id"):
80
+ continue
81
+ rows.append(cleaned)
82
+ return rows
83
+
84
+
85
+ def validate_row(
86
+ row: dict[str, str],
87
+ nodes: dict[str, dict[str, Any]],
88
+ row_num: int,
89
+ ) -> tuple[dict[str, Any], list[str], list[str]]:
90
+ """Valida una fila y devuelve (fila_alineada, errores, warnings)."""
91
+ errors: list[str] = []
92
+ warnings: list[str] = []
93
+ aligned: dict[str, Any] = {
94
+ "external_id": row["external_id"],
95
+ "external_label": row.get("external_label", ""),
96
+ "mapped_node_id": row.get("mapped_node_id", ""),
97
+ "perspective": row.get("perspective", ""),
98
+ "phase": row.get("phase", ""),
99
+ "position": row.get("position", ""),
100
+ "relation_candidate": row.get("relation_candidate", "none") or "none",
101
+ "notes": row.get("notes", ""),
102
+ "canonical_label": "",
103
+ "canonical_perspective": "",
104
+ "canonical_phase": "",
105
+ "canonical_position": "",
106
+ "status": "ok",
107
+ }
108
+
109
+ node_id = aligned["mapped_node_id"]
110
+ if not node_id:
111
+ errors.append(f"fila {row_num}: mapped_node_id vacío")
112
+ aligned["status"] = "error"
113
+ return aligned, errors, warnings
114
+
115
+ if node_id not in nodes:
116
+ errors.append(
117
+ f"fila {row_num}: mapped_node_id '{node_id}' no existe en los 78 nodos canónicos"
118
+ )
119
+ aligned["status"] = "error"
120
+ return aligned, errors, warnings
121
+
122
+ canon = nodes[node_id]
123
+ aligned["canonical_label"] = canon.get("label", "")
124
+ aligned["canonical_perspective"] = canon.get("perspective", "")
125
+ aligned["canonical_phase"] = canon.get("phase", "")
126
+ aligned["canonical_position"] = canon.get("position", "")
127
+
128
+ # Consistencia opcional de perspectiva / fase / posición
129
+ if aligned["perspective"] and aligned["perspective"] not in VALID_PERSPECTIVES:
130
+ warnings.append(
131
+ f"fila {row_num}: perspective '{aligned['perspective']}' no es canónica "
132
+ f"({sorted(VALID_PERSPECTIVES)})"
133
+ )
134
+ elif aligned["perspective"] and aligned["perspective"] != canon.get("perspective"):
135
+ # Solo advertir si el usuario forzó un valor distinto del nodo
136
+ if aligned["perspective"] in {"Ind", "D", "Tot"}:
137
+ warnings.append(
138
+ f"fila {row_num}: perspective declarada '{aligned['perspective']}' "
139
+ f"≠ perspectiva del nodo '{canon.get('perspective')}'"
140
+ )
141
+
142
+ if aligned["phase"] and aligned["phase"] not in VALID_PHASES:
143
+ warnings.append(
144
+ f"fila {row_num}: phase '{aligned['phase']}' no es canónica ({sorted(VALID_PHASES)})"
145
+ )
146
+ elif aligned["phase"] and aligned["phase"] != canon.get("phase"):
147
+ warnings.append(
148
+ f"fila {row_num}: phase declarada '{aligned['phase']}' ≠ fase del nodo '{canon.get('phase')}'"
149
+ )
150
+
151
+ if aligned["position"] and aligned["position"] not in VALID_POSITIONS:
152
+ warnings.append(
153
+ f"fila {row_num}: position '{aligned['position']}' no es canónica "
154
+ f"({sorted(VALID_POSITIONS)})"
155
+ )
156
+ elif aligned["position"] and aligned["position"] != canon.get("position"):
157
+ warnings.append(
158
+ f"fila {row_num}: position declarada '{aligned['position']}' "
159
+ f"≠ posición del nodo '{canon.get('position')}'"
160
+ )
161
+
162
+ if aligned["relation_candidate"] not in VALID_RELATIONS:
163
+ warnings.append(
164
+ f"fila {row_num}: relation_candidate '{aligned['relation_candidate']}' "
165
+ f"no es válida ({sorted(VALID_RELATIONS)}); se fuerza a 'none'"
166
+ )
167
+ aligned["relation_candidate"] = "none"
168
+
169
+ if warnings and aligned["status"] == "ok":
170
+ aligned["status"] = "warning"
171
+
172
+ return aligned, errors, warnings
173
+
174
+
175
+ def main() -> int:
176
+ parser = argparse.ArgumentParser(
177
+ description="Alinea un CSV de conceptos externos a la ontología IOM de 78 nodos."
178
+ )
179
+ parser.add_argument("--input", "-i", required=True, type=Path, help="CSV de entrada")
180
+ parser.add_argument(
181
+ "--output",
182
+ "-o",
183
+ type=Path,
184
+ default=None,
185
+ help="CSV alineado de salida",
186
+ )
187
+ parser.add_argument(
188
+ "--strict",
189
+ action="store_true",
190
+ help="Tratar warnings como errores (exit code 1)",
191
+ )
192
+ parser.add_argument(
193
+ "--report",
194
+ type=Path,
195
+ default=None,
196
+ help="Ruta del informe JSON de validación",
197
+ )
198
+ args = parser.parse_args()
199
+
200
+ if not args.input.is_file():
201
+ print(f"ERROR: no existe el archivo de entrada: {args.input}", file=sys.stderr)
202
+ return 1
203
+
204
+ nodes = load_canonical_nodes()
205
+ rows = read_input_csv(args.input)
206
+ if not rows:
207
+ print("ERROR: el CSV de entrada no contiene filas de datos.", file=sys.stderr)
208
+ return 1
209
+
210
+ aligned_rows: list[dict[str, Any]] = []
211
+ all_errors: list[str] = []
212
+ all_warnings: list[str] = []
213
+
214
+ for i, row in enumerate(rows, start=2): # +2 por cabecera y 1-index
215
+ aligned, errors, warnings = validate_row(row, nodes, i)
216
+ aligned_rows.append(aligned)
217
+ all_errors.extend(errors)
218
+ all_warnings.extend(warnings)
219
+
220
+ # Determinar rutas de salida
221
+ if args.output is None:
222
+ out_dir = ROOT / "datasets" / "ingestion" / "aligned"
223
+ out_dir.mkdir(parents=True, exist_ok=True)
224
+ args.output = out_dir / f"{args.input.stem}_aligned.csv"
225
+ else:
226
+ args.output.parent.mkdir(parents=True, exist_ok=True)
227
+
228
+ if args.report is None:
229
+ args.report = args.output.with_suffix(".report.json")
230
+
231
+ # Escribir CSV alineado
232
+ fieldnames = [
233
+ "external_id",
234
+ "external_label",
235
+ "mapped_node_id",
236
+ "canonical_label",
237
+ "canonical_perspective",
238
+ "canonical_phase",
239
+ "canonical_position",
240
+ "perspective",
241
+ "phase",
242
+ "position",
243
+ "relation_candidate",
244
+ "status",
245
+ "notes",
246
+ ]
247
+ with args.output.open("w", encoding="utf-8", newline="") as fh:
248
+ writer = csv.DictWriter(fh, fieldnames=fieldnames, extrasaction="ignore")
249
+ writer.writeheader()
250
+ writer.writerows(aligned_rows)
251
+
252
+ report = {
253
+ "input": str(args.input),
254
+ "output": str(args.output),
255
+ "canonical_nodes": len(nodes),
256
+ "rows_processed": len(aligned_rows),
257
+ "errors": all_errors,
258
+ "warnings": all_warnings,
259
+ "ok_count": sum(1 for r in aligned_rows if r["status"] == "ok"),
260
+ "warning_count": sum(1 for r in aligned_rows if r["status"] == "warning"),
261
+ "error_count": sum(1 for r in aligned_rows if r["status"] == "error"),
262
+ }
263
+ args.report.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
264
+
265
+ # Resumen en consola
266
+ print(f"Entrada: {args.input}")
267
+ print(f"Salida: {args.output}")
268
+ print(f"Informe: {args.report}")
269
+ print(f"Filas: {report['rows_processed']} "
270
+ f"(ok={report['ok_count']}, warning={report['warning_count']}, error={report['error_count']})")
271
+ if all_errors:
272
+ print("\nERRORES:")
273
+ for e in all_errors:
274
+ print(f" - {e}")
275
+ if all_warnings:
276
+ print("\nADVERTENCIAS:")
277
+ for w in all_warnings:
278
+ print(f" - {w}")
279
+
280
+ if all_errors:
281
+ print("\nResultado: FALLO (hay errores de mapeo)")
282
+ return 1
283
+ if args.strict and all_warnings:
284
+ print("\nResultado: FALLO (--strict y hay advertencias)")
285
+ return 1
286
+ print("\nResultado: OK — los conceptos se alinearon a la ontología canónica sin romper la bóveda.")
287
+ return 0
288
+
289
+
290
+ if __name__ == "__main__":
291
+ sys.exit(main())
io_shapes.ttl ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
2
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
3
+ @prefix io: <http://example.org/iom#> .
4
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
5
+
6
+ io:StructuralShape a sh:NodeShape ;
7
+ sh:targetClass io:OntoNode ;
8
+ sh:property [ sh:path io:hasTriadIndex ; sh:datatype xsd:integer ; sh:minInclusive 1 ; sh:maxInclusive 13 ; sh:minCount 1 ; sh:maxCount 1 ] ;
9
+ sh:property [ sh:path io:hasPhase ; sh:datatype xsd:string ; sh:in ( "adv"^^xsd:string "ret"^^xsd:string ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
10
+ sh:property [ sh:path io:hasLocalPos ; sh:datatype xsd:integer ; sh:in ( 0 1 2 ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
11
+ sh:property [ sh:path io:displayLabel ; sh:datatype xsd:string ; sh:in ( "→"^^xsd:string "0"^^xsd:string "←"^^xsd:string ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
12
+ sh:property [ sh:path io:hasPosition ; sh:in ( <http://example.org/iom#→> <http://example.org/iom#0> <http://example.org/iom#←> ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
13
+ sh:property [ sh:path io:hasPerspective ; sh:in ( io:Ind io:D io:Tot ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
14
+ sh:property [ sh:path io:hasDirection ; sh:in ( io:evol io:invol ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
15
+ sh:property [ sh:path rdfs:label ; sh:languageIn ( "es" ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
16
+ sh:property [ sh:path io:mirrorOf ; sh:class io:OntoNode ; sh:minCount 1 ; sh:maxCount 1 ] ;
17
+ sh:property [ sh:path io:creates ; sh:class io:OntoNode ; sh:minCount 1 ; sh:maxCount 2 ] ;
18
+ sh:sparql [
19
+ sh:message "posicion y fase" ;
20
+ sh:select """
21
+ PREFIX io: <http://example.org/iom#>
22
+ SELECT $this WHERE {
23
+ $this io:hasLocalPos ?pos ; io:hasPerspective ?perspective ; io:hasPosition ?position ; io:hasPhase ?phase .
24
+ FILTER (
25
+ (?pos = 1 && (?perspective != io:D || ?position != <http://example.org/iom#0>)) ||
26
+ (?pos = 0 && ?perspective != io:Ind) ||
27
+ (?pos = 2 && ?perspective != io:Tot) ||
28
+ (?phase = "adv" && (?pos = 0 || ?pos = 2) && ?position != <http://example.org/iom#→>) ||
29
+ (?phase = "ret" && (?pos = 0 || ?pos = 2) && ?position != <http://example.org/iom#←>)
30
+ )
31
+ }
32
+ """
33
+ ] ;
34
+ sh:sparql [
35
+ sh:message "etiquetas visuales" ;
36
+ sh:select """
37
+ PREFIX io: <http://example.org/iom#>
38
+ SELECT $this WHERE {
39
+ $this io:hasPhase ?phase ; io:hasLocalPos ?pos ; io:displayLabel ?label .
40
+ FILTER ((?phase = "adv" &&
41
+ !((?pos = 0 && ?label = "→") || (?pos = 1 && ?label = "0") || (?pos = 2 && ?label = "→"))) ||
42
+ (?phase = "ret" &&
43
+ !((?pos = 0 && ?label = "←") || (?pos = 1 && ?label = "0") || (?pos = 2 && ?label = "←"))))
44
+ }
45
+ """
46
+ ] ;
47
+ sh:sparql [
48
+ sh:message "espejo reciproco" ;
49
+ sh:select """
50
+ PREFIX io: <http://example.org/iom#>
51
+ SELECT $this WHERE {
52
+ $this io:hasTriadIndex ?triad ; io:hasLocalPos ?pos ; io:hasPhase ?phase ; io:mirrorOf ?mirror .
53
+ ?mirror io:hasTriadIndex ?otherTriad ; io:hasLocalPos ?otherPos ; io:hasPhase ?otherPhase .
54
+ FILTER NOT EXISTS { ?mirror io:mirrorOf $this }
55
+ FILTER (?triad != ?otherTriad || ?otherPos != (2 - ?pos) ||
56
+ !((?phase = "adv" && ?otherPhase = "ret") || (?phase = "ret" && ?otherPhase = "adv")))
57
+ }
58
+ """
59
+ ] ;
60
+ sh:sparql [
61
+ sh:message "fase y direccion" ;
62
+ sh:select """
63
+ PREFIX io: <http://example.org/iom#>
64
+ SELECT $this WHERE {
65
+ $this io:hasPhase ?phase ; io:hasDirection ?direction .
66
+ FILTER ((?phase = "adv" && ?direction != io:evol) || (?phase = "ret" && ?direction != io:invol))
67
+ }
68
+ """
69
+ ] ;
70
+ sh:sparql [
71
+ sh:message "creates reglas" ;
72
+ sh:select """
73
+ PREFIX io: <http://example.org/iom#>
74
+ SELECT $this WHERE {
75
+ $this io:hasTriadIndex ?triad ; io:hasLocalPos ?pos ; io:hasPhase ?phase ; io:creates ?target .
76
+ ?target io:hasTriadIndex ?otherTriad ; io:hasLocalPos ?otherPos ; io:hasPhase ?otherPhase .
77
+ FILTER (?triad != ?otherTriad ||
78
+ !((?phase = "adv" && ?otherPhase = "ret" &&
79
+ ((?pos = 0 && ?otherPos = 1) || (?pos = 2 && ?otherPos = 1) ||
80
+ (?pos = 1 && (?otherPos = 0 || ?otherPos = 2)))) ||
81
+ (?phase = "ret" && ?otherPhase = "adv" &&
82
+ ((?pos = 0 && ?otherPos = 1) || (?pos = 2 && ?otherPos = 1) ||
83
+ (?pos = 1 && (?otherPos = 0 || ?otherPos = 2)))))
84
+ )
85
+ }
86
+ """
87
+ ] .
88
+
89
+ io:VectorStepShape a sh:NodeShape ;
90
+ sh:targetClass io:VectorStep ;
91
+ sh:property [ sh:path io:hasVector ; sh:in ( io:Evol io:Invol ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
92
+ sh:property [ sh:path io:hasCyclePhase ; sh:datatype xsd:string ; sh:in ( "adv"^^xsd:string "ret"^^xsd:string ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
93
+ sh:property [ sh:path io:hasAxisPosition ; sh:datatype xsd:integer ; sh:in ( 0 1 2 3 4 ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
94
+ sh:property [ sh:path io:hasStepIndex ; sh:datatype xsd:integer ; sh:in ( 0 1 2 3 4 ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
95
+ sh:property [ sh:path io:displayArrow ; sh:in ( "→"^^xsd:string "←"^^xsd:string ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
96
+ sh:property [ sh:path rdfs:label ; sh:languageIn ( "es" ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
97
+ sh:sparql [
98
+ sh:message "etiqueta vectorial canónica" ;
99
+ sh:select """
100
+ PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
101
+ SELECT $this WHERE {
102
+ $this rdfs:label ?label .
103
+ BIND(STR(?label) AS ?text)
104
+ FILTER (?text != "invol" && ?text != "ind" && ?text != "dua" && ?text != "tot" && ?text != "evol")
105
+ }
106
+ """
107
+ ] .
108
+
109
+ io:ExpandedCategoryShape a sh:NodeShape ;
110
+ sh:targetClass io:ExpandedCategory ;
111
+ sh:property [ sh:path io:hasLevel ; sh:datatype xsd:integer ; sh:in ( 0 1 2 3 4 ) ; sh:minCount 1 ; sh:maxCount 1 ] ;
112
+ sh:property [ sh:path rdfs:label ; sh:languageIn ( "es" ) ; sh:minCount 1 ; sh:maxCount 1 ] .
113
+
114
+ io:SourceModelShape a sh:NodeShape ;
115
+ sh:targetNode io:SourceModel ;
116
+ sh:property [ sh:path io:declaredTriadCount ; sh:hasValue 13 ; sh:minCount 1 ; sh:maxCount 1 ] ;
117
+ sh:property [ sh:path io:declaredPerspectiveCount ; sh:hasValue 5 ; sh:minCount 1 ; sh:maxCount 1 ] ;
118
+ sh:property [ sh:path io:declaredOperatorCount ; sh:hasValue 4 ; sh:minCount 1 ; sh:maxCount 1 ] ;
119
+ sh:property [ sh:path io:declaredExpandedCategoryCount ; sh:hasValue 21 ; sh:minCount 1 ; sh:maxCount 1 ] .
120
+
121
+ io:PerspectiveShape a sh:NodeShape ;
122
+ sh:targetClass io:Perspective ;
123
+ sh:property [ sh:path rdfs:label ; sh:languageIn ( "es" ) ; sh:minCount 1 ; sh:maxCount 1 ] .
materialize_ttl.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Materializa ontology/io_ontology.ttl (hash 84e2fe87...). Preferir generate_ontology.py."""
3
+ from __future__ import annotations
4
+ import base64, hashlib, zlib
5
+ from pathlib import Path
6
+ ROOT = Path(__file__).resolve().parents[1]
7
+ OUT = ROOT / "ontology" / "io_ontology.ttl"
8
+ EXPECTED = "84e2fe878fcf4a41b7ad364fb6f22e28e16db9132b7e2de89d36de55deeb87ba"
9
+ PAYLOAD = 'eNrlncFu47gZx+/zFEJ62QU2iSg5djwtFhMkaRsg2QTNYFCg6AaMxDgcSKJBSU6ymENPPQf7BnvpbU77CHmTfZJSsmJJtER+ipXYI+1lJzZF8vvp779o6fvoD1NObui9Qdl74y+3UTR9v7tL7rE/9cgO45Ndyvw//WjsvPuQtWN3Xt7w7u5u585O21mmae2ao13xfqk9d28q26PxeLwrDrGsbdFkO3wIIny/HYTywWHdaOauiXbTQ51b4uPScfehW3cY2v3n2ellfsg7Efh5EDGPTR4MnIa3+PPP7wzxXzoJD18Tz9jK3nr6io2T87OtDyQsNnKY75MgEs2mhGOHsgB79Bfxj6ffA8PBgfgfdbDhip58zB1mnOyc7xgOE2/SQPwpjgqnxInoDIc7xjl3SSAaGyKoUHSb9YN2xjvme4NxunjtixM//RZE1GFfXMqJM2/4x3/+Z+CA+tj7chv7OGBfTg52jGPPePoauNQhhpg84y4Vk/zBCJhBxXARdbG7U4gr4TET0xKxnAQ3zNhKh9/KwDmc4Ei0zbhdfxaTv+BMxBGV6LnMxzQwMtQ/MRFU4V2OgwkpvTnv3SWOhzlxj++nOHCJeyjGmjD+cMhiAXk+5hGOcPQwJepRL1nMHXLGEvJLAydioYHomnBp4PQ0Roy/2YAXCwGQNxvzI6fYff3RaDj18MMB5+yuZpwf0l6eRffXOBAckk+Qeh6fBC7GLyMyrZ5GGHEaTMqzOE0/zG3Ool7WS3MgmZqvTs0rE4lZiNdkhVc4zyfsPH1lxt9IkGiSzpjx3afvCx9U0cstDk/JTDQ2l4ZCTYa6YBEJHIprekdVvVvg3g/E+WrSsw2fNxGKnKbm12SAQYOpN+vcakL9Mv5MIradmGgtIKtqCDj6QxyHePv4hjjNRmhwCtJLldDO9kEcqkRUOQ78TFw+ffWvxZV4+5JOAnojrqpuo4j2wCOdipFoRLY/io9zOBHhKRRQOdQQPNQZcSl2GvVvN1IYDSOx7Knp3K7qHK6tY+GAPGBNOofL6h/EbdIxXEd/Zx4N/Uazhkvn2Cd8ovoQVPYP18sh8/A0hE9+0EQsxzXdDqq6hcvk8urmzm3SNVwkJzPWpOMGZnPFyUzTtXjh4J6GFyykyXrhTZc45ZWWmMnhg+ORC/EPsr6llhj9KPkuUqCxPE55Hit/f8gHXMxhfpbapKASjOKcnDJH9MzCN1x2Ls2h8PXirU5Jcch8Hq1Ls8H6Oxm//Cl9fQjP4y1mkHyIToSK7tdrFOl3v/bn0VCW82m3eDJUHCo16VPxvZSf31TeyCiPf/ng+0ToyWnvPscsne4VmTHvCruzK3N+ZaqOIrsm0UC0Ll+TSl+xt/74769bP/9cUH/x2lW6VJmltwrXji0xmfo+cgmXO8jOZuKUYoo1ISJQiG47AaJVA0TNA7QAAboxbidAa9UAreYB2oAAIxa1E6C9aoB28wAHgABJax/CwaoRDppFyEkE8hl9hI8rRyjm8go2k0SI2hDp48oiBQaImgfYis08rmwzwACt5gHabVwoHle+UAADtJsHOGjnYv+48sUeGCLcZ9JZr2NBM3itBc1JoAgSfVMXRPSSELuxqFGGaH9TC1P7JSG+7cLGfK2FTW2Mb7+0MV9raaOMEX1Tl0b0khC7sbxRhmh/U0tU+yUhvvESZ/BaS5xikB9NlJrpReY0Vfd7stCKmTrlCJ/TZ7L+ElYXaAnAPFtBbbn5ne/kMUcyzdKjiud7z2WfKd4HS8Nzy28DbHoBvS51TMz6x9IRhVuOhVAXN+CKKCyZtaVlnac/rZm0pSL9kUWbRdoskM5eaIl0et4UpB+BpFN/aE/USicAoH58CepMwxJqqz0DeQPYL9H1+mDnuragbn2LuXuHOVGAtnrn1FYdZ0t2agvq1CG7iTaA82b5tI5zUc9AnwZx7p1LK0BLLm1BXRpkHL1zaB3oXNE21KHjgCYZ6UwB2u6dQ9t1nG3ZoW2oQ8/SjOM1U94sf9ZRLqoZ6M8Ayr1zZwVmyZ1tqDuDTKN37qwDnet5AHXnUEww9jBPCokUsAe9c+hBHeuB7NADqEPT4IYGNGJr5rxZHq3jXNQ00KNBnHvn0grQkksPoC4NNo/eObUOdq7qPahTOzHhU5Wm93rn0Xt1lPdkj96DerQfB+66IW+WQesgF6UMNGg95N65s4Ky5M57UHcGGEbvfFmHORfzEOzLmD/95kSEK0gPe2fNwzrQQ9mah1BrTrZbSLdoUK82hr1zaB3roqiBDg1m3TujVsCWjHoINmqQg/TOq3Wkc1mPoF7tE59xub63xHnUO6ce1WEeyU49At/o8PGEBton4KPeObWOdVHS0JsdUNa9c2oFbMmpR1CnhvhH73xaxzkX9T7UpwUGMo2Y6oK43zuj3q/jvC8b9T7UqIlPw7VT3iyL1lEuqhlo0QDKvTNnBWbJnPeh5gwyjd65sw50rucx1J29p98n1FFdBce9M+dxHeaxbM5jqDl79JrwSPn9e9w7e9ZxLsoZaM8gzr0zaAVoyaDHUIOG+Ebv/FnHeSFoZILvcsRCz4rERtFT72pXzBrMzywsGTMg4Y66eM2QN6xsRQe5qGVovp0Ocv8qVhSUy86ca7sFx+hfsYqOc65mcG2hS0KHBMnG3SrYPSwtrKsMQnJtIQLXFuJNQb1hJq1DXZQ10KSBqPtn1QrWklWDqwuhFtI/v9bBzoUNri5koRNrshtR/8oLUV2VEJLrCxG4vtCLf1kz4w2zaR3jopqhNzo0jPvnzwrIkj+D6wphltE/d9ahzvUMriyc/1qOgnP/6gpRXYkQkgsLEbiw8ORgzYg3zJl1iItKBjqzBnH/jFnBWDJmcEkhwC3658o6zs9aln8b4NDDYSjv94MAKenZD5/pt/sx8328y9uv1Jwdc2WbQapTc/RykxF/mi/d6QfJ28+0xXh+dpcYZx+uFRkr9N8cMkz9L4Sc6VbaDgUBbkvzKFa5yWLHDwmx1UkZ6zZCQfL+HO0QrhSx1U0R63bmQPKOEXrEJJwmv3qp3zJCRmx3UsS63SKQvI1BO4QrRWx3U8S6DQyQXFSvRxxR4k8BJfUy4UEnNayrpkdykXcrgCslPOimhHWV3UiuOQas2FgQOlR9R39RXCtR3uukjHU1x0iuhm0NcqWU97opZV0xLJJrNPWUw/gaBHpYreZhJ9Wsq89Ecslgm5wrBT3spqB1FYNILmVDgL1kQJxH1XoedVLPuio2JBdWtYi5Us6jbspZV1iF5IIfiG9MOQah3q9W9H4nFa0r+kFyNUq7pCtFvd9NUevqUZBcKAExj4h4tOqnm6uKJWTO404qWlcngeT0/RYxV8p53E0569L3kZxXrueMeURvqIDs6bPLJcp5xm+3npLoEsuRnPLcGuUqLeeJ1h17TqLLeEZyFi4CVMyDEnBlwh192qfLvUVyPmgbgCsl3NVHfbokUCSnJsLvHCkve6j6eR/q5vM+bXYikhPn2sNcKeeOPvTTZs0hOZ1Lz/k29nHA9CldMuJuPvTTZnMhOdOoFcKVIu7oQz9tktEz4kVvyzlGlyzmDjkTvL05/sILOcX8qJwgcTzMiXt8P8ViNu6hOAsTxh8OWRxEhoWWW55PCccR4/MWg+UGBWrzNnvLbdLw5++K8LPwCrSXI0x/kDcNrdhuWVxJuzjf7Wl+8Pyn7gBHpw2XDpfhVEwvy2F8PkVl5j9hnyQnm86oG2OvYlyzMNoRZKJHcWHzwecgXViIz/OQjk+y6wDHi2ZLhxZ+C1FCo8y6WwlZkm6YzUCZprriIL8WwiQLFS38RN3h/DAavOy4hYVKTP/17+yVA887ouFnRoMofXNhqMmbPvGvxYk0viu5cflkVWlbEsD3YsT/A7GtQnU='
10
+
11
+ def main() -> None:
12
+ data = zlib.decompress(base64.b64decode(PAYLOAD))
13
+ digest = hashlib.sha256(data).hexdigest()
14
+ if digest != EXPECTED:
15
+ raise SystemExit(f"hash mismatch: {digest} != {EXPECTED}")
16
+ OUT.parent.mkdir(parents=True, exist_ok=True)
17
+ OUT.write_bytes(data)
18
+ print(f"OK {OUT} ({len(data)} bytes) sha256={digest}")
19
+
20
+ if __name__ == "__main__":
21
+ main()
measure_invariance.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Invariancia interna no trivial (con control negativo).
3
+
4
+ Mide autonomía *y* distingue el grafo canónico de uno corrompido:
5
+
6
+ 1. Auto-regeneración: etiqueta ≡ regla (fase, pos) aplicada al par.
7
+ 2. Invariancia bajo índice de tríada.
8
+ 3. Reconstrucción desde subconjunto (LOO feature lookup sin etiquetas del held-out).
9
+ 4. **Control negativo:** al corromper una arista del grafo, (1) o (3) debe fallar.
10
+
11
+ Sin el control negativo, un 1.0 podría ser tautología.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import copy
16
+ import csv
17
+ import json
18
+ from collections import defaultdict
19
+ from pathlib import Path
20
+
21
+ ROOT = Path(__file__).resolve().parents[1]
22
+
23
+
24
+ def parse_node(node_id: str) -> tuple[str, int]:
25
+ parts = node_id.split("_")
26
+ return parts[1], int(parts[2][1:])
27
+
28
+
29
+ def rule_label(src: str, tgt: str) -> str:
30
+ sp, spos = parse_node(src)
31
+ tp, tpos = parse_node(tgt)
32
+ if sp == tp:
33
+ return "none"
34
+ if tpos == 2 - spos:
35
+ return "mirrorOf"
36
+ if (spos in (0, 2) and tpos == 1) or (spos == 1 and tpos in (0, 2)):
37
+ return "creates"
38
+ return "none"
39
+
40
+
41
+ def feature_key(src: str, tgt: str) -> tuple:
42
+ sp, spos = parse_node(src)
43
+ tp, tpos = parse_node(tgt)
44
+ return (sp, spos, tp, tpos)
45
+
46
+
47
+ def self_regen_rate(rows: list[dict]) -> float:
48
+ mism = sum(1 for r in rows if rule_label(r["source"], r["target"]) != r["relation"])
49
+ return 1.0 - mism / max(len(rows), 1)
50
+
51
+
52
+ def triad_invariant(rows: list[dict]) -> bool:
53
+ by_feat: dict[tuple, set[str]] = defaultdict(set)
54
+ for r in rows:
55
+ by_feat[feature_key(r["source"], r["target"])].add(r["relation"])
56
+ return all(len(v) == 1 for v in by_feat.values())
57
+
58
+
59
+ def subset_reconstruction(rows: list[dict]) -> bool:
60
+ for held in range(1, 14):
61
+ train: dict[tuple, str] = {}
62
+ test: list[tuple[tuple, str]] = []
63
+ for r in rows:
64
+ key = feature_key(r["source"], r["target"])
65
+ tid = int(r["triad_index"])
66
+ if tid == held:
67
+ test.append((key, r["relation"]))
68
+ else:
69
+ train[key] = r["relation"]
70
+ if any(train.get(k) != lab for k, lab in test):
71
+ return False
72
+ return True
73
+
74
+
75
+ def corrupt_one_edge(rows: list[dict]) -> list[dict]:
76
+ """Cambia la etiqueta de la primera arista mirrorOf a none (grafo inválido)."""
77
+ out = copy.deepcopy(rows)
78
+ for r in out:
79
+ if r["relation"] == "mirrorOf":
80
+ r["relation"] = "none"
81
+ break
82
+ return out
83
+
84
+
85
+ def main() -> int:
86
+ rows = list(
87
+ csv.DictReader(
88
+ (ROOT / "datasets" / "relation_candidates.csv").open(
89
+ encoding="utf-8", newline=""
90
+ )
91
+ )
92
+ )
93
+
94
+ regen = self_regen_rate(rows)
95
+ inv = triad_invariant(rows)
96
+ subset = subset_reconstruction(rows)
97
+
98
+ corrupted = corrupt_one_edge(rows)
99
+ # Tras corrupción: o bien auto-regeneración cae, o el grafo ya no coincide con la regla
100
+ corrupted_regen = self_regen_rate(corrupted)
101
+ negative_control_detects = corrupted_regen < 1.0
102
+
103
+ autonomy = regen == 1.0 and inv and subset
104
+ non_trivial = autonomy and negative_control_detects
105
+
106
+ report = {
107
+ "framing": (
108
+ "Invariancia no trivial: el canónico regenera 1.0; un grafo con una "
109
+ "arista corrupta debe fallar el control negativo."
110
+ ),
111
+ "canonical": {
112
+ "self_regeneration_rate": round(regen, 6),
113
+ "triad_index_invariance": inv,
114
+ "subset_reconstruction": subset,
115
+ "autonomy_measurable": autonomy,
116
+ },
117
+ "negative_control": {
118
+ "description": "primera arista mirrorOf relabelada a none",
119
+ "corrupted_self_regeneration_rate": round(corrupted_regen, 6),
120
+ "detects_corruption": negative_control_detects,
121
+ "interpretation": (
122
+ "si detects_corruption es false, la métrica no distingue "
123
+ "grafo correcto de corrompido (tautología)"
124
+ ),
125
+ },
126
+ "invariance_non_trivial": non_trivial,
127
+ }
128
+
129
+ out = ROOT / "experiments" / "results" / "invariance_metrics.json"
130
+ out.parent.mkdir(parents=True, exist_ok=True)
131
+ out.write_text(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
132
+
133
+ print("Invariancia interna (con control negativo)")
134
+ print(f" Auto-regeneración canónica: {regen}")
135
+ print(f" Invariancia bajo índice de tríada: {inv}")
136
+ print(f" Reconstrucción desde subconjunto: {subset}")
137
+ print(f" Control negativo detecta corrupción: {negative_control_detects} (rate={corrupted_regen:.6f})")
138
+ print(f" Invariancia no trivial: {non_trivial}")
139
+ print(f" Informe: {out}")
140
+ return 0 if non_trivial else 1
141
+
142
+
143
+ if __name__ == "__main__":
144
+ raise SystemExit(main())
migrate_spec.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Aplica migraciones declarativas a data/iom_spec.json.
3
+
4
+ Las migraciones se registran en el campo `migrations` del propio JSON.
5
+ Este script solo registra y valida; las transformaciones semánticas futuras
6
+ deben implementarse como funciones nombradas en MIGRATION_HANDLERS.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ from pathlib import Path
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ SPEC_PATH = ROOT / "data" / "iom_spec.json"
16
+
17
+ # Handlers de migración (from_version -> función). Vacío en 1.1.0 porque el
18
+ # cambio fue solo metadatos.
19
+ MIGRATION_HANDLERS: dict[str, callable] = {}
20
+
21
+
22
+ def load() -> dict:
23
+ return json.loads(SPEC_PATH.read_text(encoding="utf-8"))
24
+
25
+
26
+ def save(data: dict) -> None:
27
+ SPEC_PATH.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
28
+
29
+
30
+ def list_migrations(data: dict) -> None:
31
+ migrations = data.get("migrations") or []
32
+ if not migrations:
33
+ print("No hay migraciones registradas.")
34
+ return
35
+ for m in migrations:
36
+ print(f" {m['from_version']} -> {m['to_version']}: {m['description']} ({m.get('date', '?')})")
37
+
38
+
39
+ def main() -> None:
40
+ parser = argparse.ArgumentParser(description="Gestión de migraciones de iom_spec.json")
41
+ parser.add_argument("--list", action="store_true", help="Listar migraciones registradas")
42
+ parser.add_argument("--check", action="store_true", help="Verificar que spec_version es coherente")
43
+ args = parser.parse_args()
44
+
45
+ data = load()
46
+ if args.list:
47
+ print(f"spec_version actual: {data.get('spec_version')}")
48
+ list_migrations(data)
49
+ return
50
+ if args.check:
51
+ version = data.get("spec_version")
52
+ migrations = data.get("migrations") or []
53
+ if migrations:
54
+ last = migrations[-1]["to_version"]
55
+ if last != version:
56
+ raise SystemExit(f"Inconsistencia: último to_version={last} pero spec_version={version}")
57
+ print(f"OK: spec_version={version} coherente con historial de migraciones")
58
+ return
59
+ parser.print_help()
60
+
61
+
62
+ if __name__ == "__main__":
63
+ main()
package_reproducible.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Empaqueta los artefactos reproducibles, excluyendo cachés y el checkout Git."""
3
+ from pathlib import Path
4
+ from zipfile import ZIP_DEFLATED, ZipFile
5
+
6
+ ROOT = Path(__file__).resolve().parents[1]
7
+ INCLUDE = [
8
+ "README.md", "AUDITORIA.md", "EXPERIMENTOS.md", "REPRODUCCION.md", "paper.md", "LICENSE", "MANIFEST.sha256",
9
+ "IOM.lean", "IOM", "lakefile.lean", "lake-manifest.json", "lean-toolchain", "requirements.txt", "requirements-lock.txt",
10
+ "data", "datasets", "experiments/config.json", "experiments/optional", "experiments/results",
11
+ "experiments/logs", "ontology", "scripts", "tests", ".github/workflows/ci.yml",
12
+ ]
13
+
14
+ def files_in(path: Path):
15
+ if path.is_file():
16
+ yield path
17
+ elif path.is_dir():
18
+ for p in path.rglob("*"):
19
+ if p.is_file() and ".git" not in p.parts:
20
+ yield p
21
+
22
+ def main() -> None:
23
+ out = ROOT / "iom-reproducible.zip"
24
+ with ZipFile(out, "w", ZIP_DEFLATED) as zf:
25
+ for rel in INCLUDE:
26
+ for p in files_in(ROOT / rel):
27
+ zf.write(p, p.relative_to(ROOT).as_posix())
28
+ print(f"Escrito {out}")
29
+
30
+ if __name__ == "__main__":
31
+ main()
paper.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IOM — construcción formal de la unidad informativa
2
+
3
+ Este informe describe el repositorio IOM como una **construcción formal de
4
+ unidad informativa**: estructura autocontenida de distinciones, relaciones,
5
+ integración y transformación, verificable desde `data/iom_spec.json` (punto
6
+ fijo, Lean, SHACL). La autonomía verificable es el *mecanismo* de constitución
7
+ y validación; anotadores, dominios y learners de recuperación de reglas son
8
+ **encuentro**, no fundamento.
9
+
10
+ Referencia conceptual: [`docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md) · Spec: [`data/iom_spec.json`](data/iom_spec.json) · Jerarquía: [`EXPERIMENTOS.md`](EXPERIMENTOS.md).
11
+
12
+ ## Propósito
13
+
14
+ La unidad informativa es la mínima estructura autocontenida capaz de conservar una distinción, relacionarla con su opuesto, integrarla en un sistema y transformarse sin perder la trazabilidad de su identidad.
15
+
16
+ Las 13 tríadas son modos de composición de esa unidad.
17
+
18
+ ## Núcleo (fundamento)
19
+
20
+ 1. Punto fijo: `self_bootstrap.py --passes 2`
21
+ 2. SelfGenesis / FormalRules / InformationalUnit: `lake build`
22
+ 3. SHACL sobre TTL regenerado
23
+ 4. Invariancia no trivial (`measure_invariance.py`)
24
+
25
+ ## Encuentro (no fundamenta)
26
+
27
+ EXP-E (dominio / Mictlán) y EXP-A (κ) son proyección provisional. Sin
28
+ `ACCESS_LOG`, κ histórico no se declara demostración cerrada.
29
+
30
+ ## Diagnóstico circular (opcional)
31
+
32
+ PI-HGAT-T y baselines (`experiments/optional/`) recuperan etiquetas que **ya
33
+ están** en (fase, posición). Accuracy 1.0 es tautología informativa, no validez
34
+ del marco en el mundo. PyTorch no es dependencia del núcleo.
35
+
36
+ ## Límite de la afirmación
37
+
38
+ El repositorio **implementa** una construcción formal de unidad informativa.
39
+ No afirma por sí solo una unidad absoluta independiente del entorno de
40
+ ejecución. La validez interna se mide por derivabilidad y trazabilidad desde
41
+ la especificación canónica.
pi_hgat_t.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PI-HGAT-T y ablaciones: evaluación empírica estructural de tríadas IOM.
3
+
4
+ PI-HGAT-T es la implementación de referencia del clasificador de relaciones del marco.
5
+ Las etiquetas de clase proceden de reglas RDF/SHACL explícitas y se evalúan bajo
6
+ leave-one-triad-out, ablaciones y baselines.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import csv
11
+ import json
12
+ import platform
13
+ import random
14
+ import time
15
+ from pathlib import Path
16
+
17
+ import torch
18
+ from torch import nn
19
+ from torch.nn import functional as F
20
+
21
+ ROOT = Path(__file__).resolve().parents[2]
22
+ CONFIG = json.loads((ROOT / "experiments" / "config.json").read_text(encoding="utf-8"))
23
+ CLASSES = ("none", "mirrorOf", "creates")
24
+ CLASS_ID = {name: i for i, name in enumerate(CLASSES)}
25
+
26
+
27
+ def seed_everything(seed: int) -> None:
28
+ random.seed(seed)
29
+ torch.manual_seed(seed)
30
+ torch.use_deterministic_algorithms(True)
31
+ torch.set_num_threads(1)
32
+
33
+
34
+ def features_for_node(node_id: str) -> list[float]:
35
+ """Codifica solo la fase y posición, sin etiqueta léxica ni número de tríada."""
36
+ parts = node_id.split("_")
37
+ phase, position = parts[1], int(parts[2][1:])
38
+ return [float(phase == "adv"), float(phase == "ret"),
39
+ float(position == 0), float(position == 1), float(position == 2)]
40
+
41
+
42
+ def parse_pair_index(node_id: str) -> int:
43
+ phase = node_id.split("_")[1]
44
+ position = int(node_id.split("_")[2][1:])
45
+ return position if phase == "adv" else 3 + position
46
+
47
+
48
+ def read_data():
49
+ nodes: dict[int, list[list[float]]] = {i: [None] * 6 for i in range(1, 14)}
50
+ with (ROOT / "datasets" / "triad_nodes.csv").open(encoding="utf-8", newline="") as handle:
51
+ for row in csv.DictReader(handle):
52
+ nodes[int(row["triad_index"])][parse_pair_index(row["node_id"])] = features_for_node(row["node_id"])
53
+ pairs: dict[int, list[tuple[int, int, int]]] = {i: [] for i in range(1, 14)}
54
+ with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as handle:
55
+ for row in csv.DictReader(handle):
56
+ pairs[int(row["triad_index"])].append((parse_pair_index(row["source"]),
57
+ parse_pair_index(row["target"]),
58
+ CLASS_ID[row["relation"]]))
59
+ assert all(all(feature is not None for feature in group) for group in nodes.values())
60
+ return {k: torch.tensor(v, dtype=torch.float32) for k, v in nodes.items()}, pairs
61
+
62
+
63
+ class TypedGraphAttention(nn.Module):
64
+ """Atención multi-cabeza sobre los seis nodos de las dos fases de cada tríada."""
65
+ def __init__(self, dim: int, heads: int):
66
+ super().__init__()
67
+ assert dim % heads == 0
68
+ self.dim, self.heads, self.head_dim = dim, heads, dim // heads
69
+ self.query = nn.Linear(dim, dim, bias=False)
70
+ self.key = nn.Linear(dim, dim, bias=False)
71
+ self.value = nn.Linear(dim, dim, bias=False)
72
+ self.out = nn.Linear(dim, dim)
73
+ self.norm = nn.LayerNorm(dim)
74
+
75
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
76
+ batch, n_nodes, _ = x.shape
77
+ def split(layer):
78
+ return layer(x).view(batch, n_nodes, self.heads, self.head_dim).transpose(1, 2)
79
+ q, k, v = split(self.query), split(self.key), split(self.value)
80
+ scores = torch.matmul(q, k.transpose(-2, -1)) / (self.head_dim ** 0.5)
81
+ weights = torch.softmax(scores, dim=-1)
82
+ attended = torch.matmul(weights, v).transpose(1, 2).contiguous().view(batch, n_nodes, self.dim)
83
+ return self.norm(x + self.out(attended))
84
+
85
+
86
+ class PIHGATT(nn.Module):
87
+ """Codificador GAT de dos capas y decodificador para relación dirigida."""
88
+ def __init__(self, dim: int = 32, heads: int = 4, input_dim: int = 5):
89
+ super().__init__()
90
+ self.encoder = nn.Linear(input_dim, dim)
91
+ self.attention1 = TypedGraphAttention(dim, heads)
92
+ self.attention2 = TypedGraphAttention(dim, heads)
93
+ self.decoder = nn.Sequential(nn.Linear(dim * 3, dim), nn.GELU(), nn.Linear(dim, len(CLASSES)))
94
+
95
+ def encode(self, x: torch.Tensor) -> torch.Tensor:
96
+ h = F.gelu(self.encoder(x))
97
+ h = F.gelu(self.attention1(h))
98
+ return self.attention2(h)
99
+
100
+ def forward(self, x: torch.Tensor, pairs: torch.Tensor) -> torch.Tensor:
101
+ h = self.encode(x)
102
+ src, dst = pairs[:, 0], pairs[:, 1]
103
+ left, right = h[:, src, :], h[:, dst, :]
104
+ return self.decoder(torch.cat((left, right, left * right), dim=-1))
105
+
106
+
107
+ def admissible_relation(label: str, source: int, target: int) -> bool:
108
+ """Predicados de validez alineados con io:mirrorOf / io:creates en SHACL."""
109
+ source_phase, source_pos = (0 if source < 3 else 1), source % 3
110
+ target_phase, target_pos = (0 if target < 3 else 1), target % 3
111
+ if source_phase == target_phase:
112
+ return False
113
+ if label == "mirrorOf":
114
+ return target_pos == 2 - source_pos
115
+ if label == "creates":
116
+ return (source_pos in (0, 2) and target_pos == 1) or (source_pos == 1 and target_pos in (0, 2))
117
+ return True
118
+
119
+
120
+ def scores(gold: list[int], predicted: list[int]) -> dict:
121
+ matrix = [[0] * len(CLASSES) for _ in CLASSES]
122
+ for actual, guess in zip(gold, predicted):
123
+ matrix[actual][guess] += 1
124
+ per_class, f1_values = {}, []
125
+ for idx, name in enumerate(CLASSES):
126
+ tp = matrix[idx][idx]
127
+ fp = sum(matrix[row][idx] for row in range(len(CLASSES)) if row != idx)
128
+ fn = sum(matrix[idx][col] for col in range(len(CLASSES)) if col != idx)
129
+ precision = tp / (tp + fp) if tp + fp else 0.0
130
+ recall = tp / (tp + fn) if tp + fn else 0.0
131
+ f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
132
+ per_class[name] = {"precision": precision, "recall": recall, "f1": f1, "support": tp + fn}
133
+ f1_values.append(f1)
134
+ accuracy = sum(a == b for a, b in zip(gold, predicted)) / len(gold)
135
+ return {"accuracy": accuracy, "macro_f1": sum(f1_values) / len(f1_values),
136
+ "per_class": per_class, "confusion_matrix_rows_gold_cols_predicted": matrix}
137
+
138
+
139
+ def run_variant(name: str, columns: list[int], nodes, relations, cfg: dict) -> dict:
140
+ all_gold, all_pred, predicted_edges, fold_results = [], [], [], []
141
+ pair_indices = torch.tensor([(s, t) for s in range(6) for t in range(6) if s != t], dtype=torch.long)
142
+ for held_out in sorted(nodes):
143
+ seed_everything(int(cfg["seed"]) + held_out - 1)
144
+ train_ids = [i for i in nodes if i != held_out]
145
+ x_train = torch.stack([nodes[i][:, columns] for i in train_ids])
146
+ y_train = torch.tensor([label for i in train_ids for _s, _t, label in relations[i]], dtype=torch.long)
147
+ model = PIHGATT(int(cfg["hidden_dim"]), int(cfg["attention_heads"]), input_dim=len(columns))
148
+ counts = torch.bincount(y_train, minlength=len(CLASSES)).float()
149
+ class_weights = (len(y_train) / (len(CLASSES) * counts.clamp_min(1))).float()
150
+ optimizer = torch.optim.AdamW(model.parameters(), lr=float(cfg["learning_rate"]),
151
+ weight_decay=float(cfg["weight_decay"]))
152
+ model.train()
153
+ for _epoch in range(int(cfg["epochs"])):
154
+ optimizer.zero_grad(set_to_none=True)
155
+ logits = model(x_train, pair_indices).reshape(-1, len(CLASSES))
156
+ loss = F.cross_entropy(logits, y_train, weight=class_weights)
157
+ loss.backward()
158
+ optimizer.step()
159
+ model.eval()
160
+ with torch.no_grad():
161
+ predicted = model(nodes[held_out][:, columns].unsqueeze(0), pair_indices).argmax(dim=-1).reshape(-1).tolist()
162
+ gold_map = {(src, dst): label for src, dst, label in relations[held_out]}
163
+ gold = [gold_map[(src, dst)] for src, dst in pair_indices.tolist()]
164
+ all_gold.extend(gold)
165
+ all_pred.extend(predicted)
166
+ for (src, dst), label_id in zip(pair_indices.tolist(), predicted):
167
+ if label_id:
168
+ label = CLASSES[label_id]
169
+ predicted_edges.append((held_out, src, dst, label))
170
+ fold_results.append({"held_out_triad": held_out,
171
+ "accuracy": sum(a == b for a, b in zip(gold, predicted)) / len(gold)})
172
+ report = scores(all_gold, all_pred)
173
+ by_class = report["per_class"]
174
+ compliant = sum(admissible_relation(label, source, target)
175
+ for _triad, source, target, label in predicted_edges)
176
+ edge_compliance = compliant / len(predicted_edges) if predicted_edges else 1.0
177
+ metrics = {
178
+ "candidate_relation_accuracy": {"value": report["accuracy"], "property": "io:mirrorOf / io:creates; exact three-class labels"},
179
+ "relation_macro_f1": {"value": report["macro_f1"], "property": "balanced F1 for none, io:mirrorOf and io:creates"},
180
+ "mirrorOf_precision": {"value": by_class["mirrorOf"]["precision"], "property": "SHACL: reciprocal mirror; same triad; opposite phase; position reflection"},
181
+ "mirrorOf_recall": {"value": by_class["mirrorOf"]["recall"], "property": "completeness of the io:mirrorOf edge set"},
182
+ "mirrorOf_f1": {"value": by_class["mirrorOf"]["f1"], "property": "precision/recall of io:mirrorOf"},
183
+ "creates_precision": {"value": by_class["creates"]["precision"], "property": "SHACL: same triad, opposite phase, four allowed position rules"},
184
+ "creates_recall": {"value": by_class["creates"]["recall"], "property": "completeness of four creation rules"},
185
+ "creates_f1": {"value": by_class["creates"]["f1"], "property": "precision/recall of io:creates"},
186
+ "predicted_edge_rule_conformance": {"value": edge_compliance, "property": "SHACL phase/triad/position rules for predicted mirrorOf and creates", "predicted_edges": len(predicted_edges)},
187
+ }
188
+ return {"variant": name, "feature_columns": columns, "metrics": metrics,
189
+ "per_class": by_class, "confusion_matrix_rows_gold_cols_predicted": report["confusion_matrix_rows_gold_cols_predicted"],
190
+ "folds": fold_results}
191
+
192
+
193
+ def run() -> dict:
194
+ cfg = CONFIG
195
+ nodes, relations = read_data()
196
+ candidates = [
197
+ ("PI-HGAT-T_full_phase_and_position", [0, 1, 2, 3, 4]),
198
+ ("ablation_without_phase", [2, 3, 4]),
199
+ ("ablation_without_position", [0, 1]),
200
+ ]
201
+ start = time.time()
202
+ variants = [run_variant(name, columns, nodes, relations, cfg) for name, columns in candidates]
203
+ primary = variants[0]
204
+ gold_labels = [label for triad in relations.values() for _src, _dst, label in triad]
205
+ dataset = {"triads": 13, "nodes": 78, "directed_relation_candidates": len(gold_labels),
206
+ "gold_mirrorOf_edges": sum(label == CLASS_ID["mirrorOf"] for label in gold_labels),
207
+ "gold_creates_edges": sum(label == CLASS_ID["creates"] for label in gold_labels),
208
+ "gold_none_pairs": sum(label == CLASS_ID["none"] for label in gold_labels)}
209
+ report = {
210
+ "model": cfg["model_id"],
211
+ "model_definition": cfg["model_definition"],
212
+ "dataset": dataset,
213
+ "validation": "13-fold leave-one-triad-out; no lexical labels or triad index as model features",
214
+ "primary_metrics": primary["metrics"],
215
+ "experiments": variants,
216
+ "threshold_policy": "Empirical evaluation against deterministic RDF/SHACL target properties. Reference criterion is exact reconstruction (1.0); observed model and ablation scores quantify recoverability under leave-one-triad-out and are reported with confusion matrices and fold variability.",
217
+ "software": {"python": platform.python_version(), "pytorch": torch.__version__, "platform": platform.platform()},
218
+ "configuration": cfg,
219
+ }
220
+ results_path = ROOT / "experiments" / "results" / "pi_hgat_t_metrics.json"
221
+ results_path.parent.mkdir(parents=True, exist_ok=True)
222
+ results_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
223
+ log_path = ROOT / "experiments" / "logs" / "pi_hgat_t.log"
224
+ log_path.parent.mkdir(parents=True, exist_ok=True)
225
+ lines = ["PI-HGAT-T / ablation suite", f"Python={platform.python_version()} PyTorch={torch.__version__}",
226
+ f"seed={cfg['seed']} folds=13 epochs={cfg['epochs']} candidates={len(gold_labels)}"]
227
+ for variant in variants:
228
+ m = variant["metrics"]
229
+ lines.append(f"{variant['variant']}: accuracy={m['candidate_relation_accuracy']['value']:.6f} macro_f1={m['relation_macro_f1']['value']:.6f} "
230
+ f"mirrorOf_f1={m['mirrorOf_f1']['value']:.6f} creates_f1={m['creates_f1']['value']:.6f} "
231
+ f"rule_conformance={m['predicted_edge_rule_conformance']['value']:.6f}")
232
+ lines.append(f"runtime_seconds={time.time() - start:.3f}")
233
+ log_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
234
+ print("\n".join(lines))
235
+ print(f"Resultados: {results_path}")
236
+ return report
237
+
238
+
239
+ if __name__ == "__main__":
240
+ run()
plantilla_dominio.csv ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ external_id,external_label,mapped_node_id,perspective,phase,position,relation_candidate,notes
2
+ # Obligatorio: external_id, external_label
3
+ # mapped_node_id: uno de los 78 node_id de datasets/triad_nodes.csv (ej. T01_adv_P0)
4
+ # perspective: Ind | D | Tot | Evol | Invol
5
+ # phase: adv | ret
6
+ # position: left | center | right
7
+ # relation_candidate: none | mirrorOf | creates (opcional; se valida contra reglas)
8
+ # notes: texto libre
9
+ ejemplo_01,mi_concepto,T01_adv_P0,Ind,adv,left,none,"Descripción breve del mapeo"
relation_candidates.csv ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ triad_index,source,target,relation
2
+ 1,T01_adv_P0,T01_adv_P1,none
3
+ 1,T01_adv_P0,T01_adv_P2,none
4
+ 1,T01_adv_P0,T01_ret_P0,none
5
+ 1,T01_adv_P0,T01_ret_P1,creates
6
+ 1,T01_adv_P0,T01_ret_P2,mirrorOf
7
+ 1,T01_adv_P1,T01_adv_P0,none
8
+ 1,T01_adv_P1,T01_adv_P2,none
9
+ 1,T01_adv_P1,T01_ret_P0,creates
10
+ 1,T01_adv_P1,T01_ret_P1,mirrorOf
11
+ 1,T01_adv_P1,T01_ret_P2,creates
12
+ 1,T01_adv_P2,T01_adv_P0,none
13
+ 1,T01_adv_P2,T01_adv_P1,none
14
+ 1,T01_adv_P2,T01_ret_P0,mirrorOf
15
+ 1,T01_adv_P2,T01_ret_P1,creates
16
+ 1,T01_adv_P2,T01_ret_P2,none
17
+ 1,T01_ret_P0,T01_adv_P0,none
18
+ 1,T01_ret_P0,T01_adv_P1,creates
19
+ 1,T01_ret_P0,T01_adv_P2,mirrorOf
20
+ 1,T01_ret_P0,T01_ret_P1,none
21
+ 1,T01_ret_P0,T01_ret_P2,none
22
+ 1,T01_ret_P1,T01_adv_P0,creates
23
+ 1,T01_ret_P1,T01_adv_P1,mirrorOf
24
+ 1,T01_ret_P1,T01_adv_P2,creates
25
+ 1,T01_ret_P1,T01_ret_P0,none
26
+ 1,T01_ret_P1,T01_ret_P2,none
27
+ 1,T01_ret_P2,T01_adv_P0,mirrorOf
28
+ 1,T01_ret_P2,T01_adv_P1,creates
29
+ 1,T01_ret_P2,T01_adv_P2,none
30
+ 1,T01_ret_P2,T01_ret_P0,none
31
+ 1,T01_ret_P2,T01_ret_P1,none
32
+ 2,T02_adv_P0,T02_adv_P1,none
33
+ 2,T02_adv_P0,T02_adv_P2,none
34
+ 2,T02_adv_P0,T02_ret_P0,none
35
+ 2,T02_adv_P0,T02_ret_P1,creates
36
+ 2,T02_adv_P0,T02_ret_P2,mirrorOf
37
+ 2,T02_adv_P1,T02_adv_P0,none
38
+ 2,T02_adv_P1,T02_adv_P2,none
39
+ 2,T02_adv_P1,T02_ret_P0,creates
40
+ 2,T02_adv_P1,T02_ret_P1,mirrorOf
41
+ 2,T02_adv_P1,T02_ret_P2,creates
42
+ 2,T02_adv_P2,T02_adv_P0,none
43
+ 2,T02_adv_P2,T02_adv_P1,none
44
+ 2,T02_adv_P2,T02_ret_P0,mirrorOf
45
+ 2,T02_adv_P2,T02_ret_P1,creates
46
+ 2,T02_adv_P2,T02_ret_P2,none
47
+ 2,T02_ret_P0,T02_adv_P0,none
48
+ 2,T02_ret_P0,T02_adv_P1,creates
49
+ 2,T02_ret_P0,T02_adv_P2,mirrorOf
50
+ 2,T02_ret_P0,T02_ret_P1,none
51
+ 2,T02_ret_P0,T02_ret_P2,none
52
+ 2,T02_ret_P1,T02_adv_P0,creates
53
+ 2,T02_ret_P1,T02_adv_P1,mirrorOf
54
+ 2,T02_ret_P1,T02_adv_P2,creates
55
+ 2,T02_ret_P1,T02_ret_P0,none
56
+ 2,T02_ret_P1,T02_ret_P2,none
57
+ 2,T02_ret_P2,T02_adv_P0,mirrorOf
58
+ 2,T02_ret_P2,T02_adv_P1,creates
59
+ 2,T02_ret_P2,T02_adv_P2,none
60
+ 2,T02_ret_P2,T02_ret_P0,none
61
+ 2,T02_ret_P2,T02_ret_P1,none
62
+ 3,T03_adv_P0,T03_adv_P1,none
63
+ 3,T03_adv_P0,T03_adv_P2,none
64
+ 3,T03_adv_P0,T03_ret_P0,none
65
+ 3,T03_adv_P0,T03_ret_P1,creates
66
+ 3,T03_adv_P0,T03_ret_P2,mirrorOf
67
+ 3,T03_adv_P1,T03_adv_P0,none
68
+ 3,T03_adv_P1,T03_adv_P2,none
69
+ 3,T03_adv_P1,T03_ret_P0,creates
70
+ 3,T03_adv_P1,T03_ret_P1,mirrorOf
71
+ 3,T03_adv_P1,T03_ret_P2,creates
72
+ 3,T03_adv_P2,T03_adv_P0,none
73
+ 3,T03_adv_P2,T03_adv_P1,none
74
+ 3,T03_adv_P2,T03_ret_P0,mirrorOf
75
+ 3,T03_adv_P2,T03_ret_P1,creates
76
+ 3,T03_adv_P2,T03_ret_P2,none
77
+ 3,T03_ret_P0,T03_adv_P0,none
78
+ 3,T03_ret_P0,T03_adv_P1,creates
79
+ 3,T03_ret_P0,T03_adv_P2,mirrorOf
80
+ 3,T03_ret_P0,T03_ret_P1,none
81
+ 3,T03_ret_P0,T03_ret_P2,none
82
+ 3,T03_ret_P1,T03_adv_P0,creates
83
+ 3,T03_ret_P1,T03_adv_P1,mirrorOf
84
+ 3,T03_ret_P1,T03_adv_P2,creates
85
+ 3,T03_ret_P1,T03_ret_P0,none
86
+ 3,T03_ret_P1,T03_ret_P2,none
87
+ 3,T03_ret_P2,T03_adv_P0,mirrorOf
88
+ 3,T03_ret_P2,T03_adv_P1,creates
89
+ 3,T03_ret_P2,T03_adv_P2,none
90
+ 3,T03_ret_P2,T03_ret_P0,none
91
+ 3,T03_ret_P2,T03_ret_P1,none
92
+ 4,T04_adv_P0,T04_adv_P1,none
93
+ 4,T04_adv_P0,T04_adv_P2,none
94
+ 4,T04_adv_P0,T04_ret_P0,none
95
+ 4,T04_adv_P0,T04_ret_P1,creates
96
+ 4,T04_adv_P0,T04_ret_P2,mirrorOf
97
+ 4,T04_adv_P1,T04_adv_P0,none
98
+ 4,T04_adv_P1,T04_adv_P2,none
99
+ 4,T04_adv_P1,T04_ret_P0,creates
100
+ 4,T04_adv_P1,T04_ret_P1,mirrorOf
101
+ 4,T04_adv_P1,T04_ret_P2,creates
102
+ 4,T04_adv_P2,T04_adv_P0,none
103
+ 4,T04_adv_P2,T04_adv_P1,none
104
+ 4,T04_adv_P2,T04_ret_P0,mirrorOf
105
+ 4,T04_adv_P2,T04_ret_P1,creates
106
+ 4,T04_adv_P2,T04_ret_P2,none
107
+ 4,T04_ret_P0,T04_adv_P0,none
108
+ 4,T04_ret_P0,T04_adv_P1,creates
109
+ 4,T04_ret_P0,T04_adv_P2,mirrorOf
110
+ 4,T04_ret_P0,T04_ret_P1,none
111
+ 4,T04_ret_P0,T04_ret_P2,none
112
+ 4,T04_ret_P1,T04_adv_P0,creates
113
+ 4,T04_ret_P1,T04_adv_P1,mirrorOf
114
+ 4,T04_ret_P1,T04_adv_P2,creates
115
+ 4,T04_ret_P1,T04_ret_P0,none
116
+ 4,T04_ret_P1,T04_ret_P2,none
117
+ 4,T04_ret_P2,T04_adv_P0,mirrorOf
118
+ 4,T04_ret_P2,T04_adv_P1,creates
119
+ 4,T04_ret_P2,T04_adv_P2,none
120
+ 4,T04_ret_P2,T04_ret_P0,none
121
+ 4,T04_ret_P2,T04_ret_P1,none
122
+ 5,T05_adv_P0,T05_adv_P1,none
123
+ 5,T05_adv_P0,T05_adv_P2,none
124
+ 5,T05_adv_P0,T05_ret_P0,none
125
+ 5,T05_adv_P0,T05_ret_P1,creates
126
+ 5,T05_adv_P0,T05_ret_P2,mirrorOf
127
+ 5,T05_adv_P1,T05_adv_P0,none
128
+ 5,T05_adv_P1,T05_adv_P2,none
129
+ 5,T05_adv_P1,T05_ret_P0,creates
130
+ 5,T05_adv_P1,T05_ret_P1,mirrorOf
131
+ 5,T05_adv_P1,T05_ret_P2,creates
132
+ 5,T05_adv_P2,T05_adv_P0,none
133
+ 5,T05_adv_P2,T05_adv_P1,none
134
+ 5,T05_adv_P2,T05_ret_P0,mirrorOf
135
+ 5,T05_adv_P2,T05_ret_P1,creates
136
+ 5,T05_adv_P2,T05_ret_P2,none
137
+ 5,T05_ret_P0,T05_adv_P0,none
138
+ 5,T05_ret_P0,T05_adv_P1,creates
139
+ 5,T05_ret_P0,T05_adv_P2,mirrorOf
140
+ 5,T05_ret_P0,T05_ret_P1,none
141
+ 5,T05_ret_P0,T05_ret_P2,none
142
+ 5,T05_ret_P1,T05_adv_P0,creates
143
+ 5,T05_ret_P1,T05_adv_P1,mirrorOf
144
+ 5,T05_ret_P1,T05_adv_P2,creates
145
+ 5,T05_ret_P1,T05_ret_P0,none
146
+ 5,T05_ret_P1,T05_ret_P2,none
147
+ 5,T05_ret_P2,T05_adv_P0,mirrorOf
148
+ 5,T05_ret_P2,T05_adv_P1,creates
149
+ 5,T05_ret_P2,T05_adv_P2,none
150
+ 5,T05_ret_P2,T05_ret_P0,none
151
+ 5,T05_ret_P2,T05_ret_P1,none
152
+ 6,T06_adv_P0,T06_adv_P1,none
153
+ 6,T06_adv_P0,T06_adv_P2,none
154
+ 6,T06_adv_P0,T06_ret_P0,none
155
+ 6,T06_adv_P0,T06_ret_P1,creates
156
+ 6,T06_adv_P0,T06_ret_P2,mirrorOf
157
+ 6,T06_adv_P1,T06_adv_P0,none
158
+ 6,T06_adv_P1,T06_adv_P2,none
159
+ 6,T06_adv_P1,T06_ret_P0,creates
160
+ 6,T06_adv_P1,T06_ret_P1,mirrorOf
161
+ 6,T06_adv_P1,T06_ret_P2,creates
162
+ 6,T06_adv_P2,T06_adv_P0,none
163
+ 6,T06_adv_P2,T06_adv_P1,none
164
+ 6,T06_adv_P2,T06_ret_P0,mirrorOf
165
+ 6,T06_adv_P2,T06_ret_P1,creates
166
+ 6,T06_adv_P2,T06_ret_P2,none
167
+ 6,T06_ret_P0,T06_adv_P0,none
168
+ 6,T06_ret_P0,T06_adv_P1,creates
169
+ 6,T06_ret_P0,T06_adv_P2,mirrorOf
170
+ 6,T06_ret_P0,T06_ret_P1,none
171
+ 6,T06_ret_P0,T06_ret_P2,none
172
+ 6,T06_ret_P1,T06_adv_P0,creates
173
+ 6,T06_ret_P1,T06_adv_P1,mirrorOf
174
+ 6,T06_ret_P1,T06_adv_P2,creates
175
+ 6,T06_ret_P1,T06_ret_P0,none
176
+ 6,T06_ret_P1,T06_ret_P2,none
177
+ 6,T06_ret_P2,T06_adv_P0,mirrorOf
178
+ 6,T06_ret_P2,T06_adv_P1,creates
179
+ 6,T06_ret_P2,T06_adv_P2,none
180
+ 6,T06_ret_P2,T06_ret_P0,none
181
+ 6,T06_ret_P2,T06_ret_P1,none
182
+ 7,T07_adv_P0,T07_adv_P1,none
183
+ 7,T07_adv_P0,T07_adv_P2,none
184
+ 7,T07_adv_P0,T07_ret_P0,none
185
+ 7,T07_adv_P0,T07_ret_P1,creates
186
+ 7,T07_adv_P0,T07_ret_P2,mirrorOf
187
+ 7,T07_adv_P1,T07_adv_P0,none
188
+ 7,T07_adv_P1,T07_adv_P2,none
189
+ 7,T07_adv_P1,T07_ret_P0,creates
190
+ 7,T07_adv_P1,T07_ret_P1,mirrorOf
191
+ 7,T07_adv_P1,T07_ret_P2,creates
192
+ 7,T07_adv_P2,T07_adv_P0,none
193
+ 7,T07_adv_P2,T07_adv_P1,none
194
+ 7,T07_adv_P2,T07_ret_P0,mirrorOf
195
+ 7,T07_adv_P2,T07_ret_P1,creates
196
+ 7,T07_adv_P2,T07_ret_P2,none
197
+ 7,T07_ret_P0,T07_adv_P0,none
198
+ 7,T07_ret_P0,T07_adv_P1,creates
199
+ 7,T07_ret_P0,T07_adv_P2,mirrorOf
200
+ 7,T07_ret_P0,T07_ret_P1,none
201
+ 7,T07_ret_P0,T07_ret_P2,none
202
+ 7,T07_ret_P1,T07_adv_P0,creates
203
+ 7,T07_ret_P1,T07_adv_P1,mirrorOf
204
+ 7,T07_ret_P1,T07_adv_P2,creates
205
+ 7,T07_ret_P1,T07_ret_P0,none
206
+ 7,T07_ret_P1,T07_ret_P2,none
207
+ 7,T07_ret_P2,T07_adv_P0,mirrorOf
208
+ 7,T07_ret_P2,T07_adv_P1,creates
209
+ 7,T07_ret_P2,T07_adv_P2,none
210
+ 7,T07_ret_P2,T07_ret_P0,none
211
+ 7,T07_ret_P2,T07_ret_P1,none
212
+ 8,T08_adv_P0,T08_adv_P1,none
213
+ 8,T08_adv_P0,T08_adv_P2,none
214
+ 8,T08_adv_P0,T08_ret_P0,none
215
+ 8,T08_adv_P0,T08_ret_P1,creates
216
+ 8,T08_adv_P0,T08_ret_P2,mirrorOf
217
+ 8,T08_adv_P1,T08_adv_P0,none
218
+ 8,T08_adv_P1,T08_adv_P2,none
219
+ 8,T08_adv_P1,T08_ret_P0,creates
220
+ 8,T08_adv_P1,T08_ret_P1,mirrorOf
221
+ 8,T08_adv_P1,T08_ret_P2,creates
222
+ 8,T08_adv_P2,T08_adv_P0,none
223
+ 8,T08_adv_P2,T08_adv_P1,none
224
+ 8,T08_adv_P2,T08_ret_P0,mirrorOf
225
+ 8,T08_adv_P2,T08_ret_P1,creates
226
+ 8,T08_adv_P2,T08_ret_P2,none
227
+ 8,T08_ret_P0,T08_adv_P0,none
228
+ 8,T08_ret_P0,T08_adv_P1,creates
229
+ 8,T08_ret_P0,T08_adv_P2,mirrorOf
230
+ 8,T08_ret_P0,T08_ret_P1,none
231
+ 8,T08_ret_P0,T08_ret_P2,none
232
+ 8,T08_ret_P1,T08_adv_P0,creates
233
+ 8,T08_ret_P1,T08_adv_P1,mirrorOf
234
+ 8,T08_ret_P1,T08_adv_P2,creates
235
+ 8,T08_ret_P1,T08_ret_P0,none
236
+ 8,T08_ret_P1,T08_ret_P2,none
237
+ 8,T08_ret_P2,T08_adv_P0,mirrorOf
238
+ 8,T08_ret_P2,T08_adv_P1,creates
239
+ 8,T08_ret_P2,T08_adv_P2,none
240
+ 8,T08_ret_P2,T08_ret_P0,none
241
+ 8,T08_ret_P2,T08_ret_P1,none
242
+ 9,T09_adv_P0,T09_adv_P1,none
243
+ 9,T09_adv_P0,T09_adv_P2,none
244
+ 9,T09_adv_P0,T09_ret_P0,none
245
+ 9,T09_adv_P0,T09_ret_P1,creates
246
+ 9,T09_adv_P0,T09_ret_P2,mirrorOf
247
+ 9,T09_adv_P1,T09_adv_P0,none
248
+ 9,T09_adv_P1,T09_adv_P2,none
249
+ 9,T09_adv_P1,T09_ret_P0,creates
250
+ 9,T09_adv_P1,T09_ret_P1,mirrorOf
251
+ 9,T09_adv_P1,T09_ret_P2,creates
252
+ 9,T09_adv_P2,T09_adv_P0,none
253
+ 9,T09_adv_P2,T09_adv_P1,none
254
+ 9,T09_adv_P2,T09_ret_P0,mirrorOf
255
+ 9,T09_adv_P2,T09_ret_P1,creates
256
+ 9,T09_adv_P2,T09_ret_P2,none
257
+ 9,T09_ret_P0,T09_adv_P0,none
258
+ 9,T09_ret_P0,T09_adv_P1,creates
259
+ 9,T09_ret_P0,T09_adv_P2,mirrorOf
260
+ 9,T09_ret_P0,T09_ret_P1,none
261
+ 9,T09_ret_P0,T09_ret_P2,none
262
+ 9,T09_ret_P1,T09_adv_P0,creates
263
+ 9,T09_ret_P1,T09_adv_P1,mirrorOf
264
+ 9,T09_ret_P1,T09_adv_P2,creates
265
+ 9,T09_ret_P1,T09_ret_P0,none
266
+ 9,T09_ret_P1,T09_ret_P2,none
267
+ 9,T09_ret_P2,T09_adv_P0,mirrorOf
268
+ 9,T09_ret_P2,T09_adv_P1,creates
269
+ 9,T09_ret_P2,T09_adv_P2,none
270
+ 9,T09_ret_P2,T09_ret_P0,none
271
+ 9,T09_ret_P2,T09_ret_P1,none
272
+ 10,T10_adv_P0,T10_adv_P1,none
273
+ 10,T10_adv_P0,T10_adv_P2,none
274
+ 10,T10_adv_P0,T10_ret_P0,none
275
+ 10,T10_adv_P0,T10_ret_P1,creates
276
+ 10,T10_adv_P0,T10_ret_P2,mirrorOf
277
+ 10,T10_adv_P1,T10_adv_P0,none
278
+ 10,T10_adv_P1,T10_adv_P2,none
279
+ 10,T10_adv_P1,T10_ret_P0,creates
280
+ 10,T10_adv_P1,T10_ret_P1,mirrorOf
281
+ 10,T10_adv_P1,T10_ret_P2,creates
282
+ 10,T10_adv_P2,T10_adv_P0,none
283
+ 10,T10_adv_P2,T10_adv_P1,none
284
+ 10,T10_adv_P2,T10_ret_P0,mirrorOf
285
+ 10,T10_adv_P2,T10_ret_P1,creates
286
+ 10,T10_adv_P2,T10_ret_P2,none
287
+ 10,T10_ret_P0,T10_adv_P0,none
288
+ 10,T10_ret_P0,T10_adv_P1,creates
289
+ 10,T10_ret_P0,T10_adv_P2,mirrorOf
290
+ 10,T10_ret_P0,T10_ret_P1,none
291
+ 10,T10_ret_P0,T10_ret_P2,none
292
+ 10,T10_ret_P1,T10_adv_P0,creates
293
+ 10,T10_ret_P1,T10_adv_P1,mirrorOf
294
+ 10,T10_ret_P1,T10_adv_P2,creates
295
+ 10,T10_ret_P1,T10_ret_P0,none
296
+ 10,T10_ret_P1,T10_ret_P2,none
297
+ 10,T10_ret_P2,T10_adv_P0,mirrorOf
298
+ 10,T10_ret_P2,T10_adv_P1,creates
299
+ 10,T10_ret_P2,T10_adv_P2,none
300
+ 10,T10_ret_P2,T10_ret_P0,none
301
+ 10,T10_ret_P2,T10_ret_P1,none
302
+ 11,T11_adv_P0,T11_adv_P1,none
303
+ 11,T11_adv_P0,T11_adv_P2,none
304
+ 11,T11_adv_P0,T11_ret_P0,none
305
+ 11,T11_adv_P0,T11_ret_P1,creates
306
+ 11,T11_adv_P0,T11_ret_P2,mirrorOf
307
+ 11,T11_adv_P1,T11_adv_P0,none
308
+ 11,T11_adv_P1,T11_adv_P2,none
309
+ 11,T11_adv_P1,T11_ret_P0,creates
310
+ 11,T11_adv_P1,T11_ret_P1,mirrorOf
311
+ 11,T11_adv_P1,T11_ret_P2,creates
312
+ 11,T11_adv_P2,T11_adv_P0,none
313
+ 11,T11_adv_P2,T11_adv_P1,none
314
+ 11,T11_adv_P2,T11_ret_P0,mirrorOf
315
+ 11,T11_adv_P2,T11_ret_P1,creates
316
+ 11,T11_adv_P2,T11_ret_P2,none
317
+ 11,T11_ret_P0,T11_adv_P0,none
318
+ 11,T11_ret_P0,T11_adv_P1,creates
319
+ 11,T11_ret_P0,T11_adv_P2,mirrorOf
320
+ 11,T11_ret_P0,T11_ret_P1,none
321
+ 11,T11_ret_P0,T11_ret_P2,none
322
+ 11,T11_ret_P1,T11_adv_P0,creates
323
+ 11,T11_ret_P1,T11_adv_P1,mirrorOf
324
+ 11,T11_ret_P1,T11_adv_P2,creates
325
+ 11,T11_ret_P1,T11_ret_P0,none
326
+ 11,T11_ret_P1,T11_ret_P2,none
327
+ 11,T11_ret_P2,T11_adv_P0,mirrorOf
328
+ 11,T11_ret_P2,T11_adv_P1,creates
329
+ 11,T11_ret_P2,T11_adv_P2,none
330
+ 11,T11_ret_P2,T11_ret_P0,none
331
+ 11,T11_ret_P2,T11_ret_P1,none
332
+ 12,T12_adv_P0,T12_adv_P1,none
333
+ 12,T12_adv_P0,T12_adv_P2,none
334
+ 12,T12_adv_P0,T12_ret_P0,none
335
+ 12,T12_adv_P0,T12_ret_P1,creates
336
+ 12,T12_adv_P0,T12_ret_P2,mirrorOf
337
+ 12,T12_adv_P1,T12_adv_P0,none
338
+ 12,T12_adv_P1,T12_adv_P2,none
339
+ 12,T12_adv_P1,T12_ret_P0,creates
340
+ 12,T12_adv_P1,T12_ret_P1,mirrorOf
341
+ 12,T12_adv_P1,T12_ret_P2,creates
342
+ 12,T12_adv_P2,T12_adv_P0,none
343
+ 12,T12_adv_P2,T12_adv_P1,none
344
+ 12,T12_adv_P2,T12_ret_P0,mirrorOf
345
+ 12,T12_adv_P2,T12_ret_P1,creates
346
+ 12,T12_adv_P2,T12_ret_P2,none
347
+ 12,T12_ret_P0,T12_adv_P0,none
348
+ 12,T12_ret_P0,T12_adv_P1,creates
349
+ 12,T12_ret_P0,T12_adv_P2,mirrorOf
350
+ 12,T12_ret_P0,T12_ret_P1,none
351
+ 12,T12_ret_P0,T12_ret_P2,none
352
+ 12,T12_ret_P1,T12_adv_P0,creates
353
+ 12,T12_ret_P1,T12_adv_P1,mirrorOf
354
+ 12,T12_ret_P1,T12_adv_P2,creates
355
+ 12,T12_ret_P1,T12_ret_P0,none
356
+ 12,T12_ret_P1,T12_ret_P2,none
357
+ 12,T12_ret_P2,T12_adv_P0,mirrorOf
358
+ 12,T12_ret_P2,T12_adv_P1,creates
359
+ 12,T12_ret_P2,T12_adv_P2,none
360
+ 12,T12_ret_P2,T12_ret_P0,none
361
+ 12,T12_ret_P2,T12_ret_P1,none
362
+ 13,T13_adv_P0,T13_adv_P1,none
363
+ 13,T13_adv_P0,T13_adv_P2,none
364
+ 13,T13_adv_P0,T13_ret_P0,none
365
+ 13,T13_adv_P0,T13_ret_P1,creates
366
+ 13,T13_adv_P0,T13_ret_P2,mirrorOf
367
+ 13,T13_adv_P1,T13_adv_P0,none
368
+ 13,T13_adv_P1,T13_adv_P2,none
369
+ 13,T13_adv_P1,T13_ret_P0,creates
370
+ 13,T13_adv_P1,T13_ret_P1,mirrorOf
371
+ 13,T13_adv_P1,T13_ret_P2,creates
372
+ 13,T13_adv_P2,T13_adv_P0,none
373
+ 13,T13_adv_P2,T13_adv_P1,none
374
+ 13,T13_adv_P2,T13_ret_P0,mirrorOf
375
+ 13,T13_adv_P2,T13_ret_P1,creates
376
+ 13,T13_adv_P2,T13_ret_P2,none
377
+ 13,T13_ret_P0,T13_adv_P0,none
378
+ 13,T13_ret_P0,T13_adv_P1,creates
379
+ 13,T13_ret_P0,T13_adv_P2,mirrorOf
380
+ 13,T13_ret_P0,T13_ret_P1,none
381
+ 13,T13_ret_P0,T13_ret_P2,none
382
+ 13,T13_ret_P1,T13_adv_P0,creates
383
+ 13,T13_ret_P1,T13_adv_P1,mirrorOf
384
+ 13,T13_ret_P1,T13_adv_P2,creates
385
+ 13,T13_ret_P1,T13_ret_P0,none
386
+ 13,T13_ret_P1,T13_ret_P2,none
387
+ 13,T13_ret_P2,T13_adv_P0,mirrorOf
388
+ 13,T13_ret_P2,T13_adv_P1,creates
389
+ 13,T13_ret_P2,T13_adv_P2,none
390
+ 13,T13_ret_P2,T13_ret_P0,none
391
+ 13,T13_ret_P2,T13_ret_P1,none
requirements-lock.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cpu
2
+ attrs==25.3.0
3
+ filelock==4.0.12
4
+ fsspec==2026.9.0
5
+ html5rdf==1.2.1
6
+ Jinja2==3.1.6
7
+ jsonschema==4.23.0
8
+ jsonschema-specifications==2025.4.1
9
+ MarkupSafe==3.0.4
10
+ mpmath==1.3.0
11
+ networkx==3.7
12
+ numpy==1.26.4
13
+ owlrl==7.1.4
14
+ packaging==26.3
15
+ prettytable==3.18.0
16
+ pyparsing==3.3.3
17
+ pyshacl==0.30.1
18
+ rdflib==7.1.4
19
+ referencing==0.36.2
20
+ rpds-py==0.25.1
21
+ setuptools==84.0.0
22
+ sympy==1.13.1
23
+ torch==2.6.0+cpu
24
+ typing_extensions==4.16.0
25
+ wcwidth==0.9.2
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cpu
2
+ rdflib==7.1.4
3
+ pyshacl==0.30.1
4
+ owlrl==7.1.4
5
+ numpy==1.26.4
6
+ torch==2.6.0+cpu
7
+ jsonschema==4.23.0
score_independent_eval.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Scoring post-hoc de evaluación independiente (capa C).
3
+
4
+ Formato oficial de anotaciones (annotations_template.json):
5
+
6
+ {
7
+ "annotators": ["A1", "A2", "A3"],
8
+ "status": "pending_human_collection" | "complete",
9
+ "items": [
10
+ {
11
+ "id": "NR01",
12
+ "annotations": {"A1": "none" | null, ...},
13
+ "free_text": {"A1": "...", ...}
14
+ },
15
+ ...
16
+ ]
17
+ }
18
+
19
+ Reglas estadísticas:
20
+ - null / ausente ≠ etiqueta "unsure".
21
+ - Fleiss' kappa exige el **mismo conjunto de anotadores** con respuesta
22
+ no nula en **todos** los ítems incluidos (k fijo). No se trunca.
23
+ - Si un ítem tiene un subconjunto distinto de respondentes, se excluye
24
+ del kappa y se reporta en incomplete/heterogeneous.
25
+ - "unsure" es una respuesta legítima, no un relleno.
26
+
27
+ Uso:
28
+ python scripts/score_independent_eval.py
29
+ python scripts/score_independent_eval.py --annotations path/to/filled.json
30
+ python scripts/score_independent_eval.py --min-annotators 3
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json
36
+ import sys
37
+ from collections import Counter, defaultdict
38
+ from pathlib import Path
39
+ from typing import Any
40
+
41
+ ROOT = Path(__file__).resolve().parents[1]
42
+ EVAL_DIR = ROOT / "datasets" / "independent_eval"
43
+ VALID_LABELS = frozenset({"none", "mirrorOf", "creates", "unsure"})
44
+
45
+
46
+ def fleiss_kappa(ratings: list[list[str]], categories: list[str]) -> float:
47
+ """Fleiss' kappa. ratings[i] = etiquetas de los k anotadores para el ítem i.
48
+ Todas las filas deben tener la misma longitud k ≥ 2.
49
+ """
50
+ n_items = len(ratings)
51
+ if n_items == 0:
52
+ return float("nan")
53
+ n_raters = len(ratings[0])
54
+ if n_raters < 2:
55
+ return float("nan")
56
+ if any(len(r) != n_raters for r in ratings):
57
+ raise ValueError("Todas las filas de ratings deben tener la misma longitud")
58
+
59
+ cat_idx = {c: i for i, c in enumerate(categories)}
60
+ table = []
61
+ for row in ratings:
62
+ counts = [0] * len(categories)
63
+ for lab in row:
64
+ if lab not in cat_idx:
65
+ raise ValueError(f"Etiqueta fuera de categorías: {lab!r}")
66
+ counts[cat_idx[lab]] += 1
67
+ table.append(counts)
68
+
69
+ P = []
70
+ for counts in table:
71
+ s = sum(c * (c - 1) for c in counts)
72
+ P.append(s / (n_raters * (n_raters - 1)))
73
+ P_bar = sum(P) / n_items
74
+
75
+ totals = [sum(table[i][j] for i in range(n_items)) for j in range(len(categories))]
76
+ p = [t / (n_items * n_raters) for t in totals]
77
+ P_e = sum(pj ** 2 for pj in p)
78
+ if abs(1 - P_e) < 1e-12:
79
+ return 1.0
80
+ return (P_bar - P_e) / (1 - P_e)
81
+
82
+
83
+ def parse_template_format(data: dict) -> tuple[list[str], dict[str, dict[str, str | None]]]:
84
+ """Formato oficial: annotators=[ids], items=[{id, annotations: {A: label|null}}]."""
85
+ annotator_ids = list(data.get("annotators") or [])
86
+ if not annotator_ids:
87
+ raise ValueError("Campo 'annotators' vacío o ausente")
88
+
89
+ by_pair: dict[str, dict[str, str | None]] = {}
90
+ items = data.get("items")
91
+ if not isinstance(items, list):
92
+ raise ValueError("Campo 'items' debe ser una lista")
93
+
94
+ for item in items:
95
+ pid = item.get("id")
96
+ if not pid:
97
+ raise ValueError(f"Ítem sin id: {item!r}")
98
+ anns = item.get("annotations") or {}
99
+ if not isinstance(anns, dict):
100
+ raise ValueError(f"annotations de {pid} debe ser un objeto")
101
+ pair_map: dict[str, str | None] = {}
102
+ for aid in annotator_ids:
103
+ raw = anns.get(aid)
104
+ if raw is None:
105
+ pair_map[aid] = None
106
+ elif isinstance(raw, str) and raw.strip() == "":
107
+ pair_map[aid] = None
108
+ elif raw in VALID_LABELS:
109
+ pair_map[aid] = raw
110
+ else:
111
+ raise ValueError(
112
+ f"Etiqueta inválida en {pid}/{aid}: {raw!r}. "
113
+ f"Permitidas: {sorted(VALID_LABELS)} o null"
114
+ )
115
+ by_pair[pid] = pair_map
116
+ return annotator_ids, by_pair
117
+
118
+
119
+ def parse_legacy_formats(data: Any) -> tuple[list[str], dict[str, dict[str, str | None]]]:
120
+ by_pair: dict[str, dict[str, str | None]] = defaultdict(dict)
121
+ annotator_ids: list[str] = []
122
+
123
+ if isinstance(data, dict) and "annotators" in data:
124
+ anns = data["annotators"]
125
+ if isinstance(anns, list) and anns and isinstance(anns[0], dict) and "labels" in anns[0]:
126
+ for ann in anns:
127
+ aid = str(ann.get("id") or ann.get("name") or f"A{len(annotator_ids)+1}")
128
+ annotator_ids.append(aid)
129
+ for pair_id, label in (ann.get("labels") or {}).items():
130
+ by_pair[pair_id][aid] = label if label in VALID_LABELS else None
131
+ return annotator_ids, dict(by_pair)
132
+
133
+ if isinstance(data, list):
134
+ aids_set: set[str] = set()
135
+ for item in data:
136
+ pid = item.get("id") or item.get("pair_id")
137
+ aid = str(item.get("annotator") or "A1")
138
+ lab = item.get("label") or item.get("annotation")
139
+ if not pid:
140
+ continue
141
+ aids_set.add(aid)
142
+ by_pair[pid][aid] = lab if lab in VALID_LABELS else None
143
+ return sorted(aids_set), dict(by_pair)
144
+
145
+ raise ValueError(
146
+ "Formato de anotaciones no reconocido. "
147
+ "Usa el formato de annotations_template.json."
148
+ )
149
+
150
+
151
+ def load_annotations(path: Path) -> tuple[list[str], dict[str, dict[str, str | None]], dict]:
152
+ data = json.loads(path.read_text(encoding="utf-8"))
153
+ meta = {
154
+ "status": data.get("status") if isinstance(data, dict) else None,
155
+ "description": data.get("description") if isinstance(data, dict) else None,
156
+ "evaluation_mode": data.get("evaluation_mode") if isinstance(data, dict) else None,
157
+ }
158
+ if isinstance(data, dict) and isinstance(data.get("items"), list):
159
+ annotator_ids, by_pair = parse_template_format(data)
160
+ else:
161
+ annotator_ids, by_pair = parse_legacy_formats(data)
162
+ return annotator_ids, by_pair, meta
163
+
164
+
165
+ def load_rule_reference() -> dict[str, str]:
166
+ ref_path = EVAL_DIR / "rule_reference.json"
167
+ if not ref_path.is_file():
168
+ return {}
169
+ raw = json.loads(ref_path.read_text(encoding="utf-8"))
170
+ if isinstance(raw, list):
171
+ return {item["id"]: item.get("rule_label") for item in raw if "id" in item}
172
+ if isinstance(raw, dict):
173
+ out = {}
174
+ for k, v in raw.items():
175
+ if k in ("labels",):
176
+ continue
177
+ if isinstance(v, dict):
178
+ out[k] = v.get("rule_label")
179
+ elif isinstance(v, str):
180
+ out[k] = v
181
+ if "labels" in raw and isinstance(raw["labels"], dict):
182
+ out.update(raw["labels"])
183
+ return out
184
+ return {}
185
+
186
+
187
+ def main() -> int:
188
+ parser = argparse.ArgumentParser(
189
+ description="Scoring de evaluación independiente (capa C)"
190
+ )
191
+ parser.add_argument(
192
+ "--annotations",
193
+ type=Path,
194
+ default=EVAL_DIR / "annotations.json",
195
+ help="JSON de anotaciones (plantilla o rellenado)",
196
+ )
197
+ parser.add_argument(
198
+ "--min-annotators",
199
+ type=int,
200
+ default=3,
201
+ help="Número exacto de anotadores con respuesta no nula requerido por ítem (default 3)",
202
+ )
203
+ args = parser.parse_args()
204
+
205
+ if not args.annotations.is_file():
206
+ # fallback a plantilla
207
+ alt = EVAL_DIR / "annotations_template.json"
208
+ if alt.is_file():
209
+ args.annotations = alt
210
+ else:
211
+ print(f"ERROR: no se encontró {args.annotations}", file=sys.stderr)
212
+ return 1
213
+
214
+ try:
215
+ annotator_ids, by_pair, meta = load_annotations(args.annotations)
216
+ except (ValueError, json.JSONDecodeError) as exc:
217
+ print(f"ERROR de formato: {exc}", file=sys.stderr)
218
+ return 1
219
+
220
+ k_required = args.min_annotators
221
+ if k_required < 2:
222
+ print("ERROR: --min-annotators debe ser ≥ 2", file=sys.stderr)
223
+ return 1
224
+
225
+ incomplete_pairs: dict[str, dict] = {}
226
+ respondent_sets: dict[str, tuple[str, ...]] = {}
227
+ labels_by_pair_ordered: dict[str, list[str]] = {}
228
+ unsure_counts: Counter = Counter()
229
+ present_counts: Counter = Counter()
230
+
231
+ for pid, ann_map in by_pair.items():
232
+ respondents = []
233
+ labels_ordered = []
234
+ missing = []
235
+ for aid in annotator_ids:
236
+ lab = ann_map.get(aid)
237
+ if lab is None:
238
+ missing.append(aid)
239
+ else:
240
+ respondents.append(aid)
241
+ labels_ordered.append(lab)
242
+ present_counts[lab] += 1
243
+ if lab == "unsure":
244
+ unsure_counts[pid] += 1
245
+
246
+ if len(respondents) == k_required:
247
+ respondent_sets[pid] = tuple(respondents)
248
+ labels_by_pair_ordered[pid] = labels_ordered
249
+ else:
250
+ incomplete_pairs[pid] = {
251
+ "n_present": len(respondents),
252
+ "n_missing": len(missing),
253
+ "missing_annotators": missing,
254
+ "present_annotators": respondents,
255
+ "present_labels": labels_ordered,
256
+ "reason": (
257
+ f"se requieren exactamente {k_required} respuestas no nulas; "
258
+ f"hay {len(respondents)}"
259
+ ),
260
+ }
261
+
262
+ status = meta.get("status") or "unknown"
263
+ n_total = len(by_pair)
264
+
265
+ by_respondent_set: dict[tuple[str, ...], list[str]] = defaultdict(list)
266
+ for pid, rset in respondent_sets.items():
267
+ by_respondent_set[rset].append(pid)
268
+
269
+ kappa_eligible_ids: list[str] = []
270
+ kappa_annotators: tuple[str, ...] | None = None
271
+ heterogeneous: dict[str, dict] = {}
272
+
273
+ if by_respondent_set:
274
+ best_set = max(
275
+ by_respondent_set.keys(),
276
+ key=lambda s: (len(by_respondent_set[s]), s),
277
+ )
278
+ kappa_eligible_ids = sorted(by_respondent_set[best_set])
279
+ kappa_annotators = best_set
280
+
281
+ for rset, pids in by_respondent_set.items():
282
+ if rset == best_set:
283
+ continue
284
+ for pid in pids:
285
+ heterogeneous[pid] = {
286
+ "respondents": list(rset),
287
+ "n_present": len(rset),
288
+ "reason": (
289
+ "conjunto de anotadores distinto al usado para kappa "
290
+ f"({list(best_set)}); no se trunca ni se mezcla"
291
+ ),
292
+ "present_labels": labels_by_pair_ordered[pid],
293
+ }
294
+
295
+ n_kappa = len(kappa_eligible_ids)
296
+ n_incomplete = len(incomplete_pairs)
297
+ n_heterogeneous = len(heterogeneous)
298
+
299
+ if n_kappa == 0:
300
+ report = {
301
+ "status": status,
302
+ "evaluation_mode": meta.get("evaluation_mode"),
303
+ "n_pairs_total": n_total,
304
+ "n_pairs_in_kappa": 0,
305
+ "n_pairs_incomplete": n_incomplete,
306
+ "n_pairs_heterogeneous_respondent_set": n_heterogeneous,
307
+ "min_annotators_required": k_required,
308
+ "kappa_annotators": None,
309
+ "fleiss_kappa": None,
310
+ "majority_labels": {},
311
+ "posthoc_agreement_with_rule_reference": None,
312
+ "incomplete_detail": incomplete_pairs,
313
+ "heterogeneous_detail": heterogeneous,
314
+ "note": (
315
+ f"Sin ítems con exactamente {k_required} respuestas no nulas "
316
+ "del mismo conjunto de anotadores. No se trunca. "
317
+ "null/ausente ≠ 'unsure'. Protocolo listo; esperando recolección."
318
+ ),
319
+ }
320
+ out = ROOT / "experiments" / "results" / "independent_eval_scores.json"
321
+ out.parent.mkdir(parents=True, exist_ok=True)
322
+ out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
323
+ print(json.dumps(report, ensure_ascii=False, indent=2))
324
+ print(f"Escrito: {out}")
325
+ return 0
326
+
327
+ assert kappa_annotators is not None
328
+ k = len(kappa_annotators)
329
+ categories = ["none", "mirrorOf", "creates", "unsure"]
330
+ ratings = [labels_by_pair_ordered[pid] for pid in kappa_eligible_ids]
331
+
332
+ if any(len(r) != k for r in ratings):
333
+ print(
334
+ "ERROR interno: longitudes inconsistentes tras filtrado; no se calcula kappa.",
335
+ file=sys.stderr,
336
+ )
337
+ return 1
338
+
339
+ kappa = fleiss_kappa(ratings, categories)
340
+
341
+ majority: dict[str, str] = {}
342
+ unanimous = 0
343
+ for pid in kappa_eligible_ids:
344
+ labs = labels_by_pair_ordered[pid]
345
+ cnt = Counter(labs)
346
+ maj_lab, maj_n = cnt.most_common(1)[0]
347
+ majority[pid] = maj_lab
348
+ if maj_n == len(labs):
349
+ unanimous += 1
350
+
351
+ majority_all = dict(majority)
352
+ for pid, labs in labels_by_pair_ordered.items():
353
+ if pid not in majority_all and labs:
354
+ majority_all[pid] = Counter(labs).most_common(1)[0][0]
355
+
356
+ rule_ref = load_rule_reference()
357
+ comparable = {
358
+ pid: maj
359
+ for pid, maj in majority.items()
360
+ if rule_ref.get(pid) and rule_ref[pid] not in (None, "unspecified")
361
+ }
362
+ agreement_with_rules = None
363
+ if comparable:
364
+ matched = sum(1 for pid, maj in comparable.items() if rule_ref[pid] == maj)
365
+ agreement_with_rules = round(matched / len(comparable), 4)
366
+
367
+ report = {
368
+ "status": status,
369
+ "evaluation_mode": meta.get("evaluation_mode"),
370
+ "n_pairs_total": n_total,
371
+ "n_pairs_in_kappa": n_kappa,
372
+ "n_pairs_incomplete": n_incomplete,
373
+ "n_pairs_heterogeneous_respondent_set": n_heterogeneous,
374
+ "min_annotators_required": k_required,
375
+ "kappa_annotators": list(kappa_annotators),
376
+ "n_annotators_per_kappa_item": k,
377
+ "fleiss_kappa": None if (isinstance(kappa, float) and kappa != kappa) else round(kappa, 4),
378
+ "unanimous_fraction": round(unanimous / n_kappa, 4) if n_kappa else None,
379
+ "majority_labels_in_kappa": majority,
380
+ "majority_labels_all_with_any_response": majority_all,
381
+ "label_distribution_present": dict(present_counts),
382
+ "unsure_count_by_pair": dict(unsure_counts),
383
+ "posthoc_agreement_with_rule_reference": agreement_with_rules,
384
+ "n_posthoc_comparable": len(comparable),
385
+ "incomplete_detail": incomplete_pairs if incomplete_pairs else {},
386
+ "heterogeneous_detail": heterogeneous if heterogeneous else {},
387
+ "policy": (
388
+ "Fleiss' kappa solo sobre ítems con exactamente k anotadores no nulos "
389
+ "y el mismo conjunto de respondentes. No se trunca ni se rellena. "
390
+ "null ≠ unsure."
391
+ ),
392
+ "note": (
393
+ "Fleiss' kappa y mayoría (sobre el panel kappa) son el objetivo primario. "
394
+ "posthoc_agreement_with_rule_reference excluye unspecified y es solo post-hoc."
395
+ ),
396
+ }
397
+
398
+ out = ROOT / "experiments" / "results" / "independent_eval_scores.json"
399
+ out.parent.mkdir(parents=True, exist_ok=True)
400
+ out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
401
+ print(json.dumps(report, ensure_ascii=False, indent=2))
402
+ print(f"Escrito: {out}")
403
+ return 0
404
+
405
+
406
+ if __name__ == "__main__":
407
+ raise SystemExit(main())
score_quiz.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Autoevaluación del manual de protocolo ciego (no es métrica del marco)."""
3
+ from __future__ import annotations
4
+ import json, sys
5
+ from pathlib import Path
6
+
7
+ QUIZ = Path(__file__).with_name("quiz_blind_protocol.json")
8
+
9
+ def main(answers: dict[str, str]) -> int:
10
+ data = json.loads(QUIZ.read_text(encoding="utf-8"))
11
+ correct = 0
12
+ for q in data["questions"]:
13
+ got = answers.get(q["id"], "").lower().strip()
14
+ ok = got == q["answer"]
15
+ correct += int(ok)
16
+ mark = "OK" if ok else "FAIL"
17
+ print(f"{q['id']}: {mark} (esperado={q['answer']}, recibido={got or '—'})")
18
+ if not ok:
19
+ print(f" → {q['rationale']}")
20
+ total = len(data["questions"])
21
+ print(f"Puntuación: {correct}/{total}")
22
+ print("Nota: este quiz evalúa comprensión del protocolo; no modifica κ ni EXP-A.")
23
+ return 0 if correct == total else 1
24
+
25
+ if __name__ == "__main__":
26
+ if len(sys.argv) > 1 and sys.argv[1] == "--self-test":
27
+ key = {q["id"]: q["answer"] for q in json.loads(QUIZ.read_text(encoding="utf-8"))["questions"]}
28
+ raise SystemExit(main(key))
29
+ print("Uso: python experiments/learning/score_quiz.py Q1=b Q2=b Q3=c Q4=c")
30
+ print(" o: python experiments/learning/score_quiz.py --self-test")
31
+ ans = {}
32
+ for arg in sys.argv[1:]:
33
+ if "=" in arg:
34
+ k, v = arg.split("=", 1)
35
+ ans[k.strip().upper()] = v.strip()
36
+ if ans:
37
+ raise SystemExit(main(ans))
self_bootstrap.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Punto fijo del repositorio: auto-creación estable bajo iteración.
3
+
4
+ python scripts/self_bootstrap.py --passes 2
5
+ python scripts/self_bootstrap.py --with-manifest --passes 2
6
+
7
+ Con --with-manifest:
8
+ 1. Regenera CSV + MANIFEST.sha256
9
+ 2. Exige identidad con HEAD (git diff vacío)
10
+ 3. Cobertura dura de archivos críticos
11
+ 4. Sello datasets/GENERATED_FROM.json == spec_version del iom_spec.json
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import subprocess
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ ROOT = Path(__file__).resolve().parents[1]
22
+
23
+ DERIVED_CSV = [
24
+ "datasets/triad_nodes.csv",
25
+ "datasets/vector_steps.csv",
26
+ "datasets/relation_candidates.csv",
27
+ "datasets/GENERATED_FROM.json",
28
+ ]
29
+
30
+ CRITICAL_IF_PRESENT = [
31
+ "scripts/self_bootstrap.py",
32
+ "scripts/measure_invariance.py",
33
+ "scripts/create_manifest.py",
34
+ "scripts/generate_ontology.py",
35
+ "IOM/SelfGenesis.lean",
36
+ "IOM/FormalRules.lean",
37
+ "MANIFIESTO.md",
38
+ "docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md",
39
+ "datasets/independent_eval/instrument/INSTRUCTIONS.md",
40
+ "datasets/independent_eval/instrument/pairs.csv",
41
+ "datasets/independent_eval/instrument/ACCESS_LOG.template.json",
42
+ "datasets/GENERATED_FROM.json",
43
+ ]
44
+
45
+
46
+ def check_spec_version_stamp() -> list[str]:
47
+ """Falla si los derivados no declaran la misma spec_version que iom_spec.json."""
48
+ spec = json.loads((ROOT / "data" / "iom_spec.json").read_text(encoding="utf-8"))
49
+ expected = spec["spec_version"]
50
+ stamp_path = ROOT / "datasets" / "GENERATED_FROM.json"
51
+ if not stamp_path.is_file():
52
+ return [f"falta {stamp_path.as_posix()} (regenera con generate_ontology.py)"]
53
+ stamp = json.loads(stamp_path.read_text(encoding="utf-8"))
54
+ if stamp.get("spec_version") != expected:
55
+ return [
56
+ f"GENERATED_FROM.json spec_version={stamp.get('spec_version')!r} "
57
+ f"≠ iom_spec.json {expected!r}"
58
+ ]
59
+ return []
60
+
61
+
62
+ def run(cmd: list[str]) -> subprocess.CompletedProcess:
63
+ return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True)
64
+
65
+
66
+ def git_diff_paths(paths: list[str]) -> subprocess.CompletedProcess:
67
+ return run(["git", "diff", "--ignore-space-at-eol", "--exit-code", "--", *paths])
68
+
69
+
70
+ def porcelain(paths: list[str]) -> str:
71
+ return run(["git", "status", "--porcelain", "--", *paths]).stdout
72
+
73
+
74
+ def manifest_paths(manifest_file: Path) -> set[str]:
75
+ out: set[str] = set()
76
+ for line in manifest_file.read_text(encoding="utf-8").splitlines():
77
+ line = line.strip()
78
+ if not line:
79
+ continue
80
+ parts = line.split(" ", 1)
81
+ if len(parts) == 2:
82
+ out.add(parts[1])
83
+ return out
84
+
85
+
86
+ def check_manifest_coverage() -> list[str]:
87
+ mf = ROOT / "MANIFEST.sha256"
88
+ if not mf.is_file():
89
+ return ["MANIFEST.sha256 (archivo inexistente)"]
90
+ listed = manifest_paths(mf)
91
+ missing = []
92
+ for rel in CRITICAL_IF_PRESENT:
93
+ p = ROOT / rel
94
+ if p.is_file() and rel not in listed:
95
+ missing.append(rel)
96
+ return missing
97
+
98
+
99
+ def main() -> int:
100
+ parser = argparse.ArgumentParser(description="Punto fijo idempotente")
101
+ parser.add_argument("--with-manifest", action="store_true")
102
+ parser.add_argument("--passes", type=int, default=2)
103
+ args = parser.parse_args()
104
+
105
+ paths = list(DERIVED_CSV)
106
+ if args.with_manifest:
107
+ paths.append("MANIFEST.sha256")
108
+
109
+ print("=== self_bootstrap: punto fijo idempotente ===")
110
+ print(f"Pasadas: {args.passes} | manifiesto: {args.with_manifest}")
111
+ print()
112
+
113
+ for i in range(1, args.passes + 1):
114
+ print(f"--- pasada {i}/{args.passes} ---")
115
+ r = run([sys.executable, "scripts/generate_ontology.py"])
116
+ print(r.stdout, end="")
117
+ if r.returncode != 0:
118
+ print(r.stderr, file=sys.stderr)
119
+ return 1
120
+
121
+ stamp_errs = check_spec_version_stamp()
122
+ if stamp_errs:
123
+ print("FALLO: sello de spec_version inconsistente:", file=sys.stderr)
124
+ for e in stamp_errs:
125
+ print(f" - {e}", file=sys.stderr)
126
+ return 1
127
+
128
+ if args.with_manifest:
129
+ r = run([sys.executable, "scripts/create_manifest.py"])
130
+ print(r.stdout, end="")
131
+ if r.returncode != 0:
132
+ print(r.stderr, file=sys.stderr)
133
+ return 1
134
+
135
+ missing = check_manifest_coverage()
136
+ if missing:
137
+ print(
138
+ "FALLO de cobertura del manifiesto — archivos críticos en disco "
139
+ "pero ausentes de MANIFEST.sha256:",
140
+ file=sys.stderr,
141
+ )
142
+ for m in missing:
143
+ print(f" - {m}", file=sys.stderr)
144
+ return 1
145
+
146
+ r = git_diff_paths(paths)
147
+ if r.returncode != 0:
148
+ print(
149
+ f"FALLO en pasada {i}: regenerado ≠ HEAD en {paths}",
150
+ file=sys.stderr,
151
+ )
152
+ print(r.stdout or r.stderr, file=sys.stderr)
153
+ if args.with_manifest:
154
+ print(
155
+ "\nVersiona el manifiesto:\n"
156
+ " python scripts/create_manifest.py\n"
157
+ " git add MANIFEST.sha256 && git commit -m 'chore: refresh MANIFEST'\n"
158
+ " python scripts/self_bootstrap.py --with-manifest --passes 2",
159
+ file=sys.stderr,
160
+ )
161
+ return 1
162
+
163
+ dirty = porcelain(paths).strip()
164
+ if dirty:
165
+ print(f"FALLO: porcelain no limpio:\n{dirty}", file=sys.stderr)
166
+ return 1
167
+ print(
168
+ f"OK pasada {i}: diff vacío, porcelain limpio"
169
+ + (", cobertura crítica OK" if args.with_manifest else "")
170
+ + f", stamp={json.loads((ROOT / 'datasets' / 'GENERATED_FROM.json').read_text())['spec_version']}"
171
+ )
172
+
173
+ print()
174
+ print("OK: punto fijo estable (S_{n+1} = S_n).")
175
+ return 0
176
+
177
+
178
+ if __name__ == "__main__":
179
+ sys.exit(main())
sync_spec_artifacts.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Sincronización y verificación bidireccional entre especificación y artefactos.
3
+
4
+ Garantiza que data/iom_spec.json, los CSV generados, la ontología y los conteos
5
+ de pruebas permanecen coherentes. Con --check solo verifica; con --fix regenera
6
+ vía generate_ontology.py y vuelve a verificar.
7
+
8
+ Uso:
9
+ python scripts/sync_spec_artifacts.py --check
10
+ python scripts/sync_spec_artifacts.py --fix
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import csv
16
+ import json
17
+ import subprocess
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ ROOT = Path(__file__).resolve().parents[1]
22
+ SPEC_PATH = ROOT / "data" / "iom_spec.json"
23
+
24
+
25
+ def load_spec() -> dict:
26
+ return json.loads(SPEC_PATH.read_text(encoding="utf-8"))
27
+
28
+
29
+ def count_csv(name: str) -> int:
30
+ path = ROOT / "datasets" / name
31
+ if not path.is_file():
32
+ return -1
33
+ with path.open(encoding="utf-8", newline="") as fh:
34
+ return len(list(csv.DictReader(fh)))
35
+
36
+
37
+ def expected_counts(spec: dict) -> dict:
38
+ n_triads = len(spec["triads"]["adv"])
39
+ n_positions = len(spec["positions"]["indices"])
40
+ n_vectors = len(spec["vectors"])
41
+ steps_per_vector = len(spec["vectors"][0]["labels"]) if spec["vectors"] else 5
42
+ # 6 nodos por tríada (2 fases × 3 pos), 5 destinos no reflexivos → 6*5=30 pares/tríada
43
+ pairs_per_triad = (2 * n_positions) * (2 * n_positions - 1)
44
+ # creates: 4 rules × product of position lists × n_triads
45
+ creates = 0
46
+ for rule in spec["creation_rules"]:
47
+ creates += len(rule["source_positions"]) * len(rule["target_positions"]) * n_triads
48
+ # mirrorOf: 3 posiciones × 2 direcciones × n_triads = 6 * n_triads
49
+ mirrors = n_positions * 2 * n_triads
50
+ nodes = n_triads * 2 * n_positions
51
+ pairs = n_triads * pairs_per_triad
52
+ none = pairs - mirrors - creates
53
+ return {
54
+ "n_triads": n_triads,
55
+ "nodes": nodes,
56
+ "vector_steps": n_vectors * steps_per_vector,
57
+ "relation_candidates": pairs,
58
+ "mirrorOf": mirrors,
59
+ "creates": creates,
60
+ "none": none,
61
+ }
62
+
63
+
64
+ def check(spec: dict) -> list[str]:
65
+ errors = []
66
+ exp = expected_counts(spec)
67
+
68
+ # Versión
69
+ if not spec.get("spec_version"):
70
+ errors.append("Falta spec_version")
71
+ migrations = spec.get("migrations") or []
72
+ if migrations and migrations[-1].get("to_version") != spec.get("spec_version"):
73
+ errors.append(
74
+ f"spec_version={spec.get('spec_version')} != último to_version={migrations[-1].get('to_version')}"
75
+ )
76
+
77
+ # Conteos CSV
78
+ actual_nodes = count_csv("triad_nodes.csv")
79
+ actual_vecs = count_csv("vector_steps.csv")
80
+ actual_rels = count_csv("relation_candidates.csv")
81
+
82
+ if actual_nodes != exp["nodes"]:
83
+ errors.append(f"triad_nodes.csv: {actual_nodes} filas, esperado {exp['nodes']}")
84
+ if actual_vecs != exp["vector_steps"]:
85
+ errors.append(f"vector_steps.csv: {actual_vecs} filas, esperado {exp['vector_steps']}")
86
+ if actual_rels != exp["relation_candidates"]:
87
+ errors.append(
88
+ f"relation_candidates.csv: {actual_rels} filas, esperado {exp['relation_candidates']}"
89
+ )
90
+
91
+ # Conteos de relaciones
92
+ if actual_rels > 0:
93
+ with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as fh:
94
+ from collections import Counter
95
+ c = Counter(r["relation"] for r in csv.DictReader(fh))
96
+ for key in ("mirrorOf", "creates", "none"):
97
+ if c.get(key, 0) != exp[key]:
98
+ errors.append(f"relación {key}: {c.get(key, 0)}, esperado {exp[key]}")
99
+
100
+ # Ontología existe y menciona version-ish content
101
+ ttl = ROOT / "ontology" / "io_ontology.ttl"
102
+ if not ttl.is_file():
103
+ errors.append("Falta ontology/io_ontology.ttl")
104
+ else:
105
+ text = ttl.read_text(encoding="utf-8")
106
+ if "mirrorOf" not in text or "creates" not in text:
107
+ errors.append("io_ontology.ttl no contiene mirrorOf/creates")
108
+
109
+ # Schema
110
+ schema = ROOT / "data" / "iom_spec.schema.json"
111
+ if not schema.is_file():
112
+ errors.append("Falta data/iom_spec.schema.json")
113
+
114
+ return errors
115
+
116
+
117
+ def main() -> int:
118
+ parser = argparse.ArgumentParser()
119
+ parser.add_argument("--check", action="store_true", help="Solo verificar sincronización")
120
+ parser.add_argument("--fix", action="store_true", help="Regenerar artefactos y verificar")
121
+ args = parser.parse_args()
122
+
123
+ if not args.check and not args.fix:
124
+ args.check = True
125
+
126
+ if args.fix:
127
+ print("Regenerando ontología y datasets…")
128
+ r = subprocess.run(
129
+ [sys.executable, "scripts/generate_ontology.py"],
130
+ cwd=ROOT,
131
+ capture_output=True,
132
+ text=True,
133
+ )
134
+ if r.returncode != 0:
135
+ print(r.stdout)
136
+ print(r.stderr, file=sys.stderr)
137
+ return 1
138
+ print(r.stdout.strip())
139
+
140
+ spec = load_spec()
141
+ errors = check(spec)
142
+ exp = expected_counts(spec)
143
+
144
+ print(f"spec_version={spec.get('spec_version')} schema_version={spec.get('schema_version')}")
145
+ print(f"Esperado: nodos={exp['nodes']} vectores={exp['vector_steps']} "
146
+ f"pares={exp['relation_candidates']} "
147
+ f"(mirror={exp['mirrorOf']} creates={exp['creates']} none={exp['none']})")
148
+
149
+ if errors:
150
+ print("INCONSISTENCIAS:")
151
+ for e in errors:
152
+ print(f" - {e}")
153
+ return 1
154
+ print("OK: especificación, CSV y ontología sincronizados")
155
+ return 0
156
+
157
+
158
+ if __name__ == "__main__":
159
+ sys.exit(main())
test_formal_rules_bridge.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Puente: las relaciones del CSV deben satisfacer los predicados formales
3
+ codificados en IOM/FormalRules.lean (isMirrorRel / isCreatesRel / sameTriad).
4
+
5
+ Equivalencia de capas:
6
+ Lean isMirrorRel ↔ Python is_mirror ∧ same_triad
7
+ Lean isCreatesRel ↔ Python is_creates ∧ same_triad
8
+ Lean isMirror (posicional) ↔ Python is_mirror (sin exigir tríada)
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import csv
13
+ import re
14
+ import unittest
15
+ from pathlib import Path
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+
19
+
20
+ def load_relations():
21
+ with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as fh:
22
+ return list(csv.DictReader(fh))
23
+
24
+
25
+ def parse_node(node_id: str) -> tuple[int, str, int]:
26
+ """Devuelve (triad_id, phase, position)."""
27
+ m = re.fullmatch(r"T(\d{2})_(adv|ret)_P([0-2])", node_id)
28
+ assert m, node_id
29
+ return int(m.group(1)), m.group(2), int(m.group(3))
30
+
31
+
32
+ def same_triad(src: str, tgt: str) -> bool:
33
+ return parse_node(src)[0] == parse_node(tgt)[0]
34
+
35
+
36
+ def is_mirror_positional(src: str, tgt: str) -> bool:
37
+ """Equivale a Lean isMirror / isMirrorPositional."""
38
+ _sid, sp, spos = parse_node(src)
39
+ _tid, tp, tpos = parse_node(tgt)
40
+ return sp != tp and tpos == 2 - spos
41
+
42
+
43
+ def is_creates_positional(src: str, tgt: str) -> bool:
44
+ """Equivale a Lean isCreates / isCreatesPositional."""
45
+ _sid, sp, spos = parse_node(src)
46
+ _tid, tp, tpos = parse_node(tgt)
47
+ if sp == tp:
48
+ return False
49
+ lateral_s = spos in (0, 2)
50
+ lateral_t = tpos in (0, 2)
51
+ return (lateral_s and tpos == 1) or (spos == 1 and lateral_t)
52
+
53
+
54
+ def is_mirror_rel(src: str, tgt: str) -> bool:
55
+ """Equivale a Lean isMirrorRel: sameTriad ∧ isMirrorPositional."""
56
+ return same_triad(src, tgt) and is_mirror_positional(src, tgt)
57
+
58
+
59
+ def is_creates_rel(src: str, tgt: str) -> bool:
60
+ """Equivale a Lean isCreatesRel: sameTriad ∧ isCreatesPositional."""
61
+ return same_triad(src, tgt) and is_creates_positional(src, tgt)
62
+
63
+
64
+ class FormalRulesBridgeTests(unittest.TestCase):
65
+ """Comprueba que el JSON/CSV regenerado cumple los predicados Lean."""
66
+
67
+ @classmethod
68
+ def setUpClass(cls):
69
+ cls.rows = load_relations()
70
+ cls.lean = (ROOT / "IOM" / "FormalRules.lean").read_text(encoding="utf-8")
71
+
72
+ def test_lean_defines_same_triad_and_rel_predicates(self):
73
+ self.assertIn("def sameTriad", self.lean)
74
+ self.assertIn("def isMirrorRel", self.lean)
75
+ self.assertIn("def isCreatesRel", self.lean)
76
+ self.assertIn("def isMirrorPositional", self.lean)
77
+ self.assertIn("def isCreatesPositional", self.lean)
78
+ self.assertIn("triadId", self.lean)
79
+ self.assertIn("expectedMirrorDirected", self.lean)
80
+ self.assertIn("expectedCreatesDirected", self.lean)
81
+
82
+ def test_every_mirrorOf_satisfies_isMirrorRel(self):
83
+ for row in self.rows:
84
+ if row["relation"] != "mirrorOf":
85
+ continue
86
+ self.assertTrue(
87
+ is_mirror_rel(row["source"], row["target"]),
88
+ f"mirrorOf viola isMirrorRel: {row['source']} -> {row['target']}",
89
+ )
90
+ self.assertFalse(
91
+ is_creates_rel(row["source"], row["target"]),
92
+ f"mirrorOf no debe ser createsRel: {row}",
93
+ )
94
+
95
+ def test_every_creates_satisfies_isCreatesRel(self):
96
+ for row in self.rows:
97
+ if row["relation"] != "creates":
98
+ continue
99
+ self.assertTrue(
100
+ is_creates_rel(row["source"], row["target"]),
101
+ f"creates viola isCreatesRel: {row['source']} -> {row['target']}",
102
+ )
103
+ self.assertFalse(
104
+ is_mirror_rel(row["source"], row["target"]),
105
+ f"creates no debe ser mirrorRel: {row}",
106
+ )
107
+
108
+ def test_none_satisfies_neither_rel(self):
109
+ for row in self.rows:
110
+ if row["relation"] != "none":
111
+ continue
112
+ self.assertFalse(
113
+ is_mirror_rel(row["source"], row["target"]), row
114
+ )
115
+ self.assertFalse(
116
+ is_creates_rel(row["source"], row["target"]), row
117
+ )
118
+
119
+ def test_cross_triad_positional_mirror_is_not_rel(self):
120
+ """Un par cross-tríada puede cumplir la condición posicional pero no isMirrorRel."""
121
+ # T07_adv_P0 y T01_ret_P2: posicional mirror, distinta tríada
122
+ self.assertTrue(is_mirror_positional("T07_adv_P0", "T01_ret_P2"))
123
+ self.assertFalse(same_triad("T07_adv_P0", "T01_ret_P2"))
124
+ self.assertFalse(is_mirror_rel("T07_adv_P0", "T01_ret_P2"))
125
+
126
+ def test_counts_match_lean_constants(self):
127
+ from collections import Counter
128
+ c = Counter(r["relation"] for r in self.rows)
129
+ self.assertEqual(c["mirrorOf"], 78)
130
+ self.assertEqual(c["creates"], 104)
131
+ self.assertEqual(c["none"], 208)
132
+ self.assertIn("78", self.lean)
133
+ self.assertIn("104", self.lean)
134
+ self.assertIn("208", self.lean)
135
+
136
+ def test_partition_complete_with_rel(self):
137
+ for row in self.rows:
138
+ m = is_mirror_rel(row["source"], row["target"])
139
+ c = is_creates_rel(row["source"], row["target"])
140
+ self.assertFalse(m and c, row)
141
+ if row["relation"] == "mirrorOf":
142
+ self.assertTrue(m)
143
+ elif row["relation"] == "creates":
144
+ self.assertTrue(c)
145
+ else:
146
+ self.assertFalse(m or c)
147
+
148
+
149
+ if __name__ == "__main__":
150
+ unittest.main()
test_metrics_audit.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Pruebas que formalizan las conclusiones de la auditoría de métricas 100%."""
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import unittest
7
+ from collections import defaultdict
8
+ from pathlib import Path
9
+
10
+ ROOT = Path(__file__).resolve().parents[1]
11
+
12
+
13
+ def parse_node(node_id: str):
14
+ parts = node_id.split("_")
15
+ return parts[1], int(parts[2][1:])
16
+
17
+
18
+ def feature_key(src, tgt):
19
+ sp, spos = parse_node(src)
20
+ tp, tpos = parse_node(tgt)
21
+ return (sp, spos, tp, tpos)
22
+
23
+
24
+ def deterministic_label(src, tgt):
25
+ sp, spos = parse_node(src)
26
+ tp, tpos = parse_node(tgt)
27
+ if sp == tp:
28
+ return "none"
29
+ if tpos == 2 - spos:
30
+ return "mirrorOf"
31
+ if (spos in (0, 2) and tpos == 1) or (spos == 1 and tpos in (0, 2)):
32
+ return "creates"
33
+ return "none"
34
+
35
+
36
+ class PerfectMetricsAuditTests(unittest.TestCase):
37
+ @classmethod
38
+ def setUpClass(cls):
39
+ with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as fh:
40
+ cls.rows = list(csv.DictReader(fh))
41
+
42
+ def test_gold_matches_deterministic_rule(self):
43
+ for row in self.rows:
44
+ self.assertEqual(
45
+ deterministic_label(row["source"], row["target"]),
46
+ row["relation"],
47
+ msg=row,
48
+ )
49
+
50
+ def test_label_is_function_of_phase_position_only(self):
51
+ by_feat = defaultdict(set)
52
+ for row in self.rows:
53
+ by_feat[feature_key(row["source"], row["target"])].add(row["relation"])
54
+ for key, labels in by_feat.items():
55
+ self.assertEqual(len(labels), 1, f"clave {key} tiene etiquetas {labels}")
56
+
57
+ def test_loo_features_fully_recoverable_from_train(self):
58
+ """En cada fold LOO, todo par de test es recuperable por lookup de features."""
59
+ for held in range(1, 14):
60
+ train = {}
61
+ test = []
62
+ for row in self.rows:
63
+ key = feature_key(row["source"], row["target"])
64
+ if int(row["triad_index"]) == held:
65
+ test.append((key, row["relation"]))
66
+ else:
67
+ train[key] = row["relation"]
68
+ for key, lab in test:
69
+ self.assertEqual(train.get(key), lab)
70
+
71
+ def test_model_does_not_use_triad_index_in_features(self):
72
+ """Sanity: features_for_node en pi_hgat_t no incluye índice de tríada."""
73
+ src = (ROOT / "experiments" / "optional" / "pi_hgat_t.py").read_text(encoding="utf-8")
74
+ self.assertIn("sin etiqueta léxica ni número de tríada", src)
75
+ self.assertIn("phase == \"adv\"", src)
76
+ self.assertIn("position == 0", src)
77
+
78
+
79
+ if __name__ == "__main__":
80
+ unittest.main()
test_ontology.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pruebas de tríadas, vectores, OWL/RDF, SHACL y datasets generados.
2
+
3
+ Requiere rdflib y pyshacl (requirements-lock.txt). Si faltan, la clase se omite
4
+ con un mensaje explícito: eso no implica que la ontología falle.
5
+ """
6
+ import csv
7
+ import json
8
+ import unittest
9
+ from pathlib import Path
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+
13
+ try:
14
+ from pyshacl import validate
15
+ from rdflib import Graph, Literal, Namespace
16
+ from rdflib.namespace import OWL, RDF, RDFS, XSD
17
+ _ONT_DEPS = True
18
+ _ONT_IMPORT_ERROR = None
19
+ except ModuleNotFoundError as exc:
20
+ _ONT_DEPS = False
21
+ _ONT_IMPORT_ERROR = exc
22
+ validate = None # type: ignore
23
+ Graph = Literal = Namespace = OWL = RDF = RDFS = XSD = None # type: ignore
24
+
25
+
26
+ @unittest.skipUnless(
27
+ _ONT_DEPS,
28
+ f"omitido: falta dependencia de ontología ({_ONT_IMPORT_ERROR}). "
29
+ "Instala requirements-lock.txt; no implica fallo de la ontología.",
30
+ )
31
+ class IOMValidationTests(unittest.TestCase):
32
+ @classmethod
33
+ def setUpClass(cls):
34
+ cls.IO = Namespace("http://example.org/iom#")
35
+ cls.DATA = ROOT / "ontology" / "io_ontology.ttl"
36
+ cls.SHAPES = ROOT / "ontology" / "io_shapes.ttl"
37
+ cls.SPEC = json.loads((ROOT / "data" / "iom_spec.json").read_text(encoding="utf-8"))
38
+ with (ROOT / "datasets" / "triad_nodes.csv").open(encoding="utf-8", newline="") as handle:
39
+ cls.NODE_ROWS = list(csv.DictReader(handle))
40
+
41
+ def setUp(self):
42
+ self.data = Graph().parse(self.DATA, format="turtle")
43
+ self.shapes = Graph().parse(self.SHAPES, format="turtle")
44
+ self.IO = self.__class__.IO
45
+
46
+ def conforms(self, graph=None, focus_nodes=None):
47
+ result, _report, text = validate(
48
+ self.data if graph is None else graph,
49
+ shacl_graph=self.shapes,
50
+ inference="none",
51
+ focus_nodes=focus_nodes,
52
+ )
53
+ return result, text
54
+
55
+ def test_spec_matches_canonical_numbered_triad_matrices(self):
56
+ expected_adv = [
57
+ ["orientación", "cuántico", "dirección"],
58
+ ["hardware", "virtual", "software"],
59
+ ["universo", "espacio", "vacío"],
60
+ ["singularidad", "tiempo", "infinito"],
61
+ ["cuerpo", "consciente", "mundo"],
62
+ ["carácter", "subconsciente", "personalidad"],
63
+ ["memoria", "inconsciente", "imaginación"],
64
+ ["receptor", "supraconsciente", "emisor"],
65
+ ["lógica", "inteligencia", "libertad"],
66
+ ["muerte", "artificial", "vida"],
67
+ ["descendente", "mente", "ascendente"],
68
+ ["oscuridad", "consciencia", "luz"],
69
+ ["animal", "humano", "IA"],
70
+ ]
71
+ self.assertEqual(self.SPEC["triads"]["adv"], expected_adv)
72
+ self.assertEqual(self.SPEC["triads"]["ret"], [row[::-1] for row in expected_adv])
73
+ self.assertEqual(self.SPEC["triads"]["index_base"], 1)
74
+ self.assertEqual(self.SPEC["positions"]["adv_labels"], ["→", "0", "→"])
75
+ self.assertEqual(self.SPEC["positions"]["ret_labels"], ["←", "0", "←"])
76
+
77
+ def test_exact_triad_dataset_and_shacl_conformance(self):
78
+ IO = self.IO
79
+ nodes = set(self.data.subjects(RDF.type, IO.OntoNode))
80
+ expected = {
81
+ IO[f"T{i:02d}_{phase}_P{pos}"]
82
+ for i in range(1, 14)
83
+ for phase in ("adv", "ret")
84
+ for pos in range(3)
85
+ }
86
+ self.assertEqual(nodes, expected)
87
+ self.assertTrue(self.conforms()[0], self.conforms()[1])
88
+ for phase in ("adv", "ret"):
89
+ rows = self.SPEC["triads"][phase]
90
+ for row_index, row in enumerate(rows):
91
+ triad_index = row_index + 1
92
+ for pos, label in enumerate(row):
93
+ node = IO[f"T{triad_index:02d}_{phase}_P{pos}"]
94
+ self.assertEqual(str(self.data.value(node, RDFS.label)), label)
95
+ visual_label = self.SPEC["positions"]["adv_labels" if phase == "adv" else "ret_labels"][pos]
96
+ self.assertEqual(str(self.data.value(node, IO.displayLabel)), visual_label)
97
+ self.assertEqual(
98
+ self.data.value(node, IO.hasTriadIndex),
99
+ Literal(triad_index, datatype=XSD.integer),
100
+ )
101
+ self.assertEqual(
102
+ self.data.value(node, IO.hasLocalPos),
103
+ Literal(pos, datatype=XSD.integer),
104
+ )
105
+ self.assertEqual(
106
+ self.data.value(node, IO.hasPerspective),
107
+ IO[self.SPEC["perspectives"][pos]],
108
+ )
109
+ self.assertEqual(
110
+ self.data.value(node, IO.hasPosition),
111
+ IO[{"adv": ["→", "0", "→"], "ret": ["←", "0", "←"]}[phase][pos]],
112
+ )
113
+ display_labels = self.SPEC["positions"]["adv_labels" if phase == "adv" else "ret_labels"]
114
+ generated = next(r for r in self.NODE_ROWS if r["node_id"] == f"T{triad_index:02d}_{phase}_P{pos}")
115
+ self.assertEqual(generated["display_label"], display_labels[pos])
116
+
117
+ def test_mirrors_are_reciprocal_and_swap_laterals(self):
118
+ IO = self.IO
119
+ for i in range(1, 14):
120
+ for pos in range(3):
121
+ adv, ret = IO[f"T{i:02d}_adv_P{pos}"], IO[f"T{i:02d}_ret_P{2 - pos}"]
122
+ self.assertEqual(self.data.value(adv, IO.mirrorOf), ret)
123
+ self.assertEqual(self.data.value(ret, IO.mirrorOf), adv)
124
+
125
+ def test_creation_edges_follow_all_four_rules(self):
126
+ IO = self.IO
127
+ actual = set(self.data.triples((None, IO.creates, None)))
128
+ expected = set()
129
+ for i in range(1, 14):
130
+ for rule in self.SPEC["creation_rules"]:
131
+ for src in rule["source_positions"]:
132
+ for dst in rule["target_positions"]:
133
+ expected.add(
134
+ (
135
+ IO[f"T{i:02d}_{rule['source_phase']}_P{src}"],
136
+ IO.creates,
137
+ IO[f"T{i:02d}_{rule['target_phase']}_P{dst}"],
138
+ )
139
+ )
140
+ n_rules_edges = sum(
141
+ len(r["source_positions"]) * len(r["target_positions"])
142
+ for r in self.SPEC["creation_rules"]
143
+ )
144
+ self.assertEqual(len(expected), 13 * n_rules_edges)
145
+ self.assertEqual(actual, expected)
146
+
147
+ def test_vectors_match_all_four_updated_sequences(self):
148
+ IO = self.IO
149
+ self.assertEqual(len(set(self.data.subjects(RDF.type, IO.VectorStep))), 20)
150
+ for row in self.SPEC["vectors"]:
151
+ for idx, (label, axis) in enumerate(zip(row["labels"], row["axis_positions"])):
152
+ step = IO[f"vector_{row['name'].lower()}_{row['phase']}_{idx}"]
153
+ self.assertEqual(self.data.value(step, IO.hasVector), IO[row["name"]])
154
+ self.assertEqual(str(self.data.value(step, IO.hasCyclePhase)), row["phase"])
155
+ self.assertEqual(
156
+ self.data.value(step, IO.hasStepIndex),
157
+ Literal(idx, datatype=XSD.integer),
158
+ )
159
+ self.assertEqual(
160
+ self.data.value(step, IO.hasAxisPosition),
161
+ Literal(axis, datatype=XSD.integer),
162
+ )
163
+ self.assertEqual(
164
+ self.data.value(step, IO.displayArrow),
165
+ Literal(row["arrow"], datatype=XSD.string),
166
+ )
167
+ self.assertEqual(str(self.data.value(step, RDFS.label)), label)
168
+
169
+ def test_owl_classes_object_property_axioms_and_perspectives(self):
170
+ IO = self.IO
171
+ for cls in (
172
+ IO.OntoNode,
173
+ IO.VectorStep,
174
+ IO.Perspective,
175
+ IO.ExpandedCategory,
176
+ IO.Position,
177
+ IO.Direction,
178
+ ):
179
+ self.assertIn((cls, RDF.type, OWL.Class), self.data)
180
+ for prop in (
181
+ IO.hasPerspective,
182
+ IO.hasPosition,
183
+ IO.hasDirection,
184
+ IO.hasVector,
185
+ IO.mirrorOf,
186
+ IO.creates,
187
+ ):
188
+ self.assertIn((prop, RDF.type, OWL.ObjectProperty), self.data)
189
+ self.assertIsNotNone(self.data.value(prop, RDFS.domain))
190
+ self.assertIsNotNone(self.data.value(prop, RDFS.range))
191
+ self.assertIn((IO.displayLabel, RDF.type, OWL.DatatypeProperty), self.data)
192
+ self.assertIn((IO.displayLabel, RDF.type, OWL.FunctionalProperty), self.data)
193
+ self.assertIn((IO.mirrorOf, RDF.type, OWL.SymmetricProperty), self.data)
194
+ for resource in (IO.Ind, IO.D, IO.Tot, IO.Evol, IO.Invol):
195
+ self.assertIn((resource, RDF.type, IO.Perspective), self.data)
196
+
197
+ def test_expanded_categories_keep_declared_level_counts(self):
198
+ IO = self.IO
199
+ nodes = set(self.data.subjects(RDF.type, IO.ExpandedCategory))
200
+ self.assertEqual(len(nodes), 21)
201
+ self.assertEqual(
202
+ [
203
+ sum(
204
+ self.data.value(n, IO.hasLevel) == Literal(level, datatype=XSD.integer)
205
+ for n in nodes
206
+ )
207
+ for level in range(5)
208
+ ],
209
+ [1, 4, 6, 6, 4],
210
+ )
211
+
212
+ def test_generated_datasets_have_expected_rows(self):
213
+ n_triads = len(self.SPEC["triads"]["adv"])
214
+ n_vec = sum(len(v["labels"]) for v in self.SPEC["vectors"])
215
+ expected = {
216
+ "triad_nodes.csv": n_triads * 2 * 3,
217
+ "vector_steps.csv": n_vec,
218
+ "relation_candidates.csv": n_triads * 6 * 5,
219
+ }
220
+ for name, count in expected.items():
221
+ with (ROOT / "datasets" / name).open(encoding="utf-8", newline="") as f:
222
+ self.assertEqual(len(list(csv.DictReader(f))), count, name)
223
+
224
+ def test_wrong_visual_position_label_is_rejected(self):
225
+ IO = self.IO
226
+ graph = Graph()
227
+ for triple in self.data:
228
+ graph.add(triple)
229
+ node = IO["T01_adv_P0"]
230
+ graph.remove((node, IO.displayLabel, Literal("→", datatype=XSD.string)))
231
+ graph.add((node, IO.displayLabel, Literal("←", datatype=XSD.string)))
232
+ self.assertFalse(self.conforms(graph, [node])[0])
233
+
234
+ def test_wrong_phase_direction_is_rejected(self):
235
+ IO = self.IO
236
+ graph = Graph()
237
+ for triple in self.data:
238
+ graph.add(triple)
239
+ node = IO["T01_adv_P0"]
240
+ graph.remove((node, IO.hasDirection, IO.evol))
241
+ graph.add((node, IO.hasDirection, IO.invol))
242
+ self.assertFalse(self.conforms(graph, [node])[0])
243
+
244
+ def test_nonreciprocal_or_misplaced_mirror_is_rejected(self):
245
+ IO = self.IO
246
+ graph = Graph()
247
+ for triple in self.data:
248
+ graph.add(triple)
249
+ node, good, wrong = IO["T01_adv_P0"], IO["T01_ret_P2"], IO["T01_ret_P0"]
250
+ graph.remove((node, IO.mirrorOf, good))
251
+ graph.add((node, IO.mirrorOf, wrong))
252
+ self.assertFalse(self.conforms(graph, [node])[0])
253
+
254
+ def test_wrong_creation_link_is_rejected(self):
255
+ IO = self.IO
256
+ graph = Graph()
257
+ for triple in self.data:
258
+ graph.add(triple)
259
+ node, good, wrong = IO["T01_adv_P0"], IO["T01_ret_P1"], IO["T01_ret_P0"]
260
+ graph.remove((node, IO.creates, good))
261
+ graph.add((node, IO.creates, wrong))
262
+ self.assertFalse(self.conforms(graph, [node])[0])
263
+
264
+ def test_wrong_vector_label_or_axis_is_rejected(self):
265
+ IO = self.IO
266
+ graph = Graph()
267
+ for triple in self.data:
268
+ graph.add(triple)
269
+ step = IO["vector_evol_ret_1"]
270
+ old = self.data.value(step, RDFS.label)
271
+ graph.remove((step, RDFS.label, old))
272
+ graph.add((step, RDFS.label, Literal("fut", lang="es")))
273
+ self.assertFalse(self.conforms(graph, [step])[0])
274
+
275
+
276
+ if __name__ == "__main__":
277
+ unittest.main()
test_pi_hgat_t.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pruebas rápidas de la implementación PI-HGAT-T y su vínculo ontológico."""
2
+ import unittest
3
+ import torch
4
+
5
+ from experiments.optional.pi_hgat_t import PIHGATT, admissible_relation, features_for_node, read_data
6
+
7
+
8
+ class PIHGATTTests(unittest.TestCase):
9
+ def test_feature_vector_uses_only_phase_and_position(self):
10
+ self.assertEqual(features_for_node("T12_adv_P0"), [1.0, 0.0, 1.0, 0.0, 0.0])
11
+ self.assertEqual(features_for_node("T07_ret_P2"), [0.0, 1.0, 0.0, 0.0, 1.0])
12
+
13
+ def test_loaders_use_public_triad_ids_one_through_thirteen(self):
14
+ nodes, pairs = read_data()
15
+ expected = set(range(1, 14))
16
+ self.assertEqual(set(nodes), expected)
17
+ self.assertEqual(set(pairs), expected)
18
+ self.assertTrue(all(len(pairs[triad_id]) == 30 for triad_id in expected))
19
+
20
+ def test_attention_model_returns_three_relation_logits_per_candidate(self):
21
+ model = PIHGATT(dim=16, heads=4)
22
+ graph = torch.eye(5)[:5].unsqueeze(0)
23
+ pairs = torch.tensor([[0, 1], [1, 0]], dtype=torch.long)
24
+ self.assertEqual(tuple(model(graph, pairs).shape), (1, 2, 3))
25
+
26
+ def test_admissibility_uses_mirror_and_creation_properties(self):
27
+ # Índices locales 0..2=avance; 3..5=retroceso.
28
+ self.assertTrue(admissible_relation("mirrorOf", 0, 5))
29
+ self.assertFalse(admissible_relation("mirrorOf", 0, 3))
30
+ self.assertTrue(admissible_relation("creates", 0, 4))
31
+ self.assertTrue(admissible_relation("creates", 4, 0))
32
+ self.assertFalse(admissible_relation("creates", 0, 3))
33
+
34
+
35
+ if __name__ == "__main__":
36
+ unittest.main()
test_property_based.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Pruebas generativas y casos negativos para límites de índices, espejos y creates.
3
+
4
+ Cubre:
5
+ - Generación exhaustiva de pares (fase, pos) y verificación de partición
6
+ none / mirrorOf / creates (mutuamente excluyentes y completas).
7
+ - Casos negativos: índices fuera de rango, misma fase, posición no reflejada,
8
+ creates entre tríadas distintas, espejo no recíproco.
9
+ - Transformaciones temporales / involución de fase y posición.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import itertools
14
+ import unittest
15
+ from pathlib import Path
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+
19
+ PHASES = ("adv", "ret")
20
+ POSITIONS = (0, 1, 2)
21
+
22
+
23
+ def opposite_phase(p: str) -> str:
24
+ return "ret" if p == "adv" else "adv"
25
+
26
+
27
+ def mirror_pos(p: int) -> int:
28
+ return 2 - p
29
+
30
+
31
+ def is_mirror(sp: str, spos: int, tp: str, tpos: int) -> bool:
32
+ return sp != tp and tpos == mirror_pos(spos)
33
+
34
+
35
+ def is_creates(sp: str, spos: int, tp: str, tpos: int) -> bool:
36
+ if sp == tp:
37
+ return False
38
+ lateral_s = spos in (0, 2)
39
+ lateral_t = tpos in (0, 2)
40
+ return (lateral_s and tpos == 1) or (spos == 1 and lateral_t)
41
+
42
+
43
+ def classify(sp: str, spos: int, tp: str, tpos: int) -> str:
44
+ if is_mirror(sp, spos, tp, tpos):
45
+ return "mirrorOf"
46
+ if is_creates(sp, spos, tp, tpos):
47
+ return "creates"
48
+ return "none"
49
+
50
+
51
+ class ExhaustivePartitionTests(unittest.TestCase):
52
+ """Todas las combinaciones (fase, pos) × (fase, pos) no reflexivas."""
53
+
54
+ def test_partition_is_complete_and_exclusive(self):
55
+ nodes = list(itertools.product(PHASES, POSITIONS))
56
+ counts = {"none": 0, "mirrorOf": 0, "creates": 0}
57
+ for (sp, spos), (tp, tpos) in itertools.product(nodes, nodes):
58
+ if (sp, spos) == (tp, tpos):
59
+ continue
60
+ label = classify(sp, spos, tp, tpos)
61
+ counts[label] += 1
62
+ # exclusividad
63
+ m = is_mirror(sp, spos, tp, tpos)
64
+ c = is_creates(sp, spos, tp, tpos)
65
+ self.assertFalse(m and c)
66
+ if label == "mirrorOf":
67
+ self.assertTrue(m)
68
+ elif label == "creates":
69
+ self.assertTrue(c)
70
+ else:
71
+ self.assertFalse(m or c)
72
+ # 6 nodos, 30 pares dirigidos no reflexivos
73
+ self.assertEqual(sum(counts.values()), 30)
74
+ # Por tríada: 6 mirror, 8 creates, 16 none → ×13 = 78/104/208
75
+ self.assertEqual(counts["mirrorOf"], 6)
76
+ self.assertEqual(counts["creates"], 8)
77
+ self.assertEqual(counts["none"], 16)
78
+
79
+ def test_mirror_is_involution_on_position(self):
80
+ for p in POSITIONS:
81
+ self.assertEqual(mirror_pos(mirror_pos(p)), p)
82
+
83
+ def test_phase_opposite_is_involution(self):
84
+ for p in PHASES:
85
+ self.assertEqual(opposite_phase(opposite_phase(p)), p)
86
+ self.assertNotEqual(opposite_phase(p), p)
87
+
88
+
89
+ class NegativeCaseTests(unittest.TestCase):
90
+ """Casos que DEBEN fallar / clasificarse como none."""
91
+
92
+ def test_same_phase_never_mirror_or_creates(self):
93
+ for phase in PHASES:
94
+ for spos, tpos in itertools.product(POSITIONS, POSITIONS):
95
+ if spos == tpos:
96
+ continue
97
+ self.assertEqual(classify(phase, spos, phase, tpos), "none")
98
+
99
+ def test_wrong_mirror_position_is_none(self):
100
+ # adv P0 → ret P0 no es espejo (debería ser P2)
101
+ self.assertFalse(is_mirror("adv", 0, "ret", 0))
102
+ self.assertFalse(is_mirror("adv", 0, "ret", 1))
103
+ self.assertTrue(is_mirror("adv", 0, "ret", 2))
104
+
105
+ def test_creates_requires_center_involvement(self):
106
+ # lateral → lateral (sin centro) no es creates
107
+ self.assertFalse(is_creates("adv", 0, "ret", 2))
108
+ self.assertFalse(is_creates("adv", 2, "ret", 0))
109
+ # lateral → centro sí
110
+ self.assertTrue(is_creates("adv", 0, "ret", 1))
111
+ self.assertTrue(is_creates("adv", 1, "ret", 0))
112
+
113
+ def test_index_bounds(self):
114
+ """Posiciones fuera de {0,1,2} no son válidas en la especificación."""
115
+ for bad in (-1, 3, 4, 99):
116
+ # mirror_pos fuera de dominio no debe usarse en producción;
117
+ # documentamos el comportamiento aritmético
118
+ mirrored = 2 - bad
119
+ self.assertNotIn(bad, POSITIONS)
120
+ self.assertNotIn(mirrored, POSITIONS) if bad not in ( -1,) else True
121
+
122
+ def test_center_mirror_is_center(self):
123
+ self.assertEqual(mirror_pos(1), 1)
124
+ self.assertTrue(is_mirror("adv", 1, "ret", 1))
125
+
126
+
127
+ class GenerativeConsistencyTests(unittest.TestCase):
128
+ """Propiedades que deben sostenerse para cualquier tríada sintética."""
129
+
130
+ def test_mirror_count_per_synthetic_triad(self):
131
+ nodes = list(itertools.product(PHASES, POSITIONS))
132
+ mirrors = [
133
+ ((sp, spos), (tp, tpos))
134
+ for (sp, spos), (tp, tpos) in itertools.product(nodes, nodes)
135
+ if (sp, spos) != (tp, tpos) and is_mirror(sp, spos, tp, tpos)
136
+ ]
137
+ self.assertEqual(len(mirrors), 6)
138
+ # reciprocidad: si A mirrors B, B mirrors A
139
+ mirror_set = set(mirrors)
140
+ for a, b in mirrors:
141
+ self.assertIn((b, a), mirror_set)
142
+
143
+ def test_creates_count_per_synthetic_triad(self):
144
+ nodes = list(itertools.product(PHASES, POSITIONS))
145
+ creates = [
146
+ ((sp, spos), (tp, tpos))
147
+ for (sp, spos), (tp, tpos) in itertools.product(nodes, nodes)
148
+ if (sp, spos) != (tp, tpos) and is_creates(sp, spos, tp, tpos)
149
+ ]
150
+ self.assertEqual(len(creates), 8)
151
+
152
+ def test_no_overlap_mirror_creates_generative(self):
153
+ nodes = list(itertools.product(PHASES, POSITIONS))
154
+ for (sp, spos), (tp, tpos) in itertools.product(nodes, nodes):
155
+ if (sp, spos) == (tp, tpos):
156
+ continue
157
+ self.assertFalse(
158
+ is_mirror(sp, spos, tp, tpos) and is_creates(sp, spos, tp, tpos)
159
+ )
160
+
161
+
162
+ class AxisBoundTests(unittest.TestCase):
163
+ """Límites del eje vectorial [0, 4] alineados con FormalRules.lean."""
164
+
165
+ def test_axis_in_0_4(self):
166
+ for n in range(5):
167
+ self.assertTrue(0 <= n <= 4)
168
+
169
+ def test_axis_retreat_involution(self):
170
+ for n in range(5):
171
+ self.assertEqual(4 - (4 - n), n)
172
+
173
+ def test_axis_out_of_range_rejected(self):
174
+ for bad in (-1, 5, 6):
175
+ self.assertFalse(0 <= bad <= 4)
176
+
177
+
178
+ if __name__ == "__main__":
179
+ unittest.main()
test_property_links.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Pruebas de propiedades que conectan Lean, CSV y ontología generada."""
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import json
7
+ import unittest
8
+ from pathlib import Path
9
+
10
+ ROOT = Path(__file__).resolve().parents[1]
11
+
12
+
13
+ def load_spec() -> dict:
14
+ return json.loads((ROOT / "data" / "iom_spec.json").read_text(encoding="utf-8"))
15
+
16
+
17
+ def load_csv(name: str) -> list[dict]:
18
+ with (ROOT / "datasets" / name).open(encoding="utf-8", newline="") as fh:
19
+ return list(csv.DictReader(fh))
20
+
21
+
22
+ class PropertyLinksTests(unittest.TestCase):
23
+ """Conectan la especificación JSON, los CSV regenerados y las reglas formales."""
24
+
25
+ @classmethod
26
+ def setUpClass(cls):
27
+ cls.spec = load_spec()
28
+ cls.nodes = load_csv("triad_nodes.csv")
29
+ cls.relations = load_csv("relation_candidates.csv")
30
+ cls.vectors = load_csv("vector_steps.csv")
31
+ cls.n_triads = len(cls.spec["triads"]["adv"])
32
+
33
+ def test_spec_has_formal_version(self):
34
+ self.assertIn("spec_version", self.spec)
35
+ self.assertRegex(self.spec["spec_version"], r"^\d+\.\d+\.\d+$")
36
+ self.assertIn("schema_version", self.spec)
37
+
38
+ def test_node_count_matches_spec(self):
39
+ expected = self.n_triads * 2 * 3
40
+ self.assertEqual(len(self.nodes), expected)
41
+ indices = {int(r["triad_index"]) for r in self.nodes}
42
+ self.assertEqual(indices, set(range(1, self.n_triads + 1)))
43
+
44
+ def test_relation_candidate_count(self):
45
+ expected = self.n_triads * 6 * 5
46
+ self.assertEqual(len(self.relations), expected)
47
+
48
+ def test_gold_relation_counts(self):
49
+ counts = {"none": 0, "mirrorOf": 0, "creates": 0}
50
+ for row in self.relations:
51
+ counts[row["relation"]] += 1
52
+ self.assertEqual(counts["mirrorOf"], 78)
53
+ self.assertEqual(counts["creates"], 104)
54
+ self.assertEqual(counts["none"], 208)
55
+
56
+ def test_mirrorOf_property_holds_in_csv(self):
57
+ """Cada arista mirrorOf respeta: misma tríada, fase opuesta, posición reflejada."""
58
+ for row in self.relations:
59
+ if row["relation"] != "mirrorOf":
60
+ continue
61
+ src, tgt = row["source"], row["target"]
62
+ s_parts = src.split("_")
63
+ t_parts = tgt.split("_")
64
+ self.assertEqual(s_parts[0], t_parts[0], "misma tríada")
65
+ self.assertNotEqual(s_parts[1], t_parts[1], "fase opuesta")
66
+ s_pos = int(s_parts[2][1:])
67
+ t_pos = int(t_parts[2][1:])
68
+ self.assertEqual(t_pos, 2 - s_pos, "posición reflejada")
69
+
70
+ def test_creates_property_holds_in_csv(self):
71
+ """Cada arista creates respeta las cuatro reglas de creation_rules."""
72
+ rules = self.spec["creation_rules"]
73
+ allowed = set()
74
+ for rule in rules:
75
+ for sp in rule["source_positions"]:
76
+ for tp in rule["target_positions"]:
77
+ allowed.add((rule["source_phase"], sp, rule["target_phase"], tp))
78
+ for row in self.relations:
79
+ if row["relation"] != "creates":
80
+ continue
81
+ s_parts = row["source"].split("_")
82
+ t_parts = row["target"].split("_")
83
+ key = (s_parts[1], int(s_parts[2][1:]), t_parts[1], int(t_parts[2][1:]))
84
+ self.assertIn(key, allowed, f"creates no permitido: {row['source']} -> {row['target']}")
85
+
86
+ def test_vector_steps_count(self):
87
+ self.assertEqual(len(self.vectors), 20)
88
+
89
+ def test_lean_operators_file_exists_and_mentions_mirror(self):
90
+ """El código Lean debe existir y referenciar los operadores de espejo."""
91
+ lean_spec = (ROOT / "IOM" / "Specification.lean").read_text(encoding="utf-8")
92
+ self.assertIn("mirror", lean_spec.lower())
93
+ self.assertIn("TriadPosition", lean_spec)
94
+ self.assertTrue((ROOT / "IOM" / "Core.lean").exists())
95
+ self.assertTrue((ROOT / "IOM" / "Operators.lean").exists())
96
+
97
+ def test_ontology_ttl_contains_mirrorOf_and_creates(self):
98
+ ttl = (ROOT / "ontology" / "io_ontology.ttl").read_text(encoding="utf-8")
99
+ self.assertIn("mirrorOf", ttl)
100
+ self.assertIn("creates", ttl)
101
+ self.assertIn("OntoNode", ttl)
102
+
103
+ def test_shacl_shapes_exist(self):
104
+ shapes = (ROOT / "ontology" / "io_shapes.ttl").read_text(encoding="utf-8")
105
+ self.assertIn("mirrorOf", shapes)
106
+ self.assertIn("creates", shapes)
107
+
108
+
109
+ if __name__ == "__main__":
110
+ unittest.main()
test_score_independent_eval.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Pruebas del lector de anotaciones, null≠unsure y política de kappa sin truncar."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import tempfile
7
+ import unittest
8
+ from pathlib import Path
9
+ import importlib.util
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ SPEC = ROOT / "scripts" / "score_independent_eval.py"
13
+
14
+ spec = importlib.util.spec_from_file_location("score_independent_eval", SPEC)
15
+ mod = importlib.util.module_from_spec(spec)
16
+ spec.loader.exec_module(mod)
17
+
18
+
19
+ class TemplateFormatTests(unittest.TestCase):
20
+ def test_parse_empty_template(self):
21
+ data = {
22
+ "annotators": ["A1", "A2", "A3"],
23
+ "status": "pending_human_collection",
24
+ "items": [
25
+ {"id": "NR01", "annotations": {"A1": None, "A2": None, "A3": None}},
26
+ ],
27
+ }
28
+ aids, by_pair = mod.parse_template_format(data)
29
+ self.assertEqual(aids, ["A1", "A2", "A3"])
30
+ self.assertIsNone(by_pair["NR01"]["A1"])
31
+
32
+ def test_null_not_unsure(self):
33
+ data = {
34
+ "annotators": ["A1", "A2", "A3"],
35
+ "items": [
36
+ {
37
+ "id": "CT01",
38
+ "annotations": {"A1": "mirrorOf", "A2": "mirrorOf", "A3": None},
39
+ },
40
+ ],
41
+ }
42
+ _, by_pair = mod.parse_template_format(data)
43
+ self.assertIsNone(by_pair["CT01"]["A3"])
44
+
45
+ def test_invalid_label_rejected(self):
46
+ data = {
47
+ "annotators": ["A1"],
48
+ "items": [{"id": "X", "annotations": {"A1": "maybe"}}],
49
+ }
50
+ with self.assertRaises(ValueError):
51
+ mod.parse_template_format(data)
52
+
53
+
54
+ class NoTruncatePolicyTests(unittest.TestCase):
55
+ def test_heterogeneous_respondent_sets_excluded(self):
56
+ payload = {
57
+ "annotators": ["A1", "A2", "A3", "A4"],
58
+ "status": "partial",
59
+ "items": [
60
+ {
61
+ "id": "P1",
62
+ "annotations": {
63
+ "A1": "none",
64
+ "A2": "none",
65
+ "A3": "none",
66
+ "A4": None,
67
+ },
68
+ },
69
+ {
70
+ "id": "P3",
71
+ "annotations": {
72
+ "A1": "mirrorOf",
73
+ "A2": "mirrorOf",
74
+ "A3": None,
75
+ "A4": "mirrorOf",
76
+ },
77
+ },
78
+ ],
79
+ }
80
+ with tempfile.NamedTemporaryFile(
81
+ mode="w", suffix=".json", delete=False, encoding="utf-8"
82
+ ) as fh:
83
+ json.dump(payload, fh)
84
+ path = Path(fh.name)
85
+ try:
86
+ aids, by_pair, _meta = mod.load_annotations(path)
87
+ k_required = 3
88
+ respondent_sets = {}
89
+ for pid, ann_map in by_pair.items():
90
+ respondents = tuple(
91
+ aid for aid in aids if ann_map.get(aid) is not None
92
+ )
93
+ if len(respondents) == k_required:
94
+ respondent_sets[pid] = respondents
95
+ self.assertEqual(respondent_sets["P1"], ("A1", "A2", "A3"))
96
+ self.assertEqual(respondent_sets["P3"], ("A1", "A2", "A4"))
97
+ self.assertNotEqual(respondent_sets["P1"], respondent_sets["P3"])
98
+ finally:
99
+ path.unlink(missing_ok=True)
100
+
101
+
102
+ class FleissTests(unittest.TestCase):
103
+ def test_perfect_agreement(self):
104
+ ratings = [["none", "none", "none"], ["mirrorOf", "mirrorOf", "mirrorOf"]]
105
+ k = mod.fleiss_kappa(ratings, ["none", "mirrorOf", "creates", "unsure"])
106
+ self.assertAlmostEqual(k, 1.0)
107
+
108
+ def test_mismatched_lengths_raise(self):
109
+ with self.assertRaises(ValueError):
110
+ mod.fleiss_kappa(
111
+ [["none", "none"], ["none", "none", "none"]],
112
+ ["none", "mirrorOf"],
113
+ )
114
+
115
+
116
+ class AnnotatorPairsBlindTests(unittest.TestCase):
117
+ def test_default_pairs_have_no_structural_hints(self):
118
+ path = ROOT / "datasets" / "independent_eval" / "annotator_pairs.csv"
119
+ text = path.read_text(encoding="utf-8").lower()
120
+ forbidden = [
121
+ "fase",
122
+ "posición",
123
+ "posicion",
124
+ "lateral",
125
+ "centro",
126
+ "espejo",
127
+ "creates",
128
+ "mirror",
129
+ "avance",
130
+ "retroceso",
131
+ "canónico",
132
+ "canonico",
133
+ "vocabulario",
134
+ "13 filas",
135
+ "ajeno",
136
+ "new_concept",
137
+ "out_of_rules",
138
+ ]
139
+ for word in forbidden:
140
+ self.assertNotIn(
141
+ word,
142
+ text,
143
+ f"annotator_pairs.csv no debe contener la pista {word!r}",
144
+ )
145
+
146
+ def test_nc_items_use_generic_context(self):
147
+ path = ROOT / "datasets" / "independent_eval" / "annotator_pairs.csv"
148
+ lines = {
149
+ row.split(",")[0]: row
150
+ for row in path.read_text(encoding="utf-8").strip().splitlines()[1:]
151
+ }
152
+ for nid in ("NC01", "NC02", "NC03"):
153
+ self.assertIn(nid, lines)
154
+ self.assertIn("Par de conceptos", lines[nid])
155
+ self.assertNotIn("vocabulario", lines[nid].lower())
156
+ self.assertNotIn("13", lines[nid])
157
+
158
+
159
+ if __name__ == "__main__":
160
+ unittest.main()
test_validate_spec.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Validación del schema y de la spec canónica."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import unittest
7
+ from copy import deepcopy
8
+ from pathlib import Path
9
+
10
+ from jsonschema import Draft202012Validator
11
+
12
+ ROOT = Path(__file__).resolve().parents[1]
13
+ SCHEMA = json.loads((ROOT / "data" / "iom_spec.schema.json").read_text(encoding="utf-8"))
14
+ SPEC = json.loads((ROOT / "data" / "iom_spec.json").read_text(encoding="utf-8"))
15
+
16
+
17
+ class SpecificationSchemaTests(unittest.TestCase):
18
+ @classmethod
19
+ def setUpClass(cls):
20
+ cls.validator = Draft202012Validator(SCHEMA)
21
+
22
+ def test_canonical_spec_conforms_to_schema(self):
23
+ errors = list(self.validator.iter_errors(SPEC))
24
+ self.assertEqual(errors, [])
25
+
26
+ def test_canonical_position_metadata_and_triad_indexing_are_accepted(self):
27
+ spec = deepcopy(SPEC)
28
+ spec["positions"]["indices"] = [0, 1, 2]
29
+ spec["positions"]["adv_labels"] = ["→", "0", "→"]
30
+ spec["positions"]["ret_labels"] = ["←", "0", "←"]
31
+ spec["positions"]["perspectives"] = ["Ind", "D", "Tot"]
32
+ spec["triads"]["index_base"] = 1
33
+ spec["triads"]["note"] = "Los arrays empiezan en cero; triad_index es 1-based."
34
+ errors = list(self.validator.iter_errors(spec))
35
+ self.assertEqual(errors, [])
36
+
37
+ def test_invalid_position_metadata_is_rejected(self):
38
+ invalid_spec = deepcopy(SPEC)
39
+ invalid_spec["positions"]["indices"] = [0, 1]
40
+ errors = list(self.validator.iter_errors(invalid_spec))
41
+ self.assertTrue(any(list(error.absolute_path)[:1] == ["positions"] for error in errors))
42
+
43
+ def test_unknown_triad_metadata_is_rejected(self):
44
+ spec = deepcopy(SPEC)
45
+ spec["triads"]["unexpected"] = True
46
+ errors = list(self.validator.iter_errors(spec))
47
+ self.assertTrue(any(list(error.absolute_path) == ["triads"] for error in errors))
48
+
49
+ def test_missing_spec_version_is_rejected(self):
50
+ invalid_spec = deepcopy(SPEC)
51
+ del invalid_spec["spec_version"]
52
+ errors = list(self.validator.iter_errors(invalid_spec))
53
+ self.assertTrue(any("spec_version" in error.message for error in errors))
54
+
55
+ def test_malformed_semantic_version_is_rejected(self):
56
+ invalid_spec = deepcopy(SPEC)
57
+ invalid_spec["spec_version"] = "1.1"
58
+ errors = list(self.validator.iter_errors(invalid_spec))
59
+ self.assertTrue(any(list(error.absolute_path) == ["spec_version"] for error in errors))
60
+
61
+ def test_purpose_is_present_and_matches_schema(self):
62
+ """La unidad informativa queda registrada en el spec canónico."""
63
+ self.assertIn("purpose", SPEC)
64
+ purpose = SPEC["purpose"]
65
+ self.assertEqual(purpose["id"], "informational_unit_creation")
66
+ self.assertIn("mínima estructura autocontenida", purpose["definition"])
67
+ self.assertIn("criterion", purpose)
68
+ errors = list(self.validator.iter_errors(SPEC))
69
+ self.assertEqual(errors, [])
70
+
71
+ def test_generated_from_records_purpose_id(self):
72
+ stamp = json.loads((ROOT / "datasets" / "GENERATED_FROM.json").read_text(encoding="utf-8"))
73
+ self.assertEqual(stamp.get("purpose_id"), "informational_unit_creation")
74
+ self.assertEqual(stamp.get("spec_version"), SPEC["spec_version"])
75
+
76
+
77
+ if __name__ == "__main__":
78
+ unittest.main()