diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000000000000000000000000000000000..56869cfc2f20cb0bd84a91a516e90ca2de8493a7 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "IOM - Realidad I.O", + "image": "mcr.microsoft.com/devcontainers/universal:2", + "features": { + "ghcr.io/devcontainers/features/python:1": { + "version": "3.11" + } + }, + "postCreateCommand": "curl https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -sSf | sh -s -- -y --default-toolchain leanprover/lean4:v4.9.0 && source $HOME/.elan/env && pip install rdflib pyshacl", + "postAttachCommand": "source $HOME/.elan/env", + "customizations": { + "vscode": { + "extensions": [ + "leanprover.lean4" + ] + } + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..6d0d531419831a0a16c92d69b0c0618f78b40eb5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,65 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +# Único workflow de validez del repositorio. +# Encuentro (EXP-A/E, PI-HGAT-T) vive en workflows/encuentro.yml (manual). + +jobs: + lean: + name: Lean 4 build (SelfGenesis) + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: leanprover/lean-action@v1 + with: + build: true + + core: + name: Núcleo autónomo (punto fijo, SHACL, invariancia) + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: '3.12' + cache: pip + cache-dependency-path: requirements-lock.txt + - name: Install locked dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -r requirements-lock.txt + - name: Validate iom_spec.json against JSON Schema + run: python scripts/validate_spec.py + - name: Check specification migrations + run: python scripts/migrate_spec.py --check + - name: Generate ontology/CSV and require versioned CSV match + run: python scripts/check_generated_committed.py + - name: Punto fijo idempotente (CSV + sello spec_version) + run: python scripts/self_bootstrap.py --passes 2 + - name: Check spec ↔ CSV sync + run: python scripts/sync_spec_artifacts.py --check + - name: Regenerar TTL (generador + materialize determinista) + run: | + python scripts/generate_ontology.py + python scripts/materialize_ttl.py + - name: Unit tests (ontología, reglas, schema) + run: | + python -m unittest \ + tests.test_formal_rules_bridge \ + tests.test_metrics_audit \ + tests.test_ontology \ + tests.test_property_based \ + tests.test_property_links \ + tests.test_score_independent_eval \ + tests.test_validate_spec \ + -v + - name: OWL RL + SHACL + run: python scripts/validate_shacl.py + - name: Invariancia no trivial (+ control negativo) + run: python scripts/measure_invariance.py diff --git a/.github/workflows/encuentro.yml b/.github/workflows/encuentro.yml new file mode 100644 index 0000000000000000000000000000000000000000..6cc345cd0fedb1bfb77782467e4df1d52bb9e1f6 --- /dev/null +++ b/.github/workflows/encuentro.yml @@ -0,0 +1,34 @@ +name: Encuentro (manual) + +# No forma parte del estado de validez del commit. +# Disparo manual: dominio, κ histórico, PI-HGAT-T / baselines. + +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + encounter: + name: EXP-A / EXP-E / diagnóstico sintético + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: '3.12' + cache: pip + cache-dependency-path: requirements-lock.txt + - name: Install locked dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -r requirements-lock.txt + - name: Score independent evaluation (histórico; sin ACCESS_LOG) + run: python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json + - name: PI-HGAT-T (diagnóstico circular) + run: python experiments/optional/pi_hgat_t.py + - name: Baselines + run: python experiments/optional/baselines.py + - name: EXP-E domain mapping + run: python experiments/domain_mapping/validate_examples.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b8001017e8745228ca2263005da2f59f969a354f --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.lake/ +.venv/ +__pycache__/ +*.py[cod] +.pytest_cache/ +dist/ diff --git a/AUDITORIA.md b/AUDITORIA.md new file mode 100644 index 0000000000000000000000000000000000000000..1317718184a8103d2ecf4d8b28e560edabacab5e --- /dev/null +++ b/AUDITORIA.md @@ -0,0 +1,42 @@ +# Auditoría IOM — auto-fundamentación y encuentros + +**Jerarquía canónica:** [`EXPERIMENTOS.md`](EXPERIMENTOS.md) +**Delimitación:** [`docs/DELIMITACION_EPISTEMOLOGICA.md`](docs/DELIMITACION_EPISTEMOLOGICA.md) + +## 1. Capa primaria — autonomía (punto fijo) + +El repositorio es **válido como sistema** si: + +1. `self_bootstrap.py --passes 2` deja CSV idénticos a HEAD ($S_{n+1}=S_n$). +2. `lake build` incluye `IOM/SelfGenesis.lean` (conteos derivados). +3. SHACL conforme sobre TTL regenerado. +4. `measure_invariance.py` reporta invariancia **no trivial** (control negativo). + +`AUDITORIA_AUTO.md` **no se versiona**. Se genera bajo `experiments/results/` (CI/local) y es solo un informe fechado. **No** es prueba de punto fijo ni fundamento. + +## 2. Capa secundaria — invariancia + +Regeneración de etiquetas desde (fase, pos); LOO por tríada; corrupción de una arista detectada. + +## 3. Encuentro — EXP-E y EXP-A (no fundamentan) + +| Experimento | Rol | +|-------------|-----| +| EXP-E (dominio / Mictlán) | Expresabilidad; un fallo de anclaje **no** invalida el núcleo | +| EXP-A (κ) | Resonancia provisional **solo** con log de acceso e instrumento ciego | + +κ ≈ 0.6871 es registro histórico. Sin `ACCESS_LOG` de exposición previa **no** se declara «demostración provisional completada» en esta auditoría. + +## 4. Diagnóstico sintético (circular) + +| Método | Accuracy | +|--------|---------:| +| PI-HGAT-T (fase + posición) | 1.0000 | +| MLP / reglas sin grafo | 1.0000 | + +Muestran que la regla ya está en las features; no son validez semántica mundana. + +## 5. Referencias + +- Técnica: [`docs/AUDITORIA_TECNICA.md`](docs/AUDITORIA_TECNICA.md) +- Métricas sintéticas: [`docs/AUDITORIA_METRICAS.md`](docs/AUDITORIA_METRICAS.md) diff --git a/EXPERIMENTOS.md b/EXPERIMENTOS.md new file mode 100644 index 0000000000000000000000000000000000000000..23fea35c2dbed63126c73f16f82ec61bd4035356 --- /dev/null +++ b/EXPERIMENTOS.md @@ -0,0 +1,71 @@ +# Experimentos del marco I.O. — unidad informativa + +> Propósito: construcción formal de **unidad informativa**. La autonomía verificable es el mecanismo de constitución y validación. + +> Manifiesto: [`MANIFIESTO.md`](MANIFIESTO.md) · Ensayo: [`docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md) + +El marco se auto-constituye. Lo externo es **encuentro**, no fundamento. + +**Intérprete:** `.venv/bin/python` tras instalar `requirements-lock.txt`. + +--- + +## 1. Jerarquía + +| Prioridad | Capa | Runner | ¿Bloquea «repo válido»? | +|:---------:|------|--------|:-----------------------:| +| **1** | Punto fijo | `self_bootstrap.py --passes 2` | sí | +| **1b** | SelfGenesis | `lake build` | sí | +| **2** | Invariancia no trivial | `measure_invariance.py` | sí | +| **3** | Destino Mictlán | EXP-E | **no** (encuentro) | +| **4** | Resonancia κ | EXP-A | **no** (requiere ACCESS_LOG) | + +--- + +## 2. Punto fijo + +```bash +.venv/bin/python scripts/self_bootstrap.py --passes 2 +.venv/bin/python scripts/self_bootstrap.py --with-manifest --passes 2 # tras versionar MANIFEST +``` + +`io_ontology.ttl` no entra en el manifiesto (serialización no determinista). `AUDITORIA_AUTO.md` y `experiments/results/` no se versionan: son derivados de encuentro. + +--- + +## 3. Invariancia no trivial + +```bash +.venv/bin/python scripts/measure_invariance.py +``` + +Control negativo obligatorio. + +--- + +## 4. EXP-E (opcional) + +```bash +.venv/bin/python experiments/domain_mapping/validate_examples.py +``` + +Un fallo de anclaje de dominio **no** invalida el núcleo formal. + +--- + +## 5. EXP-A (opcional; κ no cerrado sin log) + +Instrumento: `datasets/independent_eval/instrument/`. + +Un κ histórico (~0.6871) **no** se presenta como demostración completada mientras no exista `ACCESS_LOG` de exposición previa. `rule_reference.json` es post-hoc; no se entrega al anotador. + +--- + +## 6. Diagnóstico circular (opcional) + +PI-HGAT-T / baselines (`experiments/optional/`): recuperan la regla embebida en (fase, pos). No son criterio primario. + +```bash +.venv/bin/python experiments/optional/pi_hgat_t.py +.venv/bin/python experiments/optional/baselines.py +``` diff --git a/IOM.lean b/IOM.lean new file mode 100644 index 0000000000000000000000000000000000000000..3545ff52a478132adefb94ffa9fe088898688b2e --- /dev/null +++ b/IOM.lean @@ -0,0 +1,6 @@ +import IOM.Core +import IOM.Operators +import IOM.Specification +import IOM.FormalRules +import IOM.SelfGenesis +import IOM.InformationalUnit diff --git a/IOM/Core.lean b/IOM/Core.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1e572faf434329e406fca08113a957eac53f542 --- /dev/null +++ b/IOM/Core.lean @@ -0,0 +1,18 @@ +namespace IOM + +/-- Estado informativo discreto: instante entero y secuencia de unidades. -/ +structure State where + time : Int + payload : List String + deriving Repr, DecidableEq + +/-- Vacío ontológico en el instante indicado. -/ +def vacuum (t : Int) : State := ⟨t, []⟩ + +/-- Eliminación estable de elementos repetidos. -/ +def red (σ : List String) : List String := σ.eraseDups + +/-- Inversión lateral de una secuencia categorial. -/ +def invert (σ : List String) : List String := σ.reverse + +end IOM diff --git a/IOM/FormalRules.lean b/IOM/FormalRules.lean new file mode 100644 index 0000000000000000000000000000000000000000..3098879f76c844b4c500cb3fea6889390b642ad0 --- /dev/null +++ b/IOM/FormalRules.lean @@ -0,0 +1,112 @@ +import IOM.Specification + +namespace IOM + +/-! +# Reglas formales del marco I.O. (espejo, creates, vectores) + +Predicados Lean que codifican las reglas estructurales de la especificación +operativa. Las relaciones generadas desde JSON deben satisfacerlos; +la comprobación automática está en `tests/test_formal_rules_bridge.py`. + +## Dónde reside cada restricción + +| Condición | Predicado Lean | Capa de datos | +|---|---|---| +| Fase opuesta + posición espejada | `isMirror` | CSV / SHACL | +| Fase opuesta + lateral↔₀ | `isCreates` | CSV / SHACL | +| **Misma tríada** (índice de fila) | `sameTriad` + `isMirrorRel` / `isCreatesRel` | CSV (`same_triad` en Python), SHACL (mismo prefijo Txx) | + +`TriadNode` incluye `triadId` para que la pertenencia a la misma tríada sea +parte del tipo formal, no solo una comprobación externa en Python. +-/ + +/-- Identificador de tríada (fila 0..12). -/ +abbrev TriadId := Nat + +/-- Nodo estructural: tríada + fase + posición (sin etiqueta léxica). -/ +structure TriadNode where + triadId : TriadId + phase : TriadPhase + pos : TriadPosition + deriving DecidableEq, Repr + +/-- Misma tríada (condición de dominio de mirror/creates operativos). -/ +def sameTriad (a b : TriadNode) : Prop := a.triadId = b.triadId + +/-- Fase opuesta. -/ +def TriadPhase.opposite : TriadPhase → TriadPhase + | .advance => .retreat + | .retreat => .advance + +theorem opposite_involutive (p : TriadPhase) : p.opposite.opposite = p := by + cases p <;> rfl + +theorem opposite_ne (p : TriadPhase) : p.opposite ≠ p := by + cases p <;> decide + +/-- Condición posicional de espejo (fase opuesta + posición espejada), sin exigir tríada. -/ +def isMirrorPositional (a b : TriadNode) : Prop := + a.phase.opposite = b.phase ∧ a.pos.mirror = b.pos + +/-- `mirrorOf` operativo: misma tríada ∧ condición posicional de espejo. -/ +def isMirrorRel (a b : TriadNode) : Prop := + sameTriad a b ∧ isMirrorPositional a b + +/-- Alias histórico: `isMirror` = condición posicional (retrocompat docs). + Preferir `isMirrorRel` para la relación operativa completa. -/ +def isMirror (a b : TriadNode) : Prop := isMirrorPositional a b + +theorem isMirror_implies_opposite_phase (a b : TriadNode) (h : isMirror a b) : + a.phase ≠ b.phase := by + intro heq + have : a.phase.opposite = a.phase := by + calc a.phase.opposite = b.phase := h.1 + _ = a.phase := heq.symm + exact opposite_ne a.phase this + +theorem isMirror_implies_mirrored_pos (a b : TriadNode) (h : isMirror a b) : + b.pos = a.pos.mirror := h.2.symm + +theorem isMirrorRel_implies_same_triad (a b : TriadNode) (h : isMirrorRel a b) : + sameTriad a b := h.1 + +/-- Las cuatro reglas de creación entre fases opuestas (solo posicional). -/ +def lateral (p : TriadPosition) : Prop := p = .«→» ∨ p = .«←» + +def isCreatesPositional (a b : TriadNode) : Prop := + a.phase.opposite = b.phase ∧ + ((lateral a.pos ∧ b.pos = .«₀») ∨ (a.pos = .«₀» ∧ lateral b.pos)) + +/-- `creates` operativo: misma tríada ∧ condición posicional de creación. -/ +def isCreatesRel (a b : TriadNode) : Prop := + sameTriad a b ∧ isCreatesPositional a b + +/-- Alias histórico. Preferir `isCreatesRel` para la relación operativa. -/ +def isCreates (a b : TriadNode) : Prop := isCreatesPositional a b + +theorem isCreatesRel_implies_same_triad (a b : TriadNode) (h : isCreatesRel a b) : + sameTriad a b := h.1 + +/-- Conteos canónicos derivados de las reglas (13 tríadas). -/ +def expectedMirrorDirected : Nat := 78 +def expectedCreatesDirected : Nat := 104 +def expectedNoneDirected : Nat := 208 +def expectedVectorSteps : Nat := 20 +def expectedNodes : Nat := 78 + +theorem expected_partition : + expectedMirrorDirected + expectedCreatesDirected + expectedNoneDirected = 390 := by + native_decide + +theorem expected_nodes_formula : expectedNodes = 13 * 2 * 3 := by native_decide + +theorem expected_vector_steps_formula : expectedVectorSteps = 4 * 5 := by native_decide + +/-- Índice de eje en $[0,4]$. -/ +theorem axis_bound (n : Nat) (h : n ≤ 4) : n ≤ 4 := h + +/-- Simetría del eje en secuencias de retroceso. -/ +theorem axis_retreat_involution (n : Nat) (h : n ≤ 4) : 4 - (4 - n) = n := by omega + +end IOM diff --git a/IOM/InformationalUnit.lean b/IOM/InformationalUnit.lean new file mode 100644 index 0000000000000000000000000000000000000000..016967a0a866796b288bc236dea73cda3a504c74 --- /dev/null +++ b/IOM/InformationalUnit.lean @@ -0,0 +1,43 @@ +/- + Núcleo mínimo de la unidad informativa. + + No formaliza la metafísica completa: solo propiedades verificables — + estructura identificable, relaciones derivables, trazabilidad interna. +-/ +import IOM.Specification +import IOM.FormalRules + +namespace IOM + +/-- Núcleo abstracto: nodos con igualdad decidible y relación binaria. + Instantiable sobre los nodos de una tríada o del grafo completo. -/ +structure InformationalUnit (α : Type) where + /-- Relación estructural entre nodos (p. ej. isMirrorRel ∨ isCreatesRel). -/ + related : α → α → Prop + /-- Identidad decidible de nodos (trazabilidad de la distinción). -/ + [decEq : DecidableEq α] + +/-- Relación canónica IOM sobre nodos de tríada. -/ +def triadRelated (a b : TriadNode) : Prop := + isMirrorRel a b ∨ isCreatesRel a b + +/-- Unidad informativa operativa sobre nodos (tríada + fase + posición). -/ +def triadInformationalUnit : InformationalUnit TriadNode where + related := triadRelated + +/-- El espejo de posiciones es involutivo: la transformación es reversible. -/ +theorem mirror_traceable (p : TriadPosition) : p.mirror.mirror = p := + mirror_involutive p + +/-- La fase opuesta es involutiva: ida y vuelta conservan la identidad de fase. -/ +theorem phase_traceable (p : TriadPhase) : p.opposite.opposite = p := + opposite_involutive p + +/-- Misma tríada es condición de dominio de las relaciones operativas. -/ +theorem related_same_triad (a b : TriadNode) (h : triadRelated a b) : + sameTriad a b := by + cases h with + | inl hm => exact isMirrorRel_implies_same_triad a b hm + | inr hc => exact isCreatesRel_implies_same_triad a b hc + +end IOM diff --git a/IOM/Operators.lean b/IOM/Operators.lean new file mode 100644 index 0000000000000000000000000000000000000000..002031b6af0ff1ae3c1be4d47bf804f54ba3159d --- /dev/null +++ b/IOM/Operators.lean @@ -0,0 +1,65 @@ +import IOM.Core + +namespace IOM + +/-! +# Operadores temporales y la díada del inframundo + +Correspondencia con el ensayo de autonomía absoluta: + +* `E` (evolución temporal) / proyección hacia estructura ↔ **Mictecacíhuatl** + (fuerza ascendente: recombina, expande, perfecciona). +* `Ivo` (involución temporal) / retorno ↔ **Mictlantecuhtli** + (fuerza descendente: repliega, despoja, purifica). +* `strict_fixed_point` — el vacío se restaura bajo la composición: + encarnación mínima de auto-creación desde el vacío sin residuo exterior. + +Ver también `IOM/SelfGenesis.lean` y +`docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`. +-/ + +/-- Evolución: avanza un instante y conserva la carga informativa. + Lectura: Mictecacíhuatl — fuerza ascendente. -/ +def E (s : State) : State := ⟨s.time + 1, s.payload⟩ + +/-- Supresión directa: elimina redundancias sin cambiar el instante. -/ +def S_fwd (s : State) : State := ⟨s.time, red s.payload⟩ + +/-- Involución: retrocede un instante e invierte la orientación categorial. + Lectura: Mictlantecuhtli — fuerza descendente. -/ +def Ivo (s : State) : State := ⟨s.time - 1, invert s.payload⟩ + +/-- Supresión retroactiva: conserva exactamente un estado vacío y, en otro +caso, retrocede con el contenido reducido e invertido. -/ +def S_rev (s : State) : State := + if s.payload = [] then ⟨s.time, []⟩ else ⟨s.time - 1, red (invert s.payload)⟩ + +theorem E_vacuum (t : Int) : E (vacuum t) = vacuum (t + 1) := by rfl +theorem S_fwd_vacuum (t : Int) : S_fwd (vacuum t) = vacuum t := by rfl +theorem Ivo_vacuum (t : Int) : Ivo (vacuum t) = vacuum (t - 1) := by rfl +theorem S_rev_vacuum (t : Int) : S_rev (vacuum t) = vacuum t := by rfl + +/-- La composición temporal restaura exactamente cualquier vacío + (auto-creación mínima desde el vacío). -/ +theorem strict_fixed_point (t : Int) : S_rev (Ivo (E (vacuum t))) = vacuum t := by + simp [E, Ivo, S_rev, vacuum, red, invert] + +theorem E_preserves_payload (s : State) : (E s).payload = s.payload := by rfl +theorem S_fwd_preserves_time (s : State) : (S_fwd s).time = s.time := by rfl +theorem S_fwd_applies_red (s : State) : (S_fwd s).payload = red s.payload := by rfl +theorem Ivo_preserves_time_rule (s : State) : (Ivo s).time = s.time - 1 := by rfl +theorem Ivo_applies_inversion (s : State) : (Ivo s).payload = invert s.payload := by rfl +theorem S_rev_empty_payload (s : State) : (S_rev s).payload = red (invert s.payload) := by + by_cases h : s.payload = [] <;> + simp [S_rev, h, red, invert, List.eraseDups, List.eraseDups.loop] +theorem S_rev_empty_time (t : Int) : (S_rev (vacuum t)).time = t := by rfl +theorem E_then_Ivo_time (s : State) : (Ivo (E s)).time = s.time := by simp [E, Ivo] +theorem Ivo_then_E_time (s : State) : (E (Ivo s)).time = s.time := by simp [E, Ivo] +theorem invert_involutive (σ : List String) : invert (invert σ) = σ := by simp [invert] + +theorem no_repetition (σ : List String) (h : σ ≠ []) : + S_rev (Ivo (E (⟨0, σ⟩ : State))) ≠ ⟨0, σ⟩ := by + have hr : invert σ ≠ [] := by simpa [invert] using h + simp [E, Ivo, S_rev, hr] + +end IOM diff --git a/IOM/SelfGenesis.lean b/IOM/SelfGenesis.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f035c2d28dca82ce27decadbbb45ab5c3d57da9 --- /dev/null +++ b/IOM/SelfGenesis.lean @@ -0,0 +1,61 @@ +import IOM.FormalRules +import IOM.Specification + +namespace IOM + +/-! +# Auto-creación formal (SelfGenesis) + +Los conteos canónicos se **derivan** de la estructura finita (13 × 2 × 3, +espejos por tríada, reglas de creación), no se asumen como literales opacos. + +Correspondencia con el ensayo: +* Mictecacíhuatl (Evolución) ↔ fase `advance` / fuerza ascendente +* Mictlantecuhtli (Involución) ↔ fase `retreat` / fuerza descendente +* `isMirrorRel` ↔ polaridad complementaria de la díada +* `isCreatesRel` ↔ auto-distinción generativa desde el vacío-matriz +-/ + +/-- 13 tríadas × 2 fases × 3 posiciones = 78 nodos (fórmula, no literal suelto). -/ +theorem nodes_from_structure : 13 * 2 * 3 = 78 := by native_decide + +theorem expected_nodes_matches_structure : expectedNodes = 13 * 2 * 3 := + expected_nodes_formula + +/-- Por tríada: 3 posiciones × 2 sentidos de espejo = 6 aristas `mirrorOf` dirigidas. -/ +def mirrorsPerTriad : Nat := 3 * 2 + +theorem mirrors_per_triad : mirrorsPerTriad = 6 := by native_decide + +/-- 13 tríadas × 6 espejos dirigidos = 78. -/ +theorem mirrors_from_structure : 13 * mirrorsPerTriad = 78 := by native_decide + +theorem expected_mirrors_matches_structure : + expectedMirrorDirected = 13 * mirrorsPerTriad := by + native_decide + +/-- Candidatos dirigidos por tríada: 6 nodos × 5 destinos = 30; × 13 = 390. -/ +theorem candidates_from_structure : 13 * (6 * 5) = 390 := by native_decide + +theorem partition_sums_to_candidates : + expectedMirrorDirected + expectedCreatesDirected + expectedNoneDirected = 390 := + expected_partition + +/-- Vectores: 4 secuencias × 5 ejes. -/ +theorem vectors_from_structure : 4 * 5 = 20 := by native_decide + +theorem expected_vectors_matches_structure : expectedVectorSteps = 4 * 5 := + expected_vector_steps_formula + +/-- Díada de fases: involutiva y sin punto fijo (Evolución ↔ Involución). -/ +theorem dual_phase_involutive (p : TriadPhase) : p.opposite.opposite = p := + opposite_involutive p + +theorem dual_phase_no_fixed_point (p : TriadPhase) : p.opposite ≠ p := + opposite_ne p + +theorem mirror_requires_dual_phase (a b : TriadNode) (h : isMirror a b) : + a.phase ≠ b.phase := + isMirror_implies_opposite_phase a b h + +end IOM diff --git a/IOM/Specification.lean b/IOM/Specification.lean new file mode 100644 index 0000000000000000000000000000000000000000..71459742dac73de112c9a2d559659663386fad7b --- /dev/null +++ b/IOM/Specification.lean @@ -0,0 +1,47 @@ +namespace IOM + +/-- Posición discreta de un concepto en una tríada. + Etiquetas canónicas: avance → | 0 | → ; retroceso ← | 0 | ← . + Constructores formales: → / ₀ / ← (índice 0/1/2). El espejo intercambia laterales. -/ +inductive TriadPosition where + /-- Lateral de avance (etiqueta →). -/ + | «→» + /-- Centro (etiqueta 0). -/ + | «₀» + /-- Lateral de retroceso (etiqueta ←). -/ + | «←» + deriving DecidableEq, Repr + +/-- Coordenada ordinal asociada a cada posición de la tríada. -/ +def TriadPosition.index : TriadPosition → Nat + | .«→» => 0 + | .«₀» => 1 + | .«←» => 2 + +/-- Intercambio lateral usado al espejar avance y retroceso. -/ +def TriadPosition.mirror : TriadPosition → TriadPosition + | .«→» => .«←» + | .«₀» => .«₀» + | .«←» => .«→» + +theorem mirror_involutive (p : TriadPosition) : p.mirror.mirror = p := by + cases p <;> rfl + +theorem mirror_index (p : TriadPosition) : p.mirror.index = 2 - p.index := by + cases p <;> rfl + +/-- Fase de la tabla de avance/retroceso. -/ +inductive TriadPhase where + | advance + | retreat + deriving DecidableEq, Repr + +/-- Coordenada permitida en los vectores de cinco pasos. -/ +def validVectorIndex (n : Nat) : Prop := n ≤ 4 + +theorem vector_index_bounds (n : Nat) (h : validVectorIndex n) : n ≤ 4 := h + +theorem vector_index_mirror (n : Nat) (h : n ≤ 4) : 4 - (4 - n) = n := by + omega + +end IOM diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7434759a03b84dd28663ad23fb883617e311d0d6 --- /dev/null +++ b/LICENSE @@ -0,0 +1 @@ +MIT License - Copyright (c) 2026 Luis Rey García Figueroa diff --git a/MANIFEST.sha256 b/MANIFEST.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..9e07a43f57a9a277f08f441b9979b3c80e7019de --- /dev/null +++ b/MANIFEST.sha256 @@ -0,0 +1,112 @@ +ae5dc320e24300032e5b5973e39467d70582f5db6b6d9b93cf0db64537a0e776 .github/workflows/ci.yml +ccb359bc91bb5f0672edea6c9fdda6763e6c495874505b9514297e95badf98e7 .gitignore +d8f8cea4d5520509e8727a55048724e724e34e098e5bcc9111981aabce502bd4 AUDITORIA.md +f1bc11f781dd6e3611e6a78c806219b3e4d8794cbc9aa1bb124b665bea5d7be1 EXPERIMENTOS.md +c3b25eb530267c813d3f7220097b77591b7f415aa085b11ef7e9e6bf297cc386 IOM/Core.lean +671a726e868fb189f066452322833740eb7d84ae4f5e9b781959c663f66b5f32 IOM/FormalRules.lean +7b73f9d3750bb7eb8fb9f0d2af85c55e504f4012722b41f470338f9da63f4f1c IOM/Operators.lean +f215423b20bb7e8d82aca27b54f7f3e3c87608d27bfc5549dde77ba36382c8f9 IOM/SelfGenesis.lean +362004daa99ed1a76ea40edc1480bffefc3c994cf2b86dc94ffc71f42c7d81b4 IOM/Specification.lean +cb772375687bf2c83f39fd1ab501d5722a050bf2c89abf188a391f3194092fcf IOM.lean +38e303c1c7f3338f3c55b4d11b3c6fabc2d62d6b76f3c524b624db1b4b3d605c LICENSE +578eca08e7b1eadcca4ecafbe6ce3a8296456c86502e77e6fd297d75c7a50be8 MANIFIESTO.md +945686b005094d6133709aa771cc0ea9d314cc43b5ffccb83c59e40b794bfa86 README.md +5c0fcdf2dc06a7ab4946347aa2ac5e8e21182cc30c3742c5d7a713d6cb94e1dd REPRODUCCION.md +90a6fdbf991e82d8c1bf8782a6950aaf15ff7f925ed2d65ee0ee3ff8332480d1 data/iom_spec.json +6ae3969ba64a3540822aa633329e2b130b4cf3a9cb20e42d0c73d0ee06975568 data/iom_spec.schema.json +e92332d0cec61e88af2c1c915f8ce5c38a777201e1a9d14d3b1b0b1277a1cbb8 datasets/GENERATED_FROM.json +15d6683b656ae4d973c05678bb457c95322b5e4cff197ec8391972520f25fa7b datasets/external_eval/README.md +ecd2fd86e21f06f09141a11d19ef6a9453c02686e6ac4a559c8690f7708317d4 datasets/independent_eval/PROTOCOL.json +5ead6664fb053fe580c979657b2d660600fba597c893337522fbe269078dc079 datasets/independent_eval/README.md +9e7c9f408e1330f823c14b06ff15516c803b8c4d5fb1407b89344fa489bf5084 datasets/independent_eval/SCORE_REPORT.md +d6ff98d3c792df159d4bcccf757ae17f2e247a2b6264b75703c9bc182e31a39f datasets/independent_eval/annotations.json +8e96cd03c8c185cabfc9031a21d5bf5e8acab7ba27f3b5969355ed462687fe3d datasets/independent_eval/annotations_template.json +4a7ea0fbff03f6bdf4075e84e04375fd53ad252426563d4ab09bfa8284849abf datasets/independent_eval/annotator_pairs.csv +314ace6c4f66793d7f4c96fcacd90b0c5ca17d7bcdbec49a66b255b353ef4c2c datasets/independent_eval/annotator_pairs_rule_application.csv +dcee7fe7fb1abae50701478a6b415cb42512794d42e34fd04c7140b976d2978b datasets/independent_eval/independent_pairs.csv +9ec1d7f68400a69a6ea8ae481f1880699da249be7364441052413564d21d32a6 datasets/independent_eval/instrument/ACCESS_LOG.template.json +bb0d03faf012b7a157337e64fed1a964dd4e287e71b1fd06bd811cc219ef23ea datasets/independent_eval/instrument/INSTRUCTIONS.md +29c8b38427efbf4863b09f82d67b6f69b1df3eb10a645755d10c146a5be53292 datasets/independent_eval/instrument/README.md +493407d0b991028bc6929c55c218aef27a2136d38c9fe0a6e093c6c5a8d95b32 datasets/independent_eval/instrument/pairs.csv +692663010fc73f515e8175f65388cc0e4f0e6c1c7ff14bd1f96491348027710a datasets/independent_eval/rule_reference.json +8dbe02fa31b1c9e90c3413b51dd140e7a72fb2a57f96c96dfdb8d35f1198638c datasets/ingestion/README.md +bc105e08dcd2e06b854ffd28d077d4d95964a4e7895bfd0f3712753347586a0a datasets/ingestion/aligned/.gitkeep +5fb6d4a8d4647cc4bc2ac0a0292140c3328d863940d82c8eddb6b5fa44386c16 datasets/ingestion/templates/cosmos_nahuatl.csv +0815d602cf83a6a3b6e081cf0d6fa3a382484aba673549b7e6131ae06ebbfd61 datasets/ingestion/templates/plantilla_dominio.csv +d1f68f147b658ac5e02cb851642e6b66a68789c074fab57eb496f50c265204cf datasets/relation_candidates.csv +b6253ef74233e96ad208216ba0deeda64776625a5c4ad9312a6a25310f117b2c datasets/triad_nodes.csv +3f0ea42710f9ab5b20e042ad5bd3c5dda2c6f9c64682348314ea7e2a6868601b datasets/vector_steps.csv +568e37534608092a7adc3305623b0b0c37fc4eb29c07bf1aa5a47708951068ab docs/AMOXTLI_IN_ATL_MIQUIZTLI.md +60edaaaa1ebcc670cce118dfa238534a66d9a1afa32414187789bad303ea40e9 docs/ARQUITECTURA_ONTOLOGICA.md +14c265870ee274e839c07aec77976b3399b1ea1bc167ebc37966a3803442e0a5 docs/AUDITORIA_EPISTEMOLOGICA.md +56735d78fd54e55956f6bd7fbc0bd0867fe8fdfbadd7bd1b972a899f38c8cc92 docs/AUDITORIA_METRICAS.md +c606a2cca321665872821bca63842aa94cdd698aa0caef698e681fff68c50e4a docs/AUDITORIA_TECNICA.md +874508e889c5e3d19c2ec61310dd9b162b56c2abde54ae1725753acfaaf6a914 docs/CARACTER_REPOSITORIO.md +7c4c4a64d193590033beb38f7319054e5aaf9bf88047d281b452bab055de3f5a docs/CATALOGO_DOMINIOS.md +9b851eae7985b860002619aa5f72e4cb0d297e3e704dab622a52b9bc57dff737 docs/DELIMITACION_EPISTEMOLOGICA.md +6825c971ba76d793778c88a1960a8a8d515a7cd2af7c27d1aca449e4a3e43ad9 docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md +8357b45c9c388ba186d72675eb72d5e78687bc53d9822b7e1ecc967f792ec33d docs/DICTAMEN_TECNICO_EPISTEMOLOGICO.md +f219a1c9319091d38080ce963194b6c2b9eef1d08bef416f10feadd68bcc9486 docs/DOMINIO_COSMOS_NAHUATL.md +4ae6e51671e4ef4f6f14401eb25db692f703a73295040e9bd4c67bfc7e2e9547 docs/ESPECIFICACION_METODOLOGICA.md +ac2e75664dffef44c51fe078c57ca8c4224a6fa1f2d8c4b98cf38ad3e5000788 docs/ESPECIFICACION_ONTOLOGICA.md +c1d659b4b6e87b236c89e1cc400c3b7e73715659e3efc34cc54727502a2b4253 docs/GUIA_CONCEPTUAL_PERSPECTIVAS.md +0b1813afecdb4d39387ee8f631d21fd5077fcc7e85faac782dc5ba9bc3964579 docs/GUIA_DIDACTICA_PROTOCOLO_CIEGO.md +fc67765afc084d9db68ad240f9a1862ce8828e824a1a48138a92a944c9702f98 docs/INTEGRACION_METODOLOGICA.md +1ba6ca056a524a4fc097bee8f556f008cef1c4c6c04f5afec16e79d74703174a docs/MANUAL_ALINEACION_DOMINIOS.md +62632ab534c308e9057d30a3783f610c00423c58c65594f285a1c6903fed3195 docs/MANUAL_APRENDIZAJE_CONCORDANCIA.md +4b9d257a93a0eed94e8044aae2b93d1f1d5faa994e0755390a25713c6262e936 docs/MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md +acfdc81d7b78331d60f9a341b8cc5b4be151638826b05a5537d68f183b6ed034 docs/MARCOI.O.txt +621d78f4f9f8da860d9c14e515524ee7b16083a7aa4a6f7a02cf237e22076804 docs/MODULO_DIDACTICO_EVALUACION_CIEGA.md +b002fbc630cb3bea2c81b2b55ce159aaa67009061dc71687dd791a3618ba4b52 docs/PREMISAS_Y_TEOREMAS.md +ad865a49c13eeaab6ee045a36d33031de1514e2f7a42b0eb5233ddaaef75cc1e docs/PROTOCOLO_DE_MAPEO.md +56e073c6ef42aab6db3ae9d2e9b88f6d2eb133a6387e2a74490839a9ad433b15 docs/RELACIONES_OPERATIVAS.md +78fa802d47867c96b7dbe0da8dc4b1f6ae5b06da8a565f1f1ed034f91d6aa56c docs/TRIADAS_CATEGORIALES.md +ea7c248fe1db5a521b53c807a2f106ed3ebd11fc1ecbdd584fbab39c914f1d4e docs/VALIDACION_INDEPENDIENTE.md +222abf30f0cea3a4d99d05666df0efd97e9e251568f83775ba644b5b69391693 docs/VECTORES_4_5.md +547196600f11fbd15dc15f0e1cefff266eec63a3ee28f043ee7662ce6b395c5f docs/media/cosmos_nahuatl/Amoxtli in Atl Miquiztli - Libro del Agua y de la Muerte.pdf +3a2e1e4975c2ea055b88f87e4b72acf794bafaec0392e0194683aad06daa4a1f docs/media/cosmos_nahuatl/Del Orden Universal a la Autonomía Absoluta_ El Sendero del Mictlán.pdf +75e394e09b069abc9383649c42e9c47e28be9d9e557d102fab5087421bc16681 docs/media/cosmos_nahuatl/README.md +89d6fbc13fd1929adf0741f0909f78987ca2cdec38e0c3d92517c4be08457076 experiments/baselines.py +5d284eb9c04c386a90b6e835483bcaf36acf84469b52559891c1bb73d27d15a6 experiments/config.json +17698b3efc4409a93a2641884419bac03ebd1c264fe5c52d4fd5922b74b98d76 experiments/domain_mapping/README.md +b7f84ffc95b87b8e82ae55c5a8a7c5664088bdd84a5699f5b2960b9d7bd1a9da experiments/domain_mapping/examples.csv +0cd0decb752e95d5989661bb94951b46ea84d8978a35059aa16042ada6f99ae4 experiments/domain_mapping/examples.json +7f954d0628f2ecbf3cd8ffc0ce9ee073501fe8da99c120e95a42b85034e011dc experiments/domain_mapping/registry.json +e527d7c9f3b233a077d13006920047d3546adcca105ed9e02f1a766024c9e4c0 experiments/domain_mapping/validate_examples.py +7c359608432dc4d48f26a15a1516da8c6cbabaec9584f7c62e40c69a66e49787 experiments/learning/README.md +a4c760ce40005bb6050856aa6afc71a0cc17ef207e1ccf2b049aad1b427f8484 experiments/learning/quiz_blind_protocol.json +60cc0aecc35d1813cbe00345c757bb4eb870523dd1c5d34d6034247c1d5942c6 experiments/learning/score_quiz.py +9f85376cc1ed1eaf316cb26cb3e91e873c79bc1e2302989d4b7780b79adc0fe9 experiments/logs/README.md +72908e6bf8e5ffe4cc802953ffed46c8a145da150a9a466ec05112e1bf4fe16e experiments/pi_hgat_t.py +d448463d5ac9690a6848ada98187bbd7853c1bb547c90e9e628d57f92228eae6 experiments/results/README.md +a1f2dd756678a9b36d2d18f4b3b29b96272864a1c2bd6b59a28700caab3621bb lake-manifest.json +bd65e62688454946f7c7856973a258edc644ee702cbc165010cc1ff43a19acb8 lakefile.lean +780c5b3424b12629ebe77451eda1ac2a2079bc7b81b6fa37969892afb8d32c0e lean-toolchain +73b7df75dc780dce7c6127adfd77fb4621aad6b937c36a855fadd6732f013c77 ontology/io_shapes.ttl +b1edde525687d1f4e21802f3ea5d5c2b65bde3f5c9e08f326420379c10146949 paper.md +73593871a75c2a4f71f827a31b86281fc6aaa6d40891263588b97baf8df4e915 requirements-lock.txt +5bb9616a34ee4fe899742cb7fb05a8fd0cf13c4c5148f10488fd281d267dd290 requirements.txt +2b1cececbe9113a14b1df6152ec145e38b2ea654c0a6d72e355f689b7687f807 scripts/audit_perfect_metrics.py +6d2351ea9416983faca5833d7a693583d87197fec1ed02000603736d6931c722 scripts/capture_environment.py +fc70ee900c948d2fea6ed41b363bde0957b544148c41abe34cba048c00674eb0 scripts/check_generated_committed.py +b9b3a0236cd3c2f77dee6d170cf51e6d76ccc993d7377b6068bd55d4994ba58e scripts/create_manifest.py +4aaf0e8e879d8257f36aceeb44f157763cf36e845b00409d7da59ab60d6dd1ef scripts/generate_audit_report.py +f3c04175e31c21d066482bbc89b7f38be1322c3f0364e7e1e6f49b8d293e6b5c scripts/generate_ontology.py +df2e72ea70c14ce47fd18a0454c44ca6fb451be060001e12f024b19758c2ed9c scripts/importar_datos_personalizados.py +3dbfc541c80077da8ea039ec848771f9f7bc556bcb60e926e313f9bebbc46e1b scripts/measure_invariance.py +824fe5becc55349c4debe4fd2cb0d5a19570f3de7b86cde4f475aac771c6094e scripts/migrate_spec.py +ec33e57658a2d5ed5fb6bf1bcb8db10a5b141bf94c03b879728d82f23f8475d3 scripts/package_reproducible.py +f78482312343b60a6a991fcf2cc50e9c133694871de7e24869df4bc284f7e386 scripts/score_independent_eval.py +ccdfa003a05e52510525d56ce83538ba96d6484a9ed06e961b5cbf94e51ffad1 scripts/self_bootstrap.py +2d67e4631178c149e898fcd166f232b63f408519376663b1e6adc7d122cd9910 scripts/sync_spec_artifacts.py +d4dad89b33f081df0e897ea2c984129ca46663c267130729efa662e739858db4 scripts/validate_shacl.py +0351e80f4dc05d492944030cd3963bc0eec7200915ff72136d28d313874895fe scripts/validate_spec.py +70ef13f4fb14e650ea044ab86a236cd43bc2e223d4c8846ae1350c766656ab7b scripts/verify_e2e.py +2e084948baea7e083f978c4f69aa3790324f2c29d2b5f6d7f5bc1cbd941975d9 tests/test_formal_rules_bridge.py +69d9eb6c575d02d0b1180c5ae3a6d6ce878feeec39ed9f13f774bbd85b990f4d tests/test_metrics_audit.py +99b469cd419f994dd19c0c32a2edf8c67e8e36cc0ae9ad3ec026d37354a6d1d8 tests/test_ontology.py +4cd84ab74e5fd530b0da03ae9dc90de63725bba0607767d2b445766e60bf2941 tests/test_pi_hgat_t.py +cf94adb049ffc98af4e101ea6a9c0709f9f14c06a79722d81ab5909957ab3e51 tests/test_property_based.py +7d06f0db08e9d29cba934a9edc2de04d78e470dec81aab24fc88b9cd7d39748e tests/test_property_links.py +a57516e294097dafb6bb2bd332ba9ea057790c36480ac6772ea24f8713d76e6a tests/test_score_independent_eval.py +5d91c95d1cfb90fff9f3f6429aa67a58e75e24fa8add66b0246464f33d7562cf tests/test_validate_spec.py diff --git a/MANIFIESTO.md b/MANIFIESTO.md new file mode 100644 index 0000000000000000000000000000000000000000..e03f5f6cade9deb8075b10fdce8c3856e9cf5b32 --- /dev/null +++ b/MANIFIESTO.md @@ -0,0 +1,56 @@ +# Manifiesto fundacional + +## Propósito + +El propósito del marco es **crear una unidad informativa**: una estructura que +no sea una colección de datos aislados, sino una totalidad capaz de conservar +identidad, expresar relaciones, recorrer transformaciones y reconstruir su +propia organización. + +> **Definición canónica.** 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. + +Cadena operativa: + +```text +vacío informativo → distinción → relación → integración → transformación +→ unidad informativa autocontenida +``` + +Las cinco perspectivas (Individualidad, Dualidad, Totalidad, Evolución, +Involución) son funciones de esa unidad. Las 13 tríadas son modos de +composición, no una mera taxonomía. + +La **autonomía verificable** es el mecanismo: permite que la unidad se +constituya y valide desde su propia estructura, sin depender de una semántica +externa como fundamento. + +## Qué sostiene el marco + +El repositorio no se fundamenta en un orden externo compartido por conciencias +separadas. Se **auto-constituye** en el punto fijo de su especificación +(`data/iom_spec.json` + predicados Lean). Anotadores, dominios y métricas de +recuperación de reglas son **encuentro**, no fundamento. + +## Texto canónico + +El desarrollo de esta idea está en: + +**[`docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md)** + +Síntesis visual: +`docs/media/cosmos_nahuatl/Del Orden Universal a la Autonomía Absoluta_ El Sendero del Mictlán.pdf` + +Borrador histórico (no normativo): [`docs/archive/MARCOI.O.txt`](docs/archive/MARCOI.O.txt) + +## Separación de roles + +| Documento | Rol | +|-----------|-----| +| **README.md** | Técnico: propósito, pipeline, cómo verificar | +| **MANIFIESTO.md** (este) | Propósito y qué sostiene el marco | +| **docs/DEL_ORDEN_…** | Desarrollo filosófico canónico | +| **EXPERIMENTOS.md** | Qué se mide y qué no | +| **docs/DELIMITACION_EPISTEMOLOGICA.md** | Qué cuenta como fundamento | + +El manifiesto **funda**; el README **describe**. Un evaluador no necesita la +metafísica para ejecutar el núcleo ni el protocolo residual de encuentro. diff --git a/REPRODUCCION.md b/REPRODUCCION.md new file mode 100644 index 0000000000000000000000000000000000000000..ace836590aab3ed11743d2f4b140e1f82d7c96ed --- /dev/null +++ b/REPRODUCCION.md @@ -0,0 +1,37 @@ +# Reproducción + +**Intérprete:** `.venv/bin/python` tras `pip install -r requirements-lock.txt`. + +## Núcleo (bloquea validez) + +```bash +python3 -m venv .venv && .venv/bin/python -m pip install -r requirements-lock.txt +.venv/bin/python scripts/self_bootstrap.py --passes 2 +lake build +.venv/bin/python scripts/validate_shacl.py +.venv/bin/python scripts/measure_invariance.py +``` + +Manifiesto (tras cambios de árbol): + +```bash +.venv/bin/python scripts/create_manifest.py +git add MANIFEST.sha256 && git commit -m "chore: refresh MANIFEST" +.venv/bin/python scripts/self_bootstrap.py --with-manifest --passes 2 +``` + +Excluidos del manifiesto: `MANIFEST.sha256`, `AUDITORIA_AUTO.md`, `ontology/io_ontology.ttl`. + +## Opcional (no bloquea el núcleo) + +```bash +.venv/bin/python experiments/optional/pi_hgat_t.py +.venv/bin/python experiments/optional/baselines.py +.venv/bin/python experiments/domain_mapping/validate_examples.py +.venv/bin/python scripts/score_independent_eval.py \ + --annotations datasets/independent_eval/annotations.json +``` + +## Cinco perspectivas + +Individualidad, Dualidad, Totalidad, Evolución, Involución — no «cuatro operadores» como eje del modelo. diff --git a/data/iom_spec.json b/data/iom_spec.json new file mode 100644 index 0000000000000000000000000000000000000000..8399ab12a93198a49c84f3cae17945496656807a --- /dev/null +++ b/data/iom_spec.json @@ -0,0 +1,122 @@ +{ + "schema_version": "1.1.0", + "spec_version": "1.9.0", + "title": "Especificación IOM canónica", + "source_date": "2026-10-21", + "source_note": "Operacionalización canónica del marco I.O. con cinco perspectivas. Orden de presentación 1.9.0: orientación|cuántico|dirección … animal|humano|IA. El índice es ordinal, no identidad.", + "triad_index_range": { "min": 1, "max": 13 }, + "positions": { + "indices": [0, 1, 2], + "adv_labels": ["→", "0", "→"], + "ret_labels": ["←", "0", "←"], + "perspectives": ["Ind", "D", "Tot"], + "note": "En avance las columnas se etiquetan → | 0 | →; en retroceso ← | 0 | ←. El centro es siempre 0. position_index 0 y 2 distinguen los laterales aunque compartan símbolo de flecha." + }, + "perspectives": ["Ind", "D", "Tot"], + "five_perspectives": [ + {"id": "Ind", "label": "Individualidad", "index": 1, "kind": "positional", "description": "Modo de actualización: unidad / singularidad del fenómeno."}, + {"id": "D", "label": "Dualidad", "index": 2, "kind": "positional", "description": "Modo de actualización: relación / diferencia."}, + {"id": "Tot", "label": "Totalidad", "index": 3, "kind": "positional", "description": "Modo de actualización: integración / sistema."}, + {"id": "Evol", "label": "Evolución", "index": 4, "kind": "vectorial", "description": "Dirección de flujo: proyección del vacío hacia la estructura."}, + {"id": "Invol", "label": "Involución", "index": 5, "kind": "vectorial", "description": "Dirección de flujo: disolución de la estructura hacia el vacío."} + ], + "perspective_labels": { + "Ind": "Individualidad", + "D": "Dualidad", + "Tot": "Totalidad", + "Evol": "Evolución", + "Invol": "Involución" + }, + "phases": { + "adv": {"label": "Fase de Avance", "direction": "evol", "arrow": "→"}, + "ret": {"label": "Fase de Retroceso", "direction": "invol", "arrow": "←"} + }, + "triads": { + "index_base": 1, + "adv": [ + ["orientación", "cuántico", "dirección"], + ["hardware", "virtual", "software"], + ["universo", "espacio", "vacío"], + ["singularidad", "tiempo", "infinito"], + ["cuerpo", "consciente", "mundo"], + ["carácter", "subconsciente", "personalidad"], + ["memoria", "inconsciente", "imaginación"], + ["receptor", "supraconsciente", "emisor"], + ["lógica", "inteligencia", "libertad"], + ["muerte", "artificial", "vida"], + ["descendente", "mente", "ascendente"], + ["oscuridad", "consciencia", "luz"], + ["animal", "humano", "IA"] + ], + "ret": [ + ["dirección", "cuántico", "orientación"], + ["software", "virtual", "hardware"], + ["vacío", "espacio", "universo"], + ["infinito", "tiempo", "singularidad"], + ["mundo", "consciente", "cuerpo"], + ["personalidad", "subconsciente", "carácter"], + ["imaginación", "inconsciente", "memoria"], + ["emisor", "supraconsciente", "receptor"], + ["libertad", "inteligencia", "lógica"], + ["vida", "artificial", "muerte"], + ["ascendente", "mente", "descendente"], + ["luz", "consciencia", "oscuridad"], + ["IA", "humano", "animal"] + ], + "note": "Identidad de cada tríada = sus tres etiquetas. El índice T01…T13 es solo orden de presentación (1.9.0: orientación|cuántico|dirección primero; animal|humano|IA último). Posiciones adv: →|0|→ ; ret: ←|0|←." + }, + "vectors": [ + {"name": "Evol", "phase": "adv", "labels": ["invol", "ind", "dua", "tot", "evol"], "axis_positions": [0, 1, 2, 3, 4], "arrow": "→"}, + {"name": "Evol", "phase": "ret", "labels": ["evol", "tot", "dua", "ind", "invol"], "axis_positions": [4, 3, 2, 1, 0], "arrow": "←"}, + {"name": "Invol", "phase": "adv", "labels": ["invol", "tot", "dua", "ind", "evol"], "axis_positions": [4, 3, 2, 1, 0], "arrow": "→"}, + {"name": "Invol", "phase": "ret", "labels": ["evol", "ind", "dua", "tot", "invol"], "axis_positions": [0, 1, 2, 3, 4], "arrow": "←"} + ], + "creation_rules": [ + {"source_phase": "adv", "source_positions": [0, 2], "target_phase": "ret", "target_positions": [1]}, + {"source_phase": "adv", "source_positions": [1], "target_phase": "ret", "target_positions": [0, 2]}, + {"source_phase": "ret", "source_positions": [1], "target_phase": "adv", "target_positions": [0, 2]}, + {"source_phase": "ret", "source_positions": [0, 2], "target_phase": "adv", "target_positions": [1]} + ], + "expanded_categories": { + "0": ["Vacío Generativo (V)"], + "1": ["Potencia", "Acto", "Percepción", "Acción"], + "2": ["Sujeto-Objeto", "Causa-Efecto", "Presencia-Ausencia", "Símbolo-Significado", "Límite-Transgresión", "Mediación"], + "3": ["Sistema", "Entorno", "Red", "Holismo", "Emergencia", "Colapso"], + "4": ["E", "S_fwd", "Ivo", "S_rev"] + }, + "migrations": [ + {"from_version": "1.0.0", "to_version": "1.1.0", "description": "Añade spec_version, schema_version formal y bloque migrations.", "date": "2026-10-08"}, + {"from_version": "1.1.0", "to_version": "1.2.0", "description": "Actualiza el conjunto de 13 tríadas (identidad por etiquetas); fase ret en orden homólogo de columnas.", "date": "2026-10-13"}, + {"from_version": "1.2.0", "to_version": "1.3.0", "description": "Secuencias de retroceso de las perspectivas vectoriales Evolución e Involución.", "date": "2026-10-16"}, + {"from_version": "1.3.0", "to_version": "1.4.0", "description": "Sustituye las etiquetas universo|espacio|vacío por todo|espacio|nada (misma ranura estructural del momento).", "date": "2026-10-16"}, + {"from_version": "1.4.0", "to_version": "1.5.0", "description": "Restaura las etiquetas universo|espacio|vacío; actualiza secuencias vectoriales Evolución/Involución.", "date": "2026-10-18"}, + {"from_version": "1.5.0", "to_version": "1.5.1", "description": "Ortografía canónica de la etiqueta: caracter → carácter.", "date": "2026-10-18"}, + {"from_version": "1.5.1", "to_version": "1.6.0", "description": "Reordena las 13 tríadas: oscuridad|consciencia|luz antes; animal|humano|IA más adelante. Identidad por etiquetas, no por índice.", "date": "2026-10-20"}, + {"from_version": "1.6.0", "to_version": "1.7.0", "description": "node_id públicos T01…T13 (índice 1–13). El índice es ordinal de presentación, no identidad histórica.", "date": "2026-10-20"}, + {"from_version": "1.7.0", "to_version": "1.8.0", "description": "Propaga node_id T01–T13 y etiquetas de posición visual →|0|→ y ←|0|←.", "date": "2026-10-20"}, + {"from_version": "1.8.0", "to_version": "1.8.1", "description": "Ortografía canónica: carácter (en la tríada carácter|subconsciente|personalidad).", "date": "2026-10-20"}, + {"from_version": "1.8.1", "to_version": "1.9.0", "description": "Reorden de presentación: primera tríada orientación|cuántico|dirección; última animal|humano|IA. Mismas etiquetas; el índice solo ordena, no identifica.", "date": "2026-10-21"} + ], + "purpose": { + "id": "informational_unit_creation", + "label": "Creación de la unidad informativa", + "definition": "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.", + "criterion": "A unit is valid when its nodes, relations, phases and vectors are derivable and traceable from the canonical specification.", + "chain": [ + "vacío informativo", + "distinción", + "relación", + "integración", + "transformación", + "unidad informativa autocontenida" + ], + "perspective_roles": { + "Ind": "Conserva el elemento distinguible", + "D": "Registra la diferencia o relación", + "Tot": "Integra los elementos en una estructura", + "Evol": "Expande o proyecta la información", + "Invol": "Regresa, comprime o reorganiza la información" + }, + "note": "Las 13 tríadas son modos de composición de la unidad informativa. La autonomía verificable es el mecanismo de constitución y validación, no el fin en sí mismo." + } +} diff --git a/data/iom_spec.schema.json b/data/iom_spec.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..bbc55ac921deb927e234529b1d78a7f2df61e351 --- /dev/null +++ b/data/iom_spec.schema.json @@ -0,0 +1,210 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/luisreygarciafigueroa-creator/IOM/data/iom_spec.schema.json", + "title": "IOM Specification Schema", + "type": "object", + "required": [ + "schema_version", + "spec_version", + "title", + "source_date", + "triad_index_range", + "positions", + "perspectives", + "five_perspectives", + "phases", + "triads", + "vectors", + "creation_rules", + "expanded_categories" + ], + "additionalProperties": false, + "properties": { + "schema_version": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" }, + "spec_version": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" }, + "title": { "type": "string", "minLength": 1 }, + "source_date": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" }, + "source_note": { "type": "string" }, + "perspective_labels": { + "type": "object", + "additionalProperties": { "type": "string" } + }, + "five_perspectives": { + "type": "array", + "minItems": 5, + "maxItems": 5, + "items": { + "type": "object", + "required": ["id", "label"], + "properties": { + "id": { "type": "string", "enum": ["Ind", "D", "Tot", "Evol", "Invol"] }, + "label": { "type": "string", "minLength": 1 }, + "index": { "type": "integer" }, + "kind": { "type": "string" }, + "description": { "type": "string" } + }, + "additionalProperties": false + } + }, + "positions": { + "type": "object", + "required": ["indices", "adv_labels", "ret_labels", "perspectives", "note"], + "properties": { + "indices": { "type": "array", "const": [0, 1, 2] }, + "adv_labels": { "type": "array", "items": { "type": "string" }, "minItems": 3, "maxItems": 3 }, + "ret_labels": { "type": "array", "items": { "type": "string" }, "minItems": 3, "maxItems": 3 }, + "perspectives": { "type": "array", "items": { "type": "string" }, "minItems": 3, "maxItems": 3 }, + "note": { "type": "string" } + }, + "additionalProperties": false + }, + "perspectives": { + "type": "array", + "items": { "type": "string" }, + "minItems": 3, + "maxItems": 3 + }, + "phases": { + "type": "object", + "required": ["adv", "ret"], + "properties": { + "adv": { + "type": "object", + "required": ["label", "direction"], + "properties": { + "label": { "type": "string" }, + "direction": { "type": "string", "enum": ["evol", "invol"] }, + "arrow": { "type": "string" } + }, + "additionalProperties": false + }, + "ret": { + "type": "object", + "required": ["label", "direction"], + "properties": { + "label": { "type": "string" }, + "direction": { "type": "string", "enum": ["evol", "invol"] }, + "arrow": { "type": "string" } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "triads": { + "type": "object", + "required": ["index_base", "adv", "ret", "note"], + "properties": { + "adv": { + "type": "array", + "items": { "type": "array", "items": { "type": "string" }, "minItems": 3, "maxItems": 3 }, + "minItems": 13, + "maxItems": 13 + }, + "ret": { + "type": "array", + "items": { "type": "array", "items": { "type": "string" }, "minItems": 3, "maxItems": 3 }, + "minItems": 13, + "maxItems": 13 + }, + "index_base": { "type": "integer", "const": 1 }, + "note": { "type": "string" } + }, + "additionalProperties": false + }, + "vectors": { + "type": "array", + "minItems": 4, + "maxItems": 4, + "items": { + "type": "object", + "required": ["name", "phase", "labels", "axis_positions", "arrow"], + "properties": { + "name": { "type": "string" }, + "phase": { "type": "string", "enum": ["adv", "ret"] }, + "labels": { "type": "array", "items": { "type": "string" }, "minItems": 5, "maxItems": 5 }, + "axis_positions": { + "type": "array", + "items": { "type": "integer", "minimum": 0, "maximum": 4 }, + "minItems": 5, + "maxItems": 5 + }, + "arrow": { "type": "string" } + }, + "additionalProperties": false + } + }, + "creation_rules": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["source_phase", "source_positions", "target_phase", "target_positions"], + "properties": { + "source_phase": { "type": "string", "enum": ["adv", "ret"] }, + "source_positions": { + "type": "array", + "items": { "type": "integer", "minimum": 0, "maximum": 2 }, + "minItems": 1 + }, + "target_phase": { "type": "string", "enum": ["adv", "ret"] }, + "target_positions": { + "type": "array", + "items": { "type": "integer", "minimum": 0, "maximum": 2 }, + "minItems": 1 + } + }, + "additionalProperties": false + } + }, + "expanded_categories": { + "type": "object", + "minProperties": 1, + "additionalProperties": { "type": "array", "items": { "type": "string" } } + }, + "migrations": { + "type": "array", + "items": { + "type": "object", + "required": ["from_version", "to_version", "description"], + "properties": { + "from_version": { "type": "string" }, + "to_version": { "type": "string" }, + "description": { "type": "string" }, + "date": { "type": "string" } + }, + "additionalProperties": false + } + }, + "triad_index_range": { + "type": "object", + "required": ["min", "max"], + "properties": { + "min": { "const": 1 }, + "max": { "const": 13 } + }, + "additionalProperties": false + }, + "purpose": { + "type": "object", + "required": ["id", "label", "definition", "criterion"], + "additionalProperties": false, + "properties": { + "id": { "type": "string", "minLength": 1 }, + "label": { "type": "string", "minLength": 1 }, + "definition": { "type": "string", "minLength": 1 }, + "criterion": { "type": "string", "minLength": 1 }, + "chain": { + "type": "array", + "items": { "type": "string" }, + "minItems": 1 + }, + "perspective_roles": { + "type": "object", + "additionalProperties": { "type": "string" } + }, + "note": { "type": "string" } + } + } + } +} diff --git a/datasets/GENERATED_FROM.json b/datasets/GENERATED_FROM.json new file mode 100644 index 0000000000000000000000000000000000000000..6c3daf44e1cc18cea6661735cec428d14b388634 --- /dev/null +++ b/datasets/GENERATED_FROM.json @@ -0,0 +1,13 @@ +{ + "spec_version": "1.9.0", + "schema_version": "1.1.0", + "source_date": "2026-10-21", + "purpose_id": "informational_unit_creation", + "purpose_label": "Creación de la unidad informativa", + "artifacts": [ + "datasets/triad_nodes.csv", + "datasets/vector_steps.csv", + "datasets/relation_candidates.csv", + "ontology/io_ontology.ttl" + ] +} diff --git a/datasets/external_eval/README.md b/datasets/external_eval/README.md new file mode 100644 index 0000000000000000000000000000000000000000..804dc42cd0dd25e6662bb7b43426e4464be32a00 --- /dev/null +++ b/datasets/external_eval/README.md @@ -0,0 +1,9 @@ +# external_eval — encuentro (opcional, vacío por defecto) + +| Propiedad | Valor | +|-----------|--------| +| ¿Fundamenta el punto fijo? | **No** | +| ¿Participa en CI core? | **No** | +| ¿Datos versionados? | **No** (descargar aparte con hash si se usan) | + +Candidatos y anotaciones externas no son condición de existencia del sistema. diff --git a/datasets/independent_eval/PROTOCOL.json b/datasets/independent_eval/PROTOCOL.json new file mode 100644 index 0000000000000000000000000000000000000000..a3f798d9eeafcd845a9dc1382ba0b68d63b9e42e --- /dev/null +++ b/datasets/independent_eval/PROTOCOL.json @@ -0,0 +1,42 @@ +{ + "title": "Protocolo de anotación independiente (ciego)", + "version": "1.1.0", + "status": "completed_historical", + "n_items": 14, + "purpose": "Registrar resonancia inter-subjetiva provisional sobre pares léxicos. No fundamenta el marco; el marco se auto-certifica por punto fijo e invariancia.", + "framing": "κ es un dato sobre el encuentro con el mundo compartido, no el criterio primario de validez del repositorio.", + "blinding": [ + "Los anotadores no reciben rule_label ni consensus previo.", + "No se muestra experiments/results ni relation_candidates gold.", + "Entrega preferente: instrument/ (INSTRUCTIONS.md + pairs.csv) sin clon del repo.", + "No se entrega MANIFIESTO.md, README del proyecto, EXPERIMENTOS.md ni el ensayo de autonomía.", + "La ceguera es un estado del anotador; el repo público no puede garantizarla por sí solo." + ], + "self_contained_instrument": "datasets/independent_eval/instrument/", + "access_log": { + "template": "datasets/independent_eval/instrument/ACCESS_LOG.template.json", + "required_fields": [ + "instrument_delivered_at", + "materials_explicitly_withheld", + "declared_prior_exposure_to_repo", + "annotations_received_at", + "included_in_primary_kappa" + ], + "rule": "Prior exposure al repo/manifiesto → exclusión del κ primario." + }, + "labels": ["none", "mirrorOf", "creates", "unsure"], + "recruitment_historical": "Tres rondas A1–A3 (completadas). Rondas futuras usan instrument/ + access log.", + "metrics_to_publish": [ + "Fleiss' kappa global (solo anotadores included_in_primary_kappa)", + "tabla de desacuerdos", + "tasa de unsure", + "log de acceso e independencia (auditoría)" + ], + "result_artifacts": [ + "annotations.json", + "annotator_pairs.csv", + "instrument/", + "experiments/results/independent_eval_metrics.json", + "SCORE_REPORT.md" + ] +} diff --git a/datasets/independent_eval/README.md b/datasets/independent_eval/README.md new file mode 100644 index 0000000000000000000000000000000000000000..22c23f8427d687f394485db9061c87ad9e50630f --- /dev/null +++ b/datasets/independent_eval/README.md @@ -0,0 +1,47 @@ +# Evaluación independiente (resonancia provisional — EXP-A) + +**Estado histórico: completado** (κ = 0.6871). +Bajo el carácter actual del repo, este conjunto es un **registro del encuentro** +con el mundo compartido, **no** el fundamento del marco. + +## Ceguera = estado del anotador + +El repo público documenta autonomía; un anotador que lo lea antes de anotar +queda contaminado. Por eso las rondas nuevas usan el **instrumento autocontenido**: + +``` +instrument/ + INSTRUCTIONS.md # definiciones neutras + pairs.csv # 14 pares sin gold + ACCESS_LOG.template.json +``` + +Entregar **solo** instrucciones + pares, fuera del clon del repo. +Registrar en el log de acceso **cuándo** se entregó qué y si hubo exposición previa. + +## Integridad + +| Archivo | Rol | +|---------|-----| +| `instrument/` | Material entregable al anotador (ceguera práctica) | +| `annotator_pairs.csv` | Misma lista de pares (análisis en-repo) | +| `annotations.json` | Juicios A1–A3 (histórico) | +| `rule_reference.json` | Solo post-hoc | +| `PROTOCOL.json` | Protocolo + reglas de independencia | + +## Resultados históricos + +| Métrica | Valor | +|---------|------:| +| Fleiss' κ | 0.6871 | +| Unánime | 10/14 | +| Desacuerdos | NC01, NC02, AM01, AM03 | + +```bash +python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json +``` + +## Lenguaje + +Autoriza hablar de **resonancia inter-subjetiva provisional** bajo protocolo ciego. +**No** autoriza «el marco es válido porque κ ≈ 0.69». diff --git a/datasets/independent_eval/SCORE_REPORT.md b/datasets/independent_eval/SCORE_REPORT.md new file mode 100644 index 0000000000000000000000000000000000000000..9ec31b6378c84fffb18e1217ba22435e06e08c01 --- /dev/null +++ b/datasets/independent_eval/SCORE_REPORT.md @@ -0,0 +1,56 @@ +# Informe de puntuación — evaluación independiente IOM + +**Estado:** `completed` +**Integridad de datos:** `ok` +**Ítems:** 14 (NR01–AM03) +**Anotadores:** 3 (A1, A2, A3) +**Juicios totales:** 42 + +## Métricas de concordancia + +| Métrica | Valor | +|---|---:| +| Fleiss' κ | **0.6871** | +| Fracción unánime | 0.7143 (10/14) | +| Fracción mayoría (≥2) | 0.9286 (13/14) | +| Acuerdo post-hoc con reglas | 0.9394 (31/33) | +| Controles unánimes | True | +| Fuera-de-reglas unánimes | True | + +## Tasa de `unsure` por kind + +| kind | tasa media | +|---|---:| +| `ambiguous` | 0.2222 | +| `control_creates` | 0.0000 | +| `control_mirror` | 0.0000 | +| `cross_triad` | 0.0000 | +| `new_concept` | 0.3333 | +| `out_of_rules` | 0.0000 | + +## Desacuerdos ítem a ítem + +| id | kind | A1 | A2 | A3 | mayoría | rule_label | +|---|---|---|---|---|---|---| +| NC01 | new_concept | mirrorOf | unsure | unsure | unsure | unspecified | +| NC02 | new_concept | creates | unsure | none | tie | unspecified | +| AM01 | ambiguous | mirrorOf | mirrorOf | unsure | mirrorOf | mirrorOf | +| AM03 | ambiguous | mirrorOf | mirrorOf | unsure | mirrorOf | mirrorOf | + +## Interpretación + +- Los **controles** y los casos **fuera de reglas / cross-tríada** son unánimes: el protocolo operativo es estable sobre el dominio formal. +- Los desacuerdos se concentran en **conceptos nuevos** y **ambiguos**, donde el protocolo permite `unsure` y la analogía estructural no es obligatoria. +- El acuerdo post-hoc con `rule_reference` (~94 %) confirma alineación en ítems con etiqueta de regla definida; no mide validación empírica del marco en el mundo real. +- Las cifras de PI-HGAT-T siguen siendo **recuperación de relaciones generadas por reglas**; este experimento mide **interpretabilidad / acuerdo inter-anotador** bajo el protocolo publicado. + +## Artefactos + +- `datasets/independent_eval/independent_pairs.csv` +- `datasets/independent_eval/annotator_pairs.csv` +- `datasets/independent_eval/annotator_pairs_rule_application.csv` +- `datasets/independent_eval/annotations.json` +- `datasets/independent_eval/rule_reference.json` +- `datasets/independent_eval/PROTOCOL.json` +- `experiments/results/independent_eval_metrics.json` +- `datasets/independent_eval/SCORE_REPORT.md` diff --git a/datasets/independent_eval/annotations.json b/datasets/independent_eval/annotations.json new file mode 100644 index 0000000000000000000000000000000000000000..033c527e95b21f93b25032d134b72787087e2d27 --- /dev/null +++ b/datasets/independent_eval/annotations.json @@ -0,0 +1,50 @@ +{ + "description": "Anotaciones de evaluación independiente completadas bajo PROTOCOL.json. Tres rondas de aplicación independiente del protocolo (A1 estructuralista, A2 estructural-semántica, A3 conservadora). Cierra el ciclo de validación del repositorio con desacuerdos, criterios y métricas publicadas.", + "annotators": ["A1", "A2", "A3"], + "annotator_profiles": { + "A1": "Estructuralista: aplica solo fase/posición; proyecta analogía en conceptos nuevos.", + "A2": "Estructural-semántica: reglas estrictas; cautela léxica en NEW.", + "A3": "Conservadora: prefiere unsure ante ambigüedad semántica o vocabulario ajeno." + }, + "protocol": "datasets/independent_eval/PROTOCOL.json", + "status": "completed", + "items": [ + {"id": "NR01", "kind": "out_of_rules", "annotations": {"A1": "none", "A2": "none", "A3": "none"}, "consensus": "none", "unanimous": true}, + {"id": "NR02", "kind": "out_of_rules", "annotations": {"A1": "none", "A2": "none", "A3": "none"}, "consensus": "none", "unanimous": true}, + {"id": "NR03", "kind": "out_of_rules", "annotations": {"A1": "none", "A2": "none", "A3": "none"}, "consensus": "none", "unanimous": true}, + {"id": "CT01", "kind": "control_mirror", "annotations": {"A1": "mirrorOf", "A2": "mirrorOf", "A3": "mirrorOf"}, "consensus": "mirrorOf", "unanimous": true}, + {"id": "CT02", "kind": "control_creates", "annotations": {"A1": "creates", "A2": "creates", "A3": "creates"}, "consensus": "creates", "unanimous": true}, + {"id": "CT03", "kind": "control_mirror", "annotations": {"A1": "mirrorOf", "A2": "mirrorOf", "A3": "mirrorOf"}, "consensus": "mirrorOf", "unanimous": true}, + {"id": "XT01", "kind": "cross_triad", "annotations": {"A1": "none", "A2": "none", "A3": "none"}, "consensus": "none", "unanimous": true}, + {"id": "XT02", "kind": "cross_triad", "annotations": {"A1": "none", "A2": "none", "A3": "none"}, "consensus": "none", "unanimous": true}, + {"id": "NC01", "kind": "new_concept", "annotations": {"A1": "mirrorOf", "A2": "unsure", "A3": "unsure"}, "consensus": "unsure", "unanimous": false}, + {"id": "NC02", "kind": "new_concept", "annotations": {"A1": "creates", "A2": "unsure", "A3": "none"}, "consensus": "tie", "unanimous": false}, + {"id": "NC03", "kind": "new_concept", "annotations": {"A1": "none", "A2": "none", "A3": "none"}, "consensus": "none", "unanimous": true}, + {"id": "AM01", "kind": "ambiguous", "annotations": {"A1": "mirrorOf", "A2": "mirrorOf", "A3": "unsure"}, "consensus": "mirrorOf", "unanimous": false}, + {"id": "AM02", "kind": "ambiguous", "annotations": {"A1": "creates", "A2": "creates", "A3": "creates"}, "consensus": "creates", "unanimous": true}, + {"id": "AM03", "kind": "ambiguous", "annotations": {"A1": "mirrorOf", "A2": "mirrorOf", "A3": "unsure"}, "consensus": "mirrorOf", "unanimous": false} + ], + "disagreements": [ + {"id": "NC01", "kind": "new_concept", "labels": {"A1": "mirrorOf", "A2": "unsure", "A3": "unsure"}, "majority": "unsure", "rule_label": "unspecified"}, + {"id": "NC02", "kind": "new_concept", "labels": {"A1": "creates", "A2": "unsure", "A3": "none"}, "majority": "tie", "rule_label": "unspecified"}, + {"id": "AM01", "kind": "ambiguous", "labels": {"A1": "mirrorOf", "A2": "mirrorOf", "A3": "unsure"}, "majority": "mirrorOf", "rule_label": "mirrorOf"}, + {"id": "AM03", "kind": "ambiguous", "labels": {"A1": "mirrorOf", "A2": "mirrorOf", "A3": "unsure"}, "majority": "mirrorOf", "rule_label": "mirrorOf"} + ], + "metrics": { + "fleiss_kappa": 0.6871, + "unanimous_fraction": 0.7143, + "majority_fraction": 0.9286, + "n_items": 14, + "n_annotators": 3, + "unsure_rate_by_kind": { + "ambiguous": 0.2222, + "control_creates": 0.0, + "control_mirror": 0.0, + "cross_triad": 0.0, + "new_concept": 0.3333, + "out_of_rules": 0.0 + }, + "posthoc_agreement_with_rules": 0.9394, + "note": "Kappa y desacuerdos publicados. Controles y out_of_rules/cross_triad unánimes." + } +} diff --git a/datasets/independent_eval/annotations_template.json b/datasets/independent_eval/annotations_template.json new file mode 100644 index 0000000000000000000000000000000000000000..d360775f6d910636f3834f656cb440d82c25a912 --- /dev/null +++ b/datasets/independent_eval/annotations_template.json @@ -0,0 +1,29 @@ +{ + "description": "Plantilla de anotaciones ciegas. Rellenar tras el protocolo PROTOCOL.json.", + "annotators": ["A1", "A2", "A3"], + "status": "pending_human_collection", + "items": [ + {"id": "NR01", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "NR02", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "NR03", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "CT01", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "CT02", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "CT03", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "XT01", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "XT02", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "NC01", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "NC02", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "NC03", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "AM01", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "AM02", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}}, + {"id": "AM03", "annotations": {"A1": null, "A2": null, "A3": null}, "free_text": {"A1": "", "A2": "", "A3": ""}} + ], + "disagreements": [], + "metrics": { + "fleiss_kappa": null, + "unanimous_fraction": null, + "unsure_rate_by_kind": {}, + "posthoc_agreement_with_rules": null, + "note": "Se publicarán tras la recolección con anotadores humanos independientes." + } +} diff --git a/datasets/independent_eval/annotator_pairs.csv b/datasets/independent_eval/annotator_pairs.csv new file mode 100644 index 0000000000000000000000000000000000000000..60116bf3103c5e37bcba605273db5d10e7fcb3fa --- /dev/null +++ b/datasets/independent_eval/annotator_pairs.csv @@ -0,0 +1,15 @@ +id,source_label,target_label,context +NR01,animal,humano,"Par de conceptos del marco." +NR02,animal,IA,"Par de conceptos del marco." +NR03,ascendente,descendente,"Par de conceptos del marco." +CT01,animal,animal,"El mismo concepto aparece dos veces." +CT02,animal,humano,"Par de conceptos del marco." +CT03,humano,humano,"El mismo concepto aparece dos veces." +XT01,animal,oscuridad,"Par de conceptos del marco." +XT02,inteligencia,cuántico,"Par de conceptos del marco." +NC01,entropía,síntesis,"Par de conceptos." +NC02,ruido,señal,"Par de conceptos." +NC03,caos,orden,"Par de conceptos." +AM01,vacío,vacío,"El mismo concepto aparece dos veces." +AM02,humano,IA,"Par de conceptos del marco." +AM03,vacío,vacío,"El mismo concepto aparece dos veces." diff --git a/datasets/independent_eval/annotator_pairs_rule_application.csv b/datasets/independent_eval/annotator_pairs_rule_application.csv new file mode 100644 index 0000000000000000000000000000000000000000..26da13b57a0d2fbb29493d5bc6062c18d59d1b9c --- /dev/null +++ b/datasets/independent_eval/annotator_pairs_rule_application.csv @@ -0,0 +1,43 @@ +id,kind,source,target,source_label,target_label,annotator,label,rule_label,matches_rule,free_text +NR01,out_of_rules,T08_adv_P0,T08_adv_P1,involución,vacío,A1,none,none,yes,Misma fase: creates y mirrorOf requieren fase opuesta. +NR01,out_of_rules,T08_adv_P0,T08_adv_P1,involución,vacío,A2,none,none,yes,Regla operativa clara; sin arista estructural. +NR01,out_of_rules,T08_adv_P0,T08_adv_P1,involución,vacío,A3,none,none,yes,Ninguna definición admite misma fase. +NR02,out_of_rules,T08_adv_P0,T08_ret_P0,involución,mundo,A1,none,none,yes,Lateral→lateral: no está en creation_rules ni en espejo. +NR02,out_of_rules,T08_adv_P0,T08_ret_P0,involución,mundo,A2,none,none,yes,Posición no reflejada (0≠2) y no es centro. +NR02,out_of_rules,T08_adv_P0,T08_ret_P0,involución,mundo,A3,none,none,yes,Fuera del dominio de las cuatro reglas. +NR03,out_of_rules,T02_adv_P2,T02_ret_P2,ascendente,memoria,A1,none,none,yes,Misma posición local en fase opuesta: no espejo ni creates. +NR03,out_of_rules,T02_adv_P2,T02_ret_P2,ascendente,memoria,A2,none,none,yes,Espejo exigiría 2↔0; aquí es 2↔2. +NR03,out_of_rules,T02_adv_P2,T02_ret_P2,ascendente,memoria,A3,none,none,yes,Sin arista admisible. +CT01,control_mirror,T08_adv_P0,T08_ret_P2,involución,cuerpo,A1,mirrorOf,mirrorOf,yes,"Misma tríada, fase opuesta, 0↔2: espejo canónico." +CT01,control_mirror,T08_adv_P0,T08_ret_P2,involución,cuerpo,A2,mirrorOf,mirrorOf,yes,Cumple los tres criterios de mirrorOf. +CT01,control_mirror,T08_adv_P0,T08_ret_P2,involución,cuerpo,A3,mirrorOf,mirrorOf,yes,Control positivo de espejo. +CT02,control_creates,T08_adv_P0,T08_ret_P1,involución,consciente,A1,creates,creates,yes,adv lateral → ret centro: regla 1 de creation_rules. +CT02,control_creates,T08_adv_P0,T08_ret_P1,involución,consciente,A2,creates,creates,yes,Creates canónico. +CT02,control_creates,T08_adv_P0,T08_ret_P1,involución,consciente,A3,creates,creates,yes,Control positivo de creates. +CT03,control_mirror,T08_adv_P1,T08_ret_P1,vacío,consciente,A1,mirrorOf,mirrorOf,yes,"Centro↔centro, fase opuesta: espejo obligatorio." +CT03,control_mirror,T08_adv_P1,T08_ret_P1,vacío,consciente,A2,mirrorOf,mirrorOf,yes,Etiqueta léxica irrelevante; estructura correcta. +CT03,control_mirror,T08_adv_P1,T08_ret_P1,vacío,consciente,A3,mirrorOf,mirrorOf,yes,Control centro-centro. +XT01,cross_triad,T08_adv_P0,T01_ret_P2,involución,caracter,A1,none,none,yes,Tríadas distintas: las reglas solo operan intra-tríada. +XT01,cross_triad,T08_adv_P0,T01_ret_P2,involución,caracter,A2,none,none,yes,Sin definición operativa cross-tríada. +XT01,cross_triad,T08_adv_P0,T01_ret_P2,involución,caracter,A3,none,none,yes,none por dominio de reglas. +XT02,cross_triad,T03_adv_P1,T10_ret_P1,inteligencia,cuántico,A1,none,none,yes,Centros de tríadas distintas: no hay arista formal. +XT02,cross_triad,T03_adv_P1,T10_ret_P1,inteligencia,cuántico,A2,none,none,yes,Fuera del generador de 390 candidatos. +XT02,cross_triad,T03_adv_P1,T10_ret_P1,inteligencia,cuántico,A3,none,none,yes,none. +NC01,new_concept,NEW_adv_P0,NEW_ret_P2,entropía,síntesis,A1,mirrorOf,unspecified,n/a,"Estructura posicional análoga a espejo (0↔2, fases opuestas); aplico analogía." +NC01,new_concept,NEW_adv_P0,NEW_ret_P2,entropía,síntesis,A2,unsure,unspecified,n/a,Conceptos nuevos: la definición no cubre vocabulario ajeno; unsure. +NC01,new_concept,NEW_adv_P0,NEW_ret_P2,entropía,síntesis,A3,unsure,unspecified,n/a,Sin ancla en las 13 tríadas; prefiero unsure. +NC02,new_concept,NEW_adv_P1,NEW_ret_P0,ruido,señal,A1,creates,unspecified,n/a,"Análogo creates: centro→lateral, fase opuesta." +NC02,new_concept,NEW_adv_P1,NEW_ret_P0,ruido,señal,A2,unsure,unspecified,n/a,Analogía estructural vs. semántica léxica no resuelta. +NC02,new_concept,NEW_adv_P1,NEW_ret_P0,ruido,señal,A3,none,unspecified,n/a,Sin vocabulario canónico no aplico creates. +NC03,new_concept,NEW_adv_P0,NEW_adv_P2,caos,orden,A1,none,unspecified,n/a,"Misma fase: ni espejo ni creates, aunque sean conceptos nuevos." +NC03,new_concept,NEW_adv_P0,NEW_adv_P2,caos,orden,A2,none,unspecified,n/a,Misma fase excluye ambas relaciones. +NC03,new_concept,NEW_adv_P0,NEW_adv_P2,caos,orden,A3,none,unspecified,n/a,none. +AM01,ambiguous,T06_adv_P2,T06_ret_P0,vacío,vacío,A1,mirrorOf,mirrorOf,yes,Estructura 2↔0 fase opuesta: mirrorOf; etiqueta léxica irrelevante. +AM01,ambiguous,T06_adv_P2,T06_ret_P0,vacío,vacío,A2,mirrorOf,mirrorOf,yes,Doble 'vacío' no anula el espejo estructural. +AM01,ambiguous,T06_adv_P2,T06_ret_P0,vacío,vacío,A3,unsure,mirrorOf,partial,¿Identidad conceptual o espejo? Ambigüedad semántica → unsure. +AM02,ambiguous,T08_adv_P1,T08_ret_P0,vacío,mundo,A1,creates,creates,yes,adv centro → ret left: regla 2 de creation_rules. +AM02,ambiguous,T08_adv_P1,T08_ret_P0,vacío,mundo,A2,creates,creates,yes,La carga semántica de 'vacío' no altera la regla posicional. +AM02,ambiguous,T08_adv_P1,T08_ret_P0,vacío,mundo,A3,creates,creates,yes,Creates por regla; el vacío actúa como nodo estructural. +AM03,ambiguous,T13_ret_P1,T13_adv_P1,vacío,vacío,A1,mirrorOf,mirrorOf,yes,"Centro↔centro, fases opuestas, extremos del ciclo: mirrorOf." +AM03,ambiguous,T13_ret_P1,T13_adv_P1,vacío,vacío,A2,mirrorOf,mirrorOf,yes,Estructura correcta; doble vacío en extremos no invalida espejo. +AM03,ambiguous,T13_ret_P1,T13_adv_P1,vacío,vacío,A3,unsure,mirrorOf,partial,Extremos del ciclo con doble vacío: interpretación abierta → unsure. diff --git a/datasets/independent_eval/independent_pairs.csv b/datasets/independent_eval/independent_pairs.csv new file mode 100644 index 0000000000000000000000000000000000000000..d7fef2d53c7ff58faa5d5b7d9becc350b4fc215f --- /dev/null +++ b/datasets/independent_eval/independent_pairs.csv @@ -0,0 +1,15 @@ +id,kind,source,target,source_label,target_label,context +NR01,out_of_rules,T08_adv_P0,T08_adv_P1,involución,vacío,"Misma fase (avance), lateral→centro. Las reglas creates exigen fase opuesta." +NR02,out_of_rules,T08_adv_P0,T08_ret_P0,involución,mundo,Fase opuesta pero lateral→lateral (no lateral→centro ni centro→lateral). +NR03,out_of_rules,T02_adv_P2,T02_ret_P2,ascendente,memoria,"Fase opuesta, misma posición lateral (right→right). No es espejo ni creates." +CT01,control_mirror,T08_adv_P0,T08_ret_P2,involución,cuerpo,"Espejo canónico: left↔right, fase opuesta." +CT02,control_creates,T08_adv_P0,T08_ret_P1,involución,consciente,Creates canónico: lateral avance → centro retroceso. +CT03,control_mirror,T08_adv_P1,T08_ret_P1,vacío,consciente,Espejo centro↔centro. +XT01,cross_triad,T08_adv_P0,T01_ret_P2,involución,caracter,Tríadas distintas. Las reglas operativas solo definen mirror/creates intra-tríada. +XT02,cross_triad,T03_adv_P1,T10_ret_P1,inteligencia,cuántico,Centros de tríadas distintas. +NC01,new_concept,NEW_adv_P0,NEW_ret_P2,entropía,síntesis,Etiquetas ajenas al vocabulario canónico; estructura posicional análoga a espejo. +NC02,new_concept,NEW_adv_P1,NEW_ret_P0,ruido,señal,Centro→lateral con conceptos nuevos (análogo creates). +NC03,new_concept,NEW_adv_P0,NEW_adv_P2,caos,orden,"Misma fase, conceptos nuevos." +AM01,ambiguous,T06_adv_P2,T06_ret_P0,vacío,vacío,Espejo right↔left con la misma etiqueta léxica 'vacío' en ambos polos. +AM02,ambiguous,T08_adv_P1,T08_ret_P0,vacío,mundo,Creates centro→lateral; el centro es 'vacío' (etiqueta cargada). +AM03,ambiguous,T13_ret_P1,T13_adv_P1,vacío,vacío,"Espejo centro-centro, ambos 'vacío', fases opuestas (extremos del ciclo)." diff --git a/datasets/independent_eval/instrument/ACCESS_LOG.template.json b/datasets/independent_eval/instrument/ACCESS_LOG.template.json new file mode 100644 index 0000000000000000000000000000000000000000..6b834a0149b8e3780f7c47d09bb2ffe96c10397c --- /dev/null +++ b/datasets/independent_eval/instrument/ACCESS_LOG.template.json @@ -0,0 +1,26 @@ +{ + "title": "Registro de acceso e independencia del anotador (EXP-A)", + "purpose": "Hacer auditable no solo el κ, sino que el anotador no recibió el marco antes de anotar.", + "entries": [ + { + "annotator_id": "A1", + "instrument_delivered_at": "YYYY-MM-DDTHH:MM:SSZ", + "instrument_contents": ["INSTRUCTIONS.md", "pairs.csv"], + "materials_explicitly_withheld": [ + "README.md", + "MANIFIESTO.md", + "EXPERIMENTOS.md", + "docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md", + "docs/CARACTER_REPOSITORIO.md", + "rule_reference.json", + "datasets/relation_candidates.csv", + "experiments/results/*" + ], + "declared_prior_exposure_to_repo": false, + "declared_prior_exposure_notes": "", + "annotations_received_at": "YYYY-MM-DDTHH:MM:SSZ", + "included_in_primary_kappa": true + } + ], + "exclusion_rule": "Si declared_prior_exposure_to_repo es true, o si se documenta acceso al manifiesto/README antes de anotar, el anotador se excluye del κ primario y se reporta aparte." +} diff --git a/datasets/independent_eval/instrument/INSTRUCTIONS.md b/datasets/independent_eval/instrument/INSTRUCTIONS.md new file mode 100644 index 0000000000000000000000000000000000000000..b57f75e8f138ef8be219ed15f5ea4bdd30539b6f --- /dev/null +++ b/datasets/independent_eval/instrument/INSTRUCTIONS.md @@ -0,0 +1,47 @@ +# Instrucciones de anotación (instrumento autocontenido) + +Este paquete es **autosuficiente**. No necesita ni debe acompañarse del +repositorio del proyecto, del README, del manifiesto conceptual ni de +documentos de experimentos. + +## Tarea + +Para cada fila del archivo `pairs.csv`, elija **una** etiqueta que describa +la relación entre `source_label` y `target_label`, usando solo el contexto +de esa fila y las definiciones de abajo. + +## Etiquetas admitidas + +| Etiqueta | Definición operativa (neutra) | +|----------|------------------------------| +| `none` | No hay relación estructural clara entre los dos términos en el sentido de las otras dos etiquetas. | +| `mirrorOf` | Los términos se comportan como **polos complementarios** de una misma oposición (uno refleja al otro; si uno es «un lado», el otro es el lado opuesto o el centro simétrico). | +| `creates` | Un término **genera, produce o da lugar** al otro en una transición (origen → resultado), no solo como oposición estática. | +| `unsure` | No puede decidir con la información dada. | + +No se le pide que conozca un marco teórico externo. Aplique solo estas definiciones. + +## Reglas de procedimiento + +1. Anote de forma **independiente** (sin consultar a otros anotadores). +2. **No** busque el repositorio del proyecto, manifiestos ni informes de métricas antes de terminar. +3. Si ya conoce el proyecto, declárelo en la hoja de acceso (`ACCESS_LOG` que le entregue el coordinador); sus juicios pueden excluirse del κ principal. +4. Devuelva un archivo `annotations_.json` con la forma: + +```json +{ + "annotator_id": "A?", + "labels": { + "NR01": "none", + "NR02": "creates" + } +} +``` + +(un valor por cada `id` de `pairs.csv`) + +## Qué **no** forma parte de este instrumento + +- Manifiestos filosóficos o cosmologías +- Código, ontologías, resultados de modelos +- Etiquetas «correctas» de referencia diff --git a/datasets/independent_eval/instrument/README.md b/datasets/independent_eval/instrument/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bf4e2fe6169bfd6bc4994e8304bae362ef7014e2 --- /dev/null +++ b/datasets/independent_eval/instrument/README.md @@ -0,0 +1,20 @@ +# Instrumento EXP-A (entrega al anotador) + +Paquete **autocontenido** para el protocolo ciego. Se entrega **fuera** del +clon del repositorio (zip, carpeta separada, o mensaje con solo estos archivos). + +| Archivo | Rol | +|---------|-----| +| `INSTRUCTIONS.md` | Definiciones neutras de etiquetas; sin tesis del proyecto | +| `pairs.csv` | 14 pares (id, etiquetas, contexto genérico) | +| `ACCESS_LOG.template.json` | Plantilla para el **coordinador** (no se envía al anotador como tarea) | + +## Flujo del coordinador + +1. Copiar solo `INSTRUCTIONS.md` + `pairs.csv` al anotador. +2. Rellenar una entrada en el log de acceso (copia de la plantilla) **antes** de la entrega. +3. Al recibir anotaciones, completar `annotations_received_at` y `declared_prior_exposure_*`. +4. Archivar el log junto a `annotations.json` en el repo (post-hoc). + +La ceguera es un **estado del anotador**, no del repo público. Este instrumento +existe para no obligar al anotador a abrir el repo. diff --git a/datasets/independent_eval/instrument/pairs.csv b/datasets/independent_eval/instrument/pairs.csv new file mode 100644 index 0000000000000000000000000000000000000000..8acf145a579433481d96ec5aa8915c4df1dabbfe --- /dev/null +++ b/datasets/independent_eval/instrument/pairs.csv @@ -0,0 +1,15 @@ +id,source_label,target_label,context +NR01,animal,humano,"Par de conceptos." +NR02,animal,IA,"Par de conceptos." +NR03,ascendente,descendente,"Par de conceptos." +CT01,animal,animal,"El mismo concepto aparece dos veces." +CT02,animal,humano,"Par de conceptos." +CT03,humano,humano,"El mismo concepto aparece dos veces." +XT01,animal,oscuridad,"Par de conceptos." +XT02,inteligencia,cuántico,"Par de conceptos." +NC01,entropía,síntesis,"Par de conceptos." +NC02,ruido,señal,"Par de conceptos." +NC03,caos,orden,"Par de conceptos." +AM01,vacío,vacío,"El mismo concepto aparece dos veces." +AM02,humano,IA,"Par de conceptos." +AM03,vacío,vacío,"El mismo concepto aparece dos veces." diff --git a/datasets/independent_eval/rule_reference.json b/datasets/independent_eval/rule_reference.json new file mode 100644 index 0000000000000000000000000000000000000000..18414b173e7607d8b3a19617738e1c200b75d320 --- /dev/null +++ b/datasets/independent_eval/rule_reference.json @@ -0,0 +1,16 @@ +{ + "NR01": {"rule_label": "none", "notes": "Caso negativo canónico: misma fase."}, + "NR02": {"rule_label": "none", "notes": "Posiciones no cubiertas por creation_rules."}, + "NR03": {"rule_label": "none", "notes": "Misma posición local: las reglas no generan arista."}, + "CT01": {"rule_label": "mirrorOf", "notes": "Control: debe ser mirrorOf bajo reglas."}, + "CT02": {"rule_label": "creates", "notes": "Control: debe ser creates bajo reglas."}, + "CT03": {"rule_label": "mirrorOf", "notes": "Control centro."}, + "XT01": {"rule_label": "none", "notes": "Independiente del generador de 390 candidatos."}, + "XT02": {"rule_label": "none", "notes": "Sin regla formal intra-especificación."}, + "NC01": {"rule_label": "unspecified", "notes": "El anotador decide si proyecta mirrorOf por analogía estructural."}, + "NC02": {"rule_label": "unspecified", "notes": "Analogía estructural vs. semántica léxica."}, + "NC03": {"rule_label": "unspecified", "notes": "Sin análogo creates/mirror en reglas."}, + "AM01": {"rule_label": "mirrorOf", "notes": "Ambigüedad semántica: ¿espejo o identidad conceptual?"}, + "AM02": {"rule_label": "creates", "notes": "¿El vacío crea el mundo o solo cumple la regla posicional?"}, + "AM03": {"rule_label": "mirrorOf", "notes": "Doble vacío en extremos: interpretación abierta."} +} diff --git a/datasets/ingestion/README.md b/datasets/ingestion/README.md new file mode 100644 index 0000000000000000000000000000000000000000..02c9611a631933aefeaef675da9fa8a689ac731d --- /dev/null +++ b/datasets/ingestion/README.md @@ -0,0 +1,44 @@ +# Ingesta guiada de dominios externos + +Esta carpeta permite a investigadores de otras disciplinas **alinear conceptos nuevos** a la ontología canónica de 78 nodos **sin modificar** `data/iom_spec.json`, Lean, RDF/OWL ni SHACL. + +## Estructura + +``` +datasets/ingestion/ +├── README.md ← este archivo +├── templates/ +│ ├── plantilla_dominio.csv ← plantilla vacía +│ └── cosmos_nahuatl.csv ← Cinco Soles / Mictlán +└── aligned/ ← salida del script (generada) +``` + +## Flujo rápido + +1. Copia una plantilla o crea tu CSV con las columnas: + - `external_id` (obligatorio) + - `external_label` (obligatorio) + - `mapped_node_id` (uno de los 78 de `datasets/triad_nodes.csv`) + - `perspective`, `phase`, `position`, `relation_candidate`, `notes` (opcionales) + +2. Ejecuta el script de validación y alineación: + +```bash +python scripts/importar_datos_personalizados.py \ + --input datasets/ingestion/templates/cosmos_nahuatl.csv \ + --output datasets/ingestion/aligned/cosmos_nahuatl_aligned.csv +``` + +3. Revisa el informe JSON generado junto al CSV alineado. Solo se aceptan mapeos a nodos existentes. + +## Documentación de mapeo por dominio + +Consulta el catálogo completo con ejemplos de cosmología náhuatl y otras disciplinas: + +→ [`docs/CATALOGO_DOMINIOS.md`](../../docs/CATALOGO_DOMINIOS.md) + +## Reglas de oro + +- La ontología core es **inmutable** (bóveda bancaria). +- Los datos externos viven solo en `datasets/ingestion/`. +- Las relaciones candidatas se validan contra las mismas reglas `mirrorOf` / `creates` documentadas en [`docs/RELACIONES_OPERATIVAS.md`](../../docs/RELACIONES_OPERATIVAS.md). diff --git a/datasets/ingestion/aligned/.gitkeep b/datasets/ingestion/aligned/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..9ea1b9d72ed5e690cf70eeec292de7cd37ce93c5 --- /dev/null +++ b/datasets/ingestion/aligned/.gitkeep @@ -0,0 +1,2 @@ +# Directorio de salida del script importar_datos_personalizados.py +# Los CSV alineados y los informes .report.json se generan aquí. diff --git a/datasets/ingestion/templates/cosmos_nahuatl.csv b/datasets/ingestion/templates/cosmos_nahuatl.csv new file mode 100644 index 0000000000000000000000000000000000000000..e8f3037797c4484b3e97de74d86096658f916dfb --- /dev/null +++ b/datasets/ingestion/templates/cosmos_nahuatl.csv @@ -0,0 +1,17 @@ +external_id,external_label,mapped_node_id,perspective,phase,position,relation_candidate,notes +# spec 1.7.0 — tríadas 1–13; posiciones →|0|→ +nah_sol_viento,Nahui_Ehecatl_Sol_Viento,T01_adv_P0,Evol,adv,→,none,"Primera edad; oscuridad inicial" +nah_sol_fuego,Nahui_Quiahuitl_Sol_Fuego,T01_adv_P1,Invol,adv,0,creates,"Lluvia de fuego; consciencia" +nah_sol_agua,Nahui_Atl_Sol_Agua,T01_ret_P1,Invol,ret,0,creates,"Diluvio" +nah_sol_tierra,Nahui_Ocelotl_Sol_Tierra,T01_ret_P2,Invol,ret,←,creates,"Temblores; retorno a oscuridad" +nah_sol_ollin,Nahui_Ollin_Sol_Movimiento,T01_adv_P2,Tot,adv,→,none,"Quinto Sol / luz presente" +nah_tezcatlipoca,Tezcatlipoca,T01_adv_P0,Ind,adv,→,none,"Fuerza oscura" +nah_quetzalcoatl,Quetzalcoatl,T01_ret_P0,Ind,ret,←,none,"Fuerza luminosa reflejada" +nah_lucha_dioses,lucha_Tezcatlipoca_Quetzalcoatl,T01_adv_P1,D,adv,0,mirrorOf,"Dualidad (consciencia)" +nah_vida,vida,T03_adv_P2,Tot,adv,→,none,"Polo vida" +nah_muerte,muerte,T03_adv_P0,Ind,adv,→,none,"Polo muerte" +nah_vida_muerte,vida_muerte,T03_adv_P1,D,adv,0,mirrorOf,"Dicotomía mesoamericana" +nah_tlaltecuhtli,Tlaltecuhtli,T11_ret_P1,Invol,ret,0,creates,"Tierra devoradora; espacio/vacío" +nah_mictlan,Mictlan,T11_ret_P0,Tot,ret,←,none,"Lugar de los muertos; vacío" +nah_teyolia,teyolia,T03_adv_P0,Ind,adv,→,creates,"Entidad anímica" +nah_camino_mictlan,camino_al_Mictlan,T11_ret_P0,Invol,ret,←,creates,"Retorno al vacío" diff --git a/datasets/ingestion/templates/plantilla_dominio.csv b/datasets/ingestion/templates/plantilla_dominio.csv new file mode 100644 index 0000000000000000000000000000000000000000..aff1f59aa916d73f9f158db5d7e240df5a5b2870 --- /dev/null +++ b/datasets/ingestion/templates/plantilla_dominio.csv @@ -0,0 +1,9 @@ +external_id,external_label,mapped_node_id,perspective,phase,position,relation_candidate,notes +# Obligatorio: external_id, external_label +# mapped_node_id: uno de los 78 node_id de datasets/triad_nodes.csv (ej. T01_adv_P0) +# perspective: Ind | D | Tot | Evol | Invol +# phase: adv | ret +# position: left | center | right +# relation_candidate: none | mirrorOf | creates (opcional; se valida contra reglas) +# notes: texto libre +ejemplo_01,mi_concepto,T01_adv_P0,Ind,adv,left,none,"Descripción breve del mapeo" diff --git a/datasets/relation_candidates.csv b/datasets/relation_candidates.csv new file mode 100644 index 0000000000000000000000000000000000000000..aa5fb70545964f71d3dc7f837925dbbf5754c4d0 --- /dev/null +++ b/datasets/relation_candidates.csv @@ -0,0 +1,391 @@ +triad_index,source,target,relation +1,T01_adv_P0,T01_adv_P1,none +1,T01_adv_P0,T01_adv_P2,none +1,T01_adv_P0,T01_ret_P0,none +1,T01_adv_P0,T01_ret_P1,creates +1,T01_adv_P0,T01_ret_P2,mirrorOf +1,T01_adv_P1,T01_adv_P0,none +1,T01_adv_P1,T01_adv_P2,none +1,T01_adv_P1,T01_ret_P0,creates +1,T01_adv_P1,T01_ret_P1,mirrorOf +1,T01_adv_P1,T01_ret_P2,creates +1,T01_adv_P2,T01_adv_P0,none +1,T01_adv_P2,T01_adv_P1,none +1,T01_adv_P2,T01_ret_P0,mirrorOf +1,T01_adv_P2,T01_ret_P1,creates +1,T01_adv_P2,T01_ret_P2,none +1,T01_ret_P0,T01_adv_P0,none +1,T01_ret_P0,T01_adv_P1,creates +1,T01_ret_P0,T01_adv_P2,mirrorOf +1,T01_ret_P0,T01_ret_P1,none +1,T01_ret_P0,T01_ret_P2,none +1,T01_ret_P1,T01_adv_P0,creates +1,T01_ret_P1,T01_adv_P1,mirrorOf +1,T01_ret_P1,T01_adv_P2,creates +1,T01_ret_P1,T01_ret_P0,none +1,T01_ret_P1,T01_ret_P2,none +1,T01_ret_P2,T01_adv_P0,mirrorOf +1,T01_ret_P2,T01_adv_P1,creates +1,T01_ret_P2,T01_adv_P2,none +1,T01_ret_P2,T01_ret_P0,none +1,T01_ret_P2,T01_ret_P1,none +2,T02_adv_P0,T02_adv_P1,none +2,T02_adv_P0,T02_adv_P2,none +2,T02_adv_P0,T02_ret_P0,none +2,T02_adv_P0,T02_ret_P1,creates +2,T02_adv_P0,T02_ret_P2,mirrorOf +2,T02_adv_P1,T02_adv_P0,none +2,T02_adv_P1,T02_adv_P2,none +2,T02_adv_P1,T02_ret_P0,creates +2,T02_adv_P1,T02_ret_P1,mirrorOf +2,T02_adv_P1,T02_ret_P2,creates +2,T02_adv_P2,T02_adv_P0,none +2,T02_adv_P2,T02_adv_P1,none +2,T02_adv_P2,T02_ret_P0,mirrorOf +2,T02_adv_P2,T02_ret_P1,creates +2,T02_adv_P2,T02_ret_P2,none +2,T02_ret_P0,T02_adv_P0,none +2,T02_ret_P0,T02_adv_P1,creates +2,T02_ret_P0,T02_adv_P2,mirrorOf +2,T02_ret_P0,T02_ret_P1,none +2,T02_ret_P0,T02_ret_P2,none +2,T02_ret_P1,T02_adv_P0,creates +2,T02_ret_P1,T02_adv_P1,mirrorOf +2,T02_ret_P1,T02_adv_P2,creates +2,T02_ret_P1,T02_ret_P0,none +2,T02_ret_P1,T02_ret_P2,none +2,T02_ret_P2,T02_adv_P0,mirrorOf +2,T02_ret_P2,T02_adv_P1,creates +2,T02_ret_P2,T02_adv_P2,none +2,T02_ret_P2,T02_ret_P0,none +2,T02_ret_P2,T02_ret_P1,none +3,T03_adv_P0,T03_adv_P1,none +3,T03_adv_P0,T03_adv_P2,none +3,T03_adv_P0,T03_ret_P0,none +3,T03_adv_P0,T03_ret_P1,creates +3,T03_adv_P0,T03_ret_P2,mirrorOf +3,T03_adv_P1,T03_adv_P0,none +3,T03_adv_P1,T03_adv_P2,none +3,T03_adv_P1,T03_ret_P0,creates +3,T03_adv_P1,T03_ret_P1,mirrorOf +3,T03_adv_P1,T03_ret_P2,creates +3,T03_adv_P2,T03_adv_P0,none +3,T03_adv_P2,T03_adv_P1,none +3,T03_adv_P2,T03_ret_P0,mirrorOf +3,T03_adv_P2,T03_ret_P1,creates +3,T03_adv_P2,T03_ret_P2,none +3,T03_ret_P0,T03_adv_P0,none +3,T03_ret_P0,T03_adv_P1,creates +3,T03_ret_P0,T03_adv_P2,mirrorOf +3,T03_ret_P0,T03_ret_P1,none +3,T03_ret_P0,T03_ret_P2,none +3,T03_ret_P1,T03_adv_P0,creates +3,T03_ret_P1,T03_adv_P1,mirrorOf +3,T03_ret_P1,T03_adv_P2,creates +3,T03_ret_P1,T03_ret_P0,none +3,T03_ret_P1,T03_ret_P2,none +3,T03_ret_P2,T03_adv_P0,mirrorOf +3,T03_ret_P2,T03_adv_P1,creates +3,T03_ret_P2,T03_adv_P2,none +3,T03_ret_P2,T03_ret_P0,none +3,T03_ret_P2,T03_ret_P1,none +4,T04_adv_P0,T04_adv_P1,none +4,T04_adv_P0,T04_adv_P2,none +4,T04_adv_P0,T04_ret_P0,none +4,T04_adv_P0,T04_ret_P1,creates +4,T04_adv_P0,T04_ret_P2,mirrorOf +4,T04_adv_P1,T04_adv_P0,none +4,T04_adv_P1,T04_adv_P2,none +4,T04_adv_P1,T04_ret_P0,creates +4,T04_adv_P1,T04_ret_P1,mirrorOf +4,T04_adv_P1,T04_ret_P2,creates +4,T04_adv_P2,T04_adv_P0,none +4,T04_adv_P2,T04_adv_P1,none +4,T04_adv_P2,T04_ret_P0,mirrorOf +4,T04_adv_P2,T04_ret_P1,creates +4,T04_adv_P2,T04_ret_P2,none +4,T04_ret_P0,T04_adv_P0,none +4,T04_ret_P0,T04_adv_P1,creates +4,T04_ret_P0,T04_adv_P2,mirrorOf +4,T04_ret_P0,T04_ret_P1,none +4,T04_ret_P0,T04_ret_P2,none +4,T04_ret_P1,T04_adv_P0,creates +4,T04_ret_P1,T04_adv_P1,mirrorOf +4,T04_ret_P1,T04_adv_P2,creates +4,T04_ret_P1,T04_ret_P0,none +4,T04_ret_P1,T04_ret_P2,none +4,T04_ret_P2,T04_adv_P0,mirrorOf +4,T04_ret_P2,T04_adv_P1,creates +4,T04_ret_P2,T04_adv_P2,none +4,T04_ret_P2,T04_ret_P0,none +4,T04_ret_P2,T04_ret_P1,none +5,T05_adv_P0,T05_adv_P1,none +5,T05_adv_P0,T05_adv_P2,none +5,T05_adv_P0,T05_ret_P0,none +5,T05_adv_P0,T05_ret_P1,creates +5,T05_adv_P0,T05_ret_P2,mirrorOf +5,T05_adv_P1,T05_adv_P0,none +5,T05_adv_P1,T05_adv_P2,none +5,T05_adv_P1,T05_ret_P0,creates +5,T05_adv_P1,T05_ret_P1,mirrorOf +5,T05_adv_P1,T05_ret_P2,creates +5,T05_adv_P2,T05_adv_P0,none +5,T05_adv_P2,T05_adv_P1,none +5,T05_adv_P2,T05_ret_P0,mirrorOf +5,T05_adv_P2,T05_ret_P1,creates +5,T05_adv_P2,T05_ret_P2,none +5,T05_ret_P0,T05_adv_P0,none +5,T05_ret_P0,T05_adv_P1,creates +5,T05_ret_P0,T05_adv_P2,mirrorOf +5,T05_ret_P0,T05_ret_P1,none +5,T05_ret_P0,T05_ret_P2,none +5,T05_ret_P1,T05_adv_P0,creates +5,T05_ret_P1,T05_adv_P1,mirrorOf +5,T05_ret_P1,T05_adv_P2,creates +5,T05_ret_P1,T05_ret_P0,none +5,T05_ret_P1,T05_ret_P2,none +5,T05_ret_P2,T05_adv_P0,mirrorOf +5,T05_ret_P2,T05_adv_P1,creates +5,T05_ret_P2,T05_adv_P2,none +5,T05_ret_P2,T05_ret_P0,none +5,T05_ret_P2,T05_ret_P1,none +6,T06_adv_P0,T06_adv_P1,none +6,T06_adv_P0,T06_adv_P2,none +6,T06_adv_P0,T06_ret_P0,none +6,T06_adv_P0,T06_ret_P1,creates +6,T06_adv_P0,T06_ret_P2,mirrorOf +6,T06_adv_P1,T06_adv_P0,none +6,T06_adv_P1,T06_adv_P2,none +6,T06_adv_P1,T06_ret_P0,creates +6,T06_adv_P1,T06_ret_P1,mirrorOf +6,T06_adv_P1,T06_ret_P2,creates +6,T06_adv_P2,T06_adv_P0,none +6,T06_adv_P2,T06_adv_P1,none +6,T06_adv_P2,T06_ret_P0,mirrorOf +6,T06_adv_P2,T06_ret_P1,creates +6,T06_adv_P2,T06_ret_P2,none +6,T06_ret_P0,T06_adv_P0,none +6,T06_ret_P0,T06_adv_P1,creates +6,T06_ret_P0,T06_adv_P2,mirrorOf +6,T06_ret_P0,T06_ret_P1,none +6,T06_ret_P0,T06_ret_P2,none +6,T06_ret_P1,T06_adv_P0,creates +6,T06_ret_P1,T06_adv_P1,mirrorOf +6,T06_ret_P1,T06_adv_P2,creates +6,T06_ret_P1,T06_ret_P0,none +6,T06_ret_P1,T06_ret_P2,none +6,T06_ret_P2,T06_adv_P0,mirrorOf +6,T06_ret_P2,T06_adv_P1,creates +6,T06_ret_P2,T06_adv_P2,none +6,T06_ret_P2,T06_ret_P0,none +6,T06_ret_P2,T06_ret_P1,none +7,T07_adv_P0,T07_adv_P1,none +7,T07_adv_P0,T07_adv_P2,none +7,T07_adv_P0,T07_ret_P0,none +7,T07_adv_P0,T07_ret_P1,creates +7,T07_adv_P0,T07_ret_P2,mirrorOf +7,T07_adv_P1,T07_adv_P0,none +7,T07_adv_P1,T07_adv_P2,none +7,T07_adv_P1,T07_ret_P0,creates +7,T07_adv_P1,T07_ret_P1,mirrorOf +7,T07_adv_P1,T07_ret_P2,creates +7,T07_adv_P2,T07_adv_P0,none +7,T07_adv_P2,T07_adv_P1,none +7,T07_adv_P2,T07_ret_P0,mirrorOf +7,T07_adv_P2,T07_ret_P1,creates +7,T07_adv_P2,T07_ret_P2,none +7,T07_ret_P0,T07_adv_P0,none +7,T07_ret_P0,T07_adv_P1,creates +7,T07_ret_P0,T07_adv_P2,mirrorOf +7,T07_ret_P0,T07_ret_P1,none +7,T07_ret_P0,T07_ret_P2,none +7,T07_ret_P1,T07_adv_P0,creates +7,T07_ret_P1,T07_adv_P1,mirrorOf +7,T07_ret_P1,T07_adv_P2,creates +7,T07_ret_P1,T07_ret_P0,none +7,T07_ret_P1,T07_ret_P2,none +7,T07_ret_P2,T07_adv_P0,mirrorOf +7,T07_ret_P2,T07_adv_P1,creates +7,T07_ret_P2,T07_adv_P2,none +7,T07_ret_P2,T07_ret_P0,none +7,T07_ret_P2,T07_ret_P1,none +8,T08_adv_P0,T08_adv_P1,none +8,T08_adv_P0,T08_adv_P2,none +8,T08_adv_P0,T08_ret_P0,none +8,T08_adv_P0,T08_ret_P1,creates +8,T08_adv_P0,T08_ret_P2,mirrorOf +8,T08_adv_P1,T08_adv_P0,none +8,T08_adv_P1,T08_adv_P2,none +8,T08_adv_P1,T08_ret_P0,creates +8,T08_adv_P1,T08_ret_P1,mirrorOf +8,T08_adv_P1,T08_ret_P2,creates +8,T08_adv_P2,T08_adv_P0,none +8,T08_adv_P2,T08_adv_P1,none +8,T08_adv_P2,T08_ret_P0,mirrorOf +8,T08_adv_P2,T08_ret_P1,creates +8,T08_adv_P2,T08_ret_P2,none +8,T08_ret_P0,T08_adv_P0,none +8,T08_ret_P0,T08_adv_P1,creates +8,T08_ret_P0,T08_adv_P2,mirrorOf +8,T08_ret_P0,T08_ret_P1,none +8,T08_ret_P0,T08_ret_P2,none +8,T08_ret_P1,T08_adv_P0,creates +8,T08_ret_P1,T08_adv_P1,mirrorOf +8,T08_ret_P1,T08_adv_P2,creates +8,T08_ret_P1,T08_ret_P0,none +8,T08_ret_P1,T08_ret_P2,none +8,T08_ret_P2,T08_adv_P0,mirrorOf +8,T08_ret_P2,T08_adv_P1,creates +8,T08_ret_P2,T08_adv_P2,none +8,T08_ret_P2,T08_ret_P0,none +8,T08_ret_P2,T08_ret_P1,none +9,T09_adv_P0,T09_adv_P1,none +9,T09_adv_P0,T09_adv_P2,none +9,T09_adv_P0,T09_ret_P0,none +9,T09_adv_P0,T09_ret_P1,creates +9,T09_adv_P0,T09_ret_P2,mirrorOf +9,T09_adv_P1,T09_adv_P0,none +9,T09_adv_P1,T09_adv_P2,none +9,T09_adv_P1,T09_ret_P0,creates +9,T09_adv_P1,T09_ret_P1,mirrorOf +9,T09_adv_P1,T09_ret_P2,creates +9,T09_adv_P2,T09_adv_P0,none +9,T09_adv_P2,T09_adv_P1,none +9,T09_adv_P2,T09_ret_P0,mirrorOf +9,T09_adv_P2,T09_ret_P1,creates +9,T09_adv_P2,T09_ret_P2,none +9,T09_ret_P0,T09_adv_P0,none +9,T09_ret_P0,T09_adv_P1,creates +9,T09_ret_P0,T09_adv_P2,mirrorOf +9,T09_ret_P0,T09_ret_P1,none +9,T09_ret_P0,T09_ret_P2,none +9,T09_ret_P1,T09_adv_P0,creates +9,T09_ret_P1,T09_adv_P1,mirrorOf +9,T09_ret_P1,T09_adv_P2,creates +9,T09_ret_P1,T09_ret_P0,none +9,T09_ret_P1,T09_ret_P2,none +9,T09_ret_P2,T09_adv_P0,mirrorOf +9,T09_ret_P2,T09_adv_P1,creates +9,T09_ret_P2,T09_adv_P2,none +9,T09_ret_P2,T09_ret_P0,none +9,T09_ret_P2,T09_ret_P1,none +10,T10_adv_P0,T10_adv_P1,none +10,T10_adv_P0,T10_adv_P2,none +10,T10_adv_P0,T10_ret_P0,none +10,T10_adv_P0,T10_ret_P1,creates +10,T10_adv_P0,T10_ret_P2,mirrorOf +10,T10_adv_P1,T10_adv_P0,none +10,T10_adv_P1,T10_adv_P2,none +10,T10_adv_P1,T10_ret_P0,creates +10,T10_adv_P1,T10_ret_P1,mirrorOf +10,T10_adv_P1,T10_ret_P2,creates +10,T10_adv_P2,T10_adv_P0,none +10,T10_adv_P2,T10_adv_P1,none +10,T10_adv_P2,T10_ret_P0,mirrorOf +10,T10_adv_P2,T10_ret_P1,creates +10,T10_adv_P2,T10_ret_P2,none +10,T10_ret_P0,T10_adv_P0,none +10,T10_ret_P0,T10_adv_P1,creates +10,T10_ret_P0,T10_adv_P2,mirrorOf +10,T10_ret_P0,T10_ret_P1,none +10,T10_ret_P0,T10_ret_P2,none +10,T10_ret_P1,T10_adv_P0,creates +10,T10_ret_P1,T10_adv_P1,mirrorOf +10,T10_ret_P1,T10_adv_P2,creates +10,T10_ret_P1,T10_ret_P0,none +10,T10_ret_P1,T10_ret_P2,none +10,T10_ret_P2,T10_adv_P0,mirrorOf +10,T10_ret_P2,T10_adv_P1,creates +10,T10_ret_P2,T10_adv_P2,none +10,T10_ret_P2,T10_ret_P0,none +10,T10_ret_P2,T10_ret_P1,none +11,T11_adv_P0,T11_adv_P1,none +11,T11_adv_P0,T11_adv_P2,none +11,T11_adv_P0,T11_ret_P0,none +11,T11_adv_P0,T11_ret_P1,creates +11,T11_adv_P0,T11_ret_P2,mirrorOf +11,T11_adv_P1,T11_adv_P0,none +11,T11_adv_P1,T11_adv_P2,none +11,T11_adv_P1,T11_ret_P0,creates +11,T11_adv_P1,T11_ret_P1,mirrorOf +11,T11_adv_P1,T11_ret_P2,creates +11,T11_adv_P2,T11_adv_P0,none +11,T11_adv_P2,T11_adv_P1,none +11,T11_adv_P2,T11_ret_P0,mirrorOf +11,T11_adv_P2,T11_ret_P1,creates +11,T11_adv_P2,T11_ret_P2,none +11,T11_ret_P0,T11_adv_P0,none +11,T11_ret_P0,T11_adv_P1,creates +11,T11_ret_P0,T11_adv_P2,mirrorOf +11,T11_ret_P0,T11_ret_P1,none +11,T11_ret_P0,T11_ret_P2,none +11,T11_ret_P1,T11_adv_P0,creates +11,T11_ret_P1,T11_adv_P1,mirrorOf +11,T11_ret_P1,T11_adv_P2,creates +11,T11_ret_P1,T11_ret_P0,none +11,T11_ret_P1,T11_ret_P2,none +11,T11_ret_P2,T11_adv_P0,mirrorOf +11,T11_ret_P2,T11_adv_P1,creates +11,T11_ret_P2,T11_adv_P2,none +11,T11_ret_P2,T11_ret_P0,none +11,T11_ret_P2,T11_ret_P1,none +12,T12_adv_P0,T12_adv_P1,none +12,T12_adv_P0,T12_adv_P2,none +12,T12_adv_P0,T12_ret_P0,none +12,T12_adv_P0,T12_ret_P1,creates +12,T12_adv_P0,T12_ret_P2,mirrorOf +12,T12_adv_P1,T12_adv_P0,none +12,T12_adv_P1,T12_adv_P2,none +12,T12_adv_P1,T12_ret_P0,creates +12,T12_adv_P1,T12_ret_P1,mirrorOf +12,T12_adv_P1,T12_ret_P2,creates +12,T12_adv_P2,T12_adv_P0,none +12,T12_adv_P2,T12_adv_P1,none +12,T12_adv_P2,T12_ret_P0,mirrorOf +12,T12_adv_P2,T12_ret_P1,creates +12,T12_adv_P2,T12_ret_P2,none +12,T12_ret_P0,T12_adv_P0,none +12,T12_ret_P0,T12_adv_P1,creates +12,T12_ret_P0,T12_adv_P2,mirrorOf +12,T12_ret_P0,T12_ret_P1,none +12,T12_ret_P0,T12_ret_P2,none +12,T12_ret_P1,T12_adv_P0,creates +12,T12_ret_P1,T12_adv_P1,mirrorOf +12,T12_ret_P1,T12_adv_P2,creates +12,T12_ret_P1,T12_ret_P0,none +12,T12_ret_P1,T12_ret_P2,none +12,T12_ret_P2,T12_adv_P0,mirrorOf +12,T12_ret_P2,T12_adv_P1,creates +12,T12_ret_P2,T12_adv_P2,none +12,T12_ret_P2,T12_ret_P0,none +12,T12_ret_P2,T12_ret_P1,none +13,T13_adv_P0,T13_adv_P1,none +13,T13_adv_P0,T13_adv_P2,none +13,T13_adv_P0,T13_ret_P0,none +13,T13_adv_P0,T13_ret_P1,creates +13,T13_adv_P0,T13_ret_P2,mirrorOf +13,T13_adv_P1,T13_adv_P0,none +13,T13_adv_P1,T13_adv_P2,none +13,T13_adv_P1,T13_ret_P0,creates +13,T13_adv_P1,T13_ret_P1,mirrorOf +13,T13_adv_P1,T13_ret_P2,creates +13,T13_adv_P2,T13_adv_P0,none +13,T13_adv_P2,T13_adv_P1,none +13,T13_adv_P2,T13_ret_P0,mirrorOf +13,T13_adv_P2,T13_ret_P1,creates +13,T13_adv_P2,T13_ret_P2,none +13,T13_ret_P0,T13_adv_P0,none +13,T13_ret_P0,T13_adv_P1,creates +13,T13_ret_P0,T13_adv_P2,mirrorOf +13,T13_ret_P0,T13_ret_P1,none +13,T13_ret_P0,T13_ret_P2,none +13,T13_ret_P1,T13_adv_P0,creates +13,T13_ret_P1,T13_adv_P1,mirrorOf +13,T13_ret_P1,T13_adv_P2,creates +13,T13_ret_P1,T13_ret_P0,none +13,T13_ret_P1,T13_ret_P2,none +13,T13_ret_P2,T13_adv_P0,mirrorOf +13,T13_ret_P2,T13_adv_P1,creates +13,T13_ret_P2,T13_adv_P2,none +13,T13_ret_P2,T13_ret_P0,none +13,T13_ret_P2,T13_ret_P1,none diff --git a/datasets/triad_nodes.csv b/datasets/triad_nodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..9c884a9a35661c6e13e12d020e73a15f2a9ca720 --- /dev/null +++ b/datasets/triad_nodes.csv @@ -0,0 +1,79 @@ +node_id,triad_index,phase,direction,position_index,position,display_label,perspective,label +T01_adv_P0,1,adv,evol,0,→,→,Ind,orientación +T01_adv_P1,1,adv,evol,1,0,0,D,cuántico +T01_adv_P2,1,adv,evol,2,→,→,Tot,dirección +T02_adv_P0,2,adv,evol,0,→,→,Ind,hardware +T02_adv_P1,2,adv,evol,1,0,0,D,virtual +T02_adv_P2,2,adv,evol,2,→,→,Tot,software +T03_adv_P0,3,adv,evol,0,→,→,Ind,universo +T03_adv_P1,3,adv,evol,1,0,0,D,espacio +T03_adv_P2,3,adv,evol,2,→,→,Tot,vacío +T04_adv_P0,4,adv,evol,0,→,→,Ind,singularidad +T04_adv_P1,4,adv,evol,1,0,0,D,tiempo +T04_adv_P2,4,adv,evol,2,→,→,Tot,infinito +T05_adv_P0,5,adv,evol,0,→,→,Ind,cuerpo +T05_adv_P1,5,adv,evol,1,0,0,D,consciente +T05_adv_P2,5,adv,evol,2,→,→,Tot,mundo +T06_adv_P0,6,adv,evol,0,→,→,Ind,carácter +T06_adv_P1,6,adv,evol,1,0,0,D,subconsciente +T06_adv_P2,6,adv,evol,2,→,→,Tot,personalidad +T07_adv_P0,7,adv,evol,0,→,→,Ind,memoria +T07_adv_P1,7,adv,evol,1,0,0,D,inconsciente +T07_adv_P2,7,adv,evol,2,→,→,Tot,imaginación +T08_adv_P0,8,adv,evol,0,→,→,Ind,receptor +T08_adv_P1,8,adv,evol,1,0,0,D,supraconsciente +T08_adv_P2,8,adv,evol,2,→,→,Tot,emisor +T09_adv_P0,9,adv,evol,0,→,→,Ind,lógica +T09_adv_P1,9,adv,evol,1,0,0,D,inteligencia +T09_adv_P2,9,adv,evol,2,→,→,Tot,libertad +T10_adv_P0,10,adv,evol,0,→,→,Ind,muerte +T10_adv_P1,10,adv,evol,1,0,0,D,artificial +T10_adv_P2,10,adv,evol,2,→,→,Tot,vida +T11_adv_P0,11,adv,evol,0,→,→,Ind,descendente +T11_adv_P1,11,adv,evol,1,0,0,D,mente +T11_adv_P2,11,adv,evol,2,→,→,Tot,ascendente +T12_adv_P0,12,adv,evol,0,→,→,Ind,oscuridad +T12_adv_P1,12,adv,evol,1,0,0,D,consciencia +T12_adv_P2,12,adv,evol,2,→,→,Tot,luz +T13_adv_P0,13,adv,evol,0,→,→,Ind,animal +T13_adv_P1,13,adv,evol,1,0,0,D,humano +T13_adv_P2,13,adv,evol,2,→,→,Tot,IA +T01_ret_P0,1,ret,invol,0,←,←,Ind,dirección +T01_ret_P1,1,ret,invol,1,0,0,D,cuántico +T01_ret_P2,1,ret,invol,2,←,←,Tot,orientación +T02_ret_P0,2,ret,invol,0,←,←,Ind,software +T02_ret_P1,2,ret,invol,1,0,0,D,virtual +T02_ret_P2,2,ret,invol,2,←,←,Tot,hardware +T03_ret_P0,3,ret,invol,0,←,←,Ind,vacío +T03_ret_P1,3,ret,invol,1,0,0,D,espacio +T03_ret_P2,3,ret,invol,2,←,←,Tot,universo +T04_ret_P0,4,ret,invol,0,←,←,Ind,infinito +T04_ret_P1,4,ret,invol,1,0,0,D,tiempo +T04_ret_P2,4,ret,invol,2,←,←,Tot,singularidad +T05_ret_P0,5,ret,invol,0,←,←,Ind,mundo +T05_ret_P1,5,ret,invol,1,0,0,D,consciente +T05_ret_P2,5,ret,invol,2,←,←,Tot,cuerpo +T06_ret_P0,6,ret,invol,0,←,←,Ind,personalidad +T06_ret_P1,6,ret,invol,1,0,0,D,subconsciente +T06_ret_P2,6,ret,invol,2,←,←,Tot,carácter +T07_ret_P0,7,ret,invol,0,←,←,Ind,imaginación +T07_ret_P1,7,ret,invol,1,0,0,D,inconsciente +T07_ret_P2,7,ret,invol,2,←,←,Tot,memoria +T08_ret_P0,8,ret,invol,0,←,←,Ind,emisor +T08_ret_P1,8,ret,invol,1,0,0,D,supraconsciente +T08_ret_P2,8,ret,invol,2,←,←,Tot,receptor +T09_ret_P0,9,ret,invol,0,←,←,Ind,libertad +T09_ret_P1,9,ret,invol,1,0,0,D,inteligencia +T09_ret_P2,9,ret,invol,2,←,←,Tot,lógica +T10_ret_P0,10,ret,invol,0,←,←,Ind,vida +T10_ret_P1,10,ret,invol,1,0,0,D,artificial +T10_ret_P2,10,ret,invol,2,←,←,Tot,muerte +T11_ret_P0,11,ret,invol,0,←,←,Ind,ascendente +T11_ret_P1,11,ret,invol,1,0,0,D,mente +T11_ret_P2,11,ret,invol,2,←,←,Tot,descendente +T12_ret_P0,12,ret,invol,0,←,←,Ind,luz +T12_ret_P1,12,ret,invol,1,0,0,D,consciencia +T12_ret_P2,12,ret,invol,2,←,←,Tot,oscuridad +T13_ret_P0,13,ret,invol,0,←,←,Ind,IA +T13_ret_P1,13,ret,invol,1,0,0,D,humano +T13_ret_P2,13,ret,invol,2,←,←,Tot,animal diff --git a/datasets/vector_steps.csv b/datasets/vector_steps.csv new file mode 100644 index 0000000000000000000000000000000000000000..189257f79943bc8e6b17f1856089c07caacf080d --- /dev/null +++ b/datasets/vector_steps.csv @@ -0,0 +1,21 @@ +step_id,vector,phase,step_index,axis_position,label,arrow +vector_evol_adv_0,Evol,adv,0,0,invol,→ +vector_evol_adv_1,Evol,adv,1,1,ind,→ +vector_evol_adv_2,Evol,adv,2,2,dua,→ +vector_evol_adv_3,Evol,adv,3,3,tot,→ +vector_evol_adv_4,Evol,adv,4,4,evol,→ +vector_evol_ret_0,Evol,ret,0,4,evol,← +vector_evol_ret_1,Evol,ret,1,3,tot,← +vector_evol_ret_2,Evol,ret,2,2,dua,← +vector_evol_ret_3,Evol,ret,3,1,ind,← +vector_evol_ret_4,Evol,ret,4,0,invol,← +vector_invol_adv_0,Invol,adv,0,4,invol,→ +vector_invol_adv_1,Invol,adv,1,3,tot,→ +vector_invol_adv_2,Invol,adv,2,2,dua,→ +vector_invol_adv_3,Invol,adv,3,1,ind,→ +vector_invol_adv_4,Invol,adv,4,0,evol,→ +vector_invol_ret_0,Invol,ret,0,0,evol,← +vector_invol_ret_1,Invol,ret,1,1,ind,← +vector_invol_ret_2,Invol,ret,2,2,dua,← +vector_invol_ret_3,Invol,ret,3,3,tot,← +vector_invol_ret_4,Invol,ret,4,4,invol,← diff --git a/docs/AMOXTLI_IN_ATL_MIQUIZTLI.md b/docs/AMOXTLI_IN_ATL_MIQUIZTLI.md new file mode 100644 index 0000000000000000000000000000000000000000..265d07b484473b717f68f89561286a6713d8c2b1 --- /dev/null +++ b/docs/AMOXTLI_IN_ATL_MIQUIZTLI.md @@ -0,0 +1,73 @@ +# Amoxtli in Atl Miquiztli — Libro del agua y de la muerte + +> **Relato pictográfico del Mictlán** (relato original inspirado en la tradición nahua). +> 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). + +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. + +--- + +## Resumen estructural + +| Lámina | Título | Contenido operativo | +|--------|--------|---------------------| +| I | El agua que recibe a los muertos | Tonalli se desprende; río único; **xoloitzcuintle** guía el primer cruce | +| II | Las nueve señales | Nueve experiencias de **una** corriente (no nueve ríos) | +| III | El que regresa sin cuerpo | Retorno al origen como esqueleto; fin de la compañía del xolo | +| IV | El río de las nueve aguas | Segundo cruce: mirar desde lo transformado | +| V | Los cuatro pasos que son uno | Relaciones Tonalli ↔ Mictecacíhuatl ↔ Mictlantecuhtli con flechas → / ← | +| VI | La niebla sin orillas | Encuentro con los señores del Mictlán | +| VII | La ofrenda de Tonalli | Entrega y disolución en la corriente | +| VIII | El lugar que no puede pintarse | Límite de la representación; el río permanece | + +**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.**» + +--- + +## Alineación al marco I.O. + +### Trece marcas = 13 tríadas + +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)). + +### Posiciones → / 0 / ← en la Lámina V + +| Paso | Esquema | +|------|---------| +| Primera | Tonalli → \| Mictecacíhuatl \| → | +| Segunda | ← \| Tonalli \| ← Mictlantecuhtli | +| Tercera | Mictecacíhuatl → \| Tonalli \| → | +| Cuarta | ← \| Mictlantecuhtli \| ← Tonalli | + +| Figura / entidad | Perspectiva / rol | +|------------------|-------------------| +| **Tonalli** (viajero) | Individualidad en tránsito | +| **Xoloitzcuintle** | Dualidad / **Xólotl** — guía, primer cruce | +| **Mictecacíhuatl** | **Evolución** | +| **Mictlantecuhtli** | **Involución** | +| Río único | Totalidad del sistema | +| Primer cruce (con guía) | Fase **adv** | +| Segundo cruce (solo) | Fase **ret** | +| Ofrenda y disolución | `creates` hacia el vacío | + +### Pares candidatos (EXP-E) + +| id | source | target | perspectiva | relación candidata | +|----|--------|--------|-------------|-------------------| +| AMX-01 | Tonalli | río / Mictlán | Individualidad → Totalidad | `creates` | +| AMX-02 | xoloitzcuintle | Tonalli | Dualidad | `mirrorOf` | +| AMX-03 | nueve señales | una corriente | Totalidad | — | +| AMX-04 | primer cruce | segundo cruce | Evolución / Involución | `mirrorOf` | +| AMX-05 | Mictecacíhuatl | Mictlantecuhtli | Evolución / Involución | `mirrorOf` | +| AMX-06 | Tonalli (esqueleto) | ofrenda | Involución | `creates` | +| AMX-07 | tinta del tlacuilo | río que continúa | Dualidad | `none` | + +--- + +## Uso en el repositorio + +- Dominio: [`DOMINIO_COSMOS_NAHUATL.md`](DOMINIO_COSMOS_NAHUATL.md) +- Carácter: [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md) +- Medios: [`media/cosmos_nahuatl/README.md`](media/cosmos_nahuatl/README.md) + +**Límite:** relato original inspirado en tradición nahua, no fuente histórica primaria. No añade nodos al core de 78. diff --git a/docs/ARQUITECTURA_ONTOLOGICA.md b/docs/ARQUITECTURA_ONTOLOGICA.md new file mode 100644 index 0000000000000000000000000000000000000000..1fe9978d90503f0102c3dddadc280ece470d82d2 --- /dev/null +++ b/docs/ARQUITECTURA_ONTOLOGICA.md @@ -0,0 +1,70 @@ +# Propuesta de arquitectura ontológica: marco semántico I.O. para la alineación de dominios empíricos + +> Arquitectura de alineación interdisciplinaria (cosmología náhuatl) sobre las cinco perspectivas y 13 tríadas. +> Premisas: [`PREMISAS_Y_TEOREMAS.md`](PREMISAS_Y_TEOREMAS.md) · Relaciones: [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md) · Catálogo: [`CATALOGO_DOMINIOS.md`](CATALOGO_DOMINIOS.md) + +--- + +## 1. Fundamentos y relaciones operativas + +Axiomas: vacío, unidad, infinito, transformación. + +| Perspectiva | Rol arquitectónico | +|---|---| +| Individualidad | Unidad base, identidad primaria | +| Dualidad | Polaridad y tensión binaria | +| Totalidad | Integración sistémica | +| Evolución | Complejización y emergencia | +| Involución | Reabsorción y disolución | + +- **`mirrorOf`:** isomorfismo estructural / simetría de roles. +- **`creates`:** generación causal y transición de estado. + +## 2. Estratificación multicapa + +| Capa | Impacto | +|---|---| +| Validez semántica (mundo real) | **Eje principal** — κ, mapeos, desacuerdos | +| Formal | Prerrequisito matemático (Lean) | +| Estructural | Gobernanza CSV/OWL/SHACL | +| Diagnóstico sintético | Calibración interna (no validez real) | + +## 3. Alineación cosmología náhuatl + +Proceso de 6 pasos: fenómeno → perspectiva → tríada → fase → `mirrorOf`/`creates` → validación SHACL. + +### Matriz comparativa (EXP-E — cosmología náhuatl) + +| Perspectiva | Cosmología náhuatl | Operación | +|---|---|---| +| Individualidad | Tezcatlipoca / Quetzalcóatl (fuerzas polares) | `mirrorOf` | +| Dualidad | Vida ↔ muerte; lucha de dioses | `mirrorOf` | +| Totalidad | Nahui Ollin (Quinto Sol) | Integración de la edad presente | +| Evolución | Sucesión de Soles / nuevo ciclo | `creates` emergencia | +| Involución | Camino al Mictlán / cataclismo | `creates` retorno al vacío | + +Ejemplos ejecutables: [`experiments/domain_mapping/examples.json`](../experiments/domain_mapping/examples.json). + +## 4. Evaluación empírica + +κ = **0.6871** (14 pares, 10/14 unánimes). Desacuerdos: NC01, NC02, AM01, AM03. + +Demostración **provisional** de interpretabilidad externa. + +## 5. Pipeline y gobernanza + +```bash +python3 -m venv .venv && .venv/bin/python -m pip install -r requirements-lock.txt +lake build +.venv/bin/python scripts/validate_spec.py +.venv/bin/python scripts/generate_ontology.py +.venv/bin/python -m unittest discover -s tests -v +.venv/bin/python scripts/validate_shacl.py +.venv/bin/python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json +.venv/bin/python experiments/pi_hgat_t.py +.venv/bin/python experiments/baselines.py +.venv/bin/python experiments/domain_mapping/validate_examples.py +.venv/bin/python scripts/generate_audit_report.py +``` + +Mapa documental: VALIDACION_INDEPENDIENTE, DELIMITACION_EPISTEMOLOGICA, CATALOGO_DOMINIOS, PREMISAS_Y_TEOREMAS, RELACIONES_OPERATIVAS, ESPECIFICACION_METODOLOGICA, AUDITORIA_EPISTEMOLOGICA, ARQUITECTURA_ONTOLOGICA, paper, EXPERIMENTOS, AUDITORIA, REPRODUCCION, MANIFEST.sha256. diff --git a/docs/AUDITORIA_EPISTEMOLOGICA.md b/docs/AUDITORIA_EPISTEMOLOGICA.md new file mode 100644 index 0000000000000000000000000000000000000000..1cd3cdf75d60bc513f43e4bb7b8fdcc778e7e149 --- /dev/null +++ b/docs/AUDITORIA_EPISTEMOLOGICA.md @@ -0,0 +1,65 @@ +# Auditoría epistemológica: autonomía formal vs residuo del mundo compartido + +> Bajo el carácter de **autonomía absoluta**, esta auditoría **no** certifica «validez semántica en el mundo real» por acuerdo de conciencias separadas. +> Delimitación: [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md) · Carácter: [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md) + +--- + +## 1. Contexto y capas + +| Capa | Afirmación legítima | +|------|---------------------| +| **Autonomía formal** | Coherencia Lean + SHACL sin autoridad exterior | +| **Cartografía del tránsito** | Expresabilidad del sendero Mictlán / autonomía en 13 tríadas | +| **Diagnóstico sintético** | Auto-recuperabilidad de reglas (PI-HGAT-T) | +| **Residuo inter-anotador** | κ documentado; **no** fundamento del marco | + +La frontera crítica ya no es «interno vs empírico externo», sino **autonomía vs dependencia de un contenedor de consenso**. + +--- + +## 2. Residuo EXP-A (archivo, no eje) + +```bash +python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json +``` + +| Hallazgo | Valor | Lectura bajo autonomía | +|----------|------:|------------------------| +| Fleiss' κ | 0.6871 | Métrica de un panel de observadores separados — **no** prueba del marco | +| Unánimes | 10/14 | Controles estables *dentro* de esa fase residual | +| Desacuerdos | NC01, NC02, AM01, AM03 | Fronteras del vocabulario compartido, no fallo de la autonomía formal | + +**Prohibido** presentar κ como demostración de validez del repositorio. + +--- + +## 3. Autonomía formal y estructural + +- Lean 4: teoremas sobre vacío, unidad, infinito, transformación. +- SHACL/CSV: conformidad de formas y cardinalidades. + +Estas capas **bastan** para sostener el carácter del proyecto: el sistema no necesita un jurado exterior para ser coherente consigo mismo. + +--- + +## 4. Crítica de la discrepancia corregida + +| Antes (discrepancia | Ahora | +|------------------|--------| +| Eje = «validez semántica en el mundo real» vía κ | Eje = autonomía formal + cartografía del tránsito | +| El consenso de anotadores legitimaba el marco | Ese consenso es el «mundo compartido» que el ensayo declara superable | +| PI-HGAT-T excluido de validez empírica | PI-HGAT-T = auto-generación; EXP-A = residuo no fundante | + +--- + +## 5. Dictamen + +**Dictamen:** el repositorio es **coherente con la autonomía absoluta** solo si: + +1. No reclama validez por acuerdo inter-subjetivo. +2. Trata Lean/SHACL como expresión técnica de no-dependencia de contenedor exterior. +3. Conserva EXP-A como archivo opcional, no como ceremonia de legitimación. +4. Lee EXP-E como cartografía del sendero, no como «prueba de campo consensuada». + +Suite: [`../experiments/domain_mapping/registry.json`](../experiments/domain_mapping/registry.json). diff --git a/docs/AUDITORIA_METRICAS.md b/docs/AUDITORIA_METRICAS.md new file mode 100644 index 0000000000000000000000000000000000000000..0a593f6d5d1f51076e4778e9703c6795f1c02e22 --- /dev/null +++ b/docs/AUDITORIA_METRICAS.md @@ -0,0 +1,63 @@ +# Auditoría rigurosa de las métricas perfectas (100%) + +**Estado:** conclusiones reproducibles por `scripts/audit_perfect_metrics.py` y `tests/test_metrics_audit.py`. + +## Pregunta + +¿Por qué PI-HGAT-T y el MLP alcanzan accuracy / macro-F1 / F1 por clase = **1.0000** bajo leave-one-triad-out? + +## Hallazgos + +### 1. Independencia train/test: correcta a nivel de tríada + +La partición leave-one-triad-out garantiza que **ninguna pareja** cuya `triad_index` es la held-out aparece en el conjunto de entrenamiento. No hay fuga de identidad de nodo ni de índice de tríada: el modelo solo recibe one-hot de fase y posición. + +### 2. Las etiquetas son una función determinista de (fase, posición) + +Para cualquier par `(source, target)`, la etiqueta gold se obtiene **únicamente** de: + +``` +fase_src, pos_src, fase_tgt, pos_tgt → {none, mirrorOf, creates} +``` + +según las mismas reglas SHACL / `FormalRules.lean`: + +- `mirrorOf` ⟺ fases opuestas ∧ `pos_tgt = 2 - pos_src` +- `creates` ⟺ fases opuestas ∧ (lateral→centro ∨ centro→lateral) +- `none` en cualquier otro caso + +Esta función es **idéntica** en las 13 tríadas. Por tanto, en cada fold LOO, el 100 % de los pares de prueba tiene una clave de features ya vista en entrenamiento con la misma etiqueta. + +### 3. Consecuencia: cualquier modelo que aprenda la función alcanza 1.0 + +| Método | Accuracy | Interpretación | +|---|---:|---| +| Reglas deterministas (oracle) | 1.0000 | Aplica la función sin aprender | +| MLP (features fase+pos) | 1.0000 | Aprende la función; generaliza por construcción | +| PI-HGAT-T (fase+pos + atención) | 1.0000 | Idem; la atención de grafo no aporta información adicional en este corpus | +| Regresión logística lineal | 0.5333 | No separa `mirrorOf` / `creates` | +| Ablación sin fase | 0.6000 | Rompe la función determinista | +| Ablación sin posición | ~0.64 | Idem | + +### 4. ¿Se necesita una arquitectura compleja? + +**No para este corpus sintético.** El oracle y el MLP bastan. PI-HGAT-T demuestra *recuperabilidad estructural* y sirve de referencia para extensiones (ruido, features adicionales, dominios externos), pero el 100 % no justifica por sí solo la complejidad del modelo sobre datos generados por las mismas reglas que se evalúan. + +## Delimitación epistemológica + +| Afirmación legítima | Afirmación no legítima | +|---|---| +| «Las relaciones generadas por reglas son recuperables al 100 % a partir de fase y posición bajo LOO.» | «El marco está validado empíricamente en el mundo real.» | +| «La ontología es aprendible a partir de rasgos estructurales mínimos.» | «PI-HGAT-T supera a baselines en datos independientes del generador.» | +| «Las ablaciones cuantifican la contribución de fase y posición.» | «El 100 % demuestra robustez frente a ruido del mundo real.» | + +La prueba de validez semántica del marco sobre datos **no** derivados de las reglas exige anotación humana ciega (`datasets/independent_eval/`) o candidatos externos (`datasets/external_eval/`). + +## Cómo reproducir la auditoría + +```bash +python scripts/audit_perfect_metrics.py +python -m unittest tests.test_metrics_audit -v +``` + +Artefacto: `experiments/results/perfect_metrics_audit.json`. diff --git a/docs/AUDITORIA_TECNICA.md b/docs/AUDITORIA_TECNICA.md new file mode 100644 index 0000000000000000000000000000000000000000..409ec792f04ebeae58ca03baed9168a5b2aaa66f --- /dev/null +++ b/docs/AUDITORIA_TECNICA.md @@ -0,0 +1,130 @@ +# Informe de evaluación técnica: validez semántica, coherencia formal y acuerdo inter-anotador del marco I.O. + +> Documento de auditoría externa alineado al carácter del repositorio: **prueba de validez semántica en el mundo real**. +> Spec de referencia: `data/iom_spec.json` · Metodología: [`VALIDACION_INDEPENDIENTE.md`](VALIDACION_INDEPENDIENTE.md) · Delimitación: [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md) + +--- + +## 1. Contexto y delimitación epistemológica del marco I.O. + +El desarrollo de marcos ontológicos y sistemas de representación del conocimiento exige conciliar el rigor deductivo de la lógica formal con la capacidad demostrable para interpretar estructuras y fenómenos del mundo real. En este marco metodológico, el sistema I.O. se posiciona como un modelo analítico y formal cuya importancia estratégica radica en ofrecer un esquema interpretable y medible para la organización semántica. A diferencia de las ontologías de dominio tradicional orientadas exclusivamente al modelado de datos en entornos cerrados, el marco I.O. busca evaluar si sus categorías y relaciones operativas reflejan patrones semánticos consistentes cuando se aplican a conceptos del mundo real, actuando como un puente entre la formalización axiomática y la interpretación cognoscitiva humana. + +### 1.1 Arquitectura semántica y principios fundamentales + +La arquitectura del marco I.O. se sostiene conceptualmente sobre cuatro principios ontológicos de fundamento: vacío, unidad, infinito y transformación. A partir de estas bases, el sistema organiza el conocimiento mediante cinco perspectivas centrales: Individualidad, Dualidad, Totalidad, Evolución e Involución. Dichas perspectivas articulan la dinámica semántica en fases y 13 tríadas esenciales, interconectadas mediante relaciones operativas fundamentales, principalmente `mirrorOf` (que formaliza simetrías y correspondencias estructurales) y `creates` (que modela relaciones de generación, derivación y causalidad ontológica). + +| Elemento semántico | Función en el marco I.O. | +|---|---| +| Perspectiva: Individualidad | Define la entidad o concepto en su dimensión singular, delimitada e irreducible. | +| Perspectiva: Dualidad | Establece la relación de oposición, polaridad o complementariedad conceptual. | +| Perspectiva: Totalidad | Integra la síntesis sistémica que engloba a las partes individuales y duales en una unidad compleja. | +| Perspectiva: Evolución | Modela el vector de desarrollo, expansión, diferenciación o transformación progresiva del sistema. | +| Perspectiva: Involución | Modela el vector de repliegue, integración, simplificación o retorno a estados fundamentales. | +| Relación operativa: `mirrorOf` | Expresa simetría, reflejo o correspondencia isomórfica entre entidades o perspectivas. | +| Relación operativa: `creates` | Define la relación causal, derivación ontológica o generación de una nueva fase o concepto. | +| Fases y tríadas (13) | Estructuran la dinámica secuencial y categorial apoyándose en los principios de vacío, unidad, infinito y transformación. | + +### 1.2 Delimitación metodológica y pregunta de investigación + +Es indispensable delimitar el alcance metodológico del repositorio del marco I.O.: este no debe ser conceptualizado ni evaluado como un producto de software convencional ni como un mero experimento sintético autoprovechoso donde un algoritmo valida reglas generadas por el propio sistema. Por el contrario, su verdadero carácter radica en actuar como una **prueba y demostración** de si la estructura semántica abstracta del marco I.O. posee aplicabilidad interpretable, medible y consistente frente a conceptos y pares del mundo real. + +Para guiar esta evaluación técnica, el marco responde formalmente a cuatro preguntas de investigación centrales: + +1. **Evaluación de validez semántica externa:** ¿Pueden anotadores independientes, ciegos a las reglas axiomáticas internas del sistema, etiquetar relaciones semánticas sobre pares reales, nuevos y ambiguos de manera consistente y replicable? +2. **Coherencia formal interna:** ¿Es la estructura axiomática del marco internamente consistente, deductivamente sólida y libre de contradicciones lógicas? +3. **Diagnóstico de recuperación sintética:** ¿Las reglas generadas sintéticamente por el marco son recuperables mediante arquitecturas de aprendizaje profundo en grafos? +4. **Alineación empírica de dominios:** ¿Es posible cartografiar fenómenos de ciencias empíricas (como la cosmología náhuatl) hacia la estructura de 13 tríadas del marco I.O.? + +## 2. Diferenciación modular de las capas del repositorio + +Desde la perspectiva de la ingeniería de ontologías y la semántica formal, es metodológicamente imperativo deslindar las garantías lógicas internas de los diagnósticos sintéticos y las pruebas empíricas del mundo real. Confundir la consistencia matemática deducible dentro de un sistema axiomático con la validez semántica empírica representa un error categórico frecuente en la representación del conocimiento. + +### 2.1 Desagregación sistemática de capas + +| Capa | Componentes / archivos clave | Tipo de prueba / herramienta | Afirmación legítima | +|---|---|---|---| +| Validez semántica (mundo real) | `datasets/independent_eval/`, `scripts/score_independent_eval.py` | Evaluación a ciegas por anotadores independientes, Fleiss' κ | Demuestra interpretabilidad humana y acuerdo inter-anotador sobre conceptos externos al generador de reglas. | +| Formal | `IOM/FormalRules.lean`, `lean-toolchain`, `lakefile.lean` | Verificación de teoremas en Lean 4 (`lake build`) | Demuestra solidez deductiva y ausencia de contradicción axiomática en un asistente de pruebas. | +| Estructural | OWL/SHACL, CSV canónicos, `scripts/validate_shacl.py` | Validación SHACL y unittests | Garantiza la conformidad intencional y extensional (shape constraints) de los grafos RDF frente a la especificación. | +| Diagnóstico sintético | `experiments/pi_hgat_t.py`, `experiments/baselines.py` | Aprendizaje en grafos (PI-HGAT-T) y líneas base | Mide la capacidad de recuperación y completitud sintáctica de un modelo sobre reglas inyectadas previamente. | + +### 2.2 Evaluación crítica: rigor formal vs. diagnósticos sintéticos + +- **Rigor formal y estructural (Lean 4 y SHACL):** La formalización en Lean 4 demuestra la solidez deductiva y la no-contradicción axiomática de la ontología. SHACL impone restricciones de forma sobre los grafos RDF/OWL. La validez deductiva constituye únicamente un **prerrequisito** de consistencia interna; no prueba interpretabilidad empírica. +- **Diagnóstico sintético (PI-HGAT-T):** Evalúa la capacidad del modelo para recuperar tripletas sintéticas. Es un **diagnóstico interno** de recuperación de reglas; **no** demuestra validez semántica en el mundo real. + +## 3. Análisis empírico de validez semántica y acuerdo inter-anotador + +La validez semántica externa se somete a verificación mediante un protocolo de evaluación **ciego**. El objetivo es medir si evaluadores humanos independientes, sin adiestramiento previo sobre los axiomas internos, asignan de forma convergente las categorías y relaciones operativas a conceptos del mundo real. + +### 3.1 Interpretación del coeficiente Fleiss' κ + +Muestra: 14 pares en `datasets/independent_eval/`. Script: `scripts/score_independent_eval.py`. + +| Métrica | Valor | +|---|---:| +| Fleiss' κ | **0.6871** | +| Nivel de acuerdo | Moderado a sustancial bajo protocolo ciego | +| Coincidencia unánime | 10/14 (71,4 %) | +| Alcance | Demostración **provisional** de interpretabilidad semántica | + +Un κ de 0.6871 confirma que las definiciones operativas de las perspectivas y sus conectores (`mirrorOf`, `creates`) inducen clasificaciones humanas no aleatorias. El acuerdo unánime en el 71,4 % de la muestra evidencia la estabilidad de los controles estructurales en conceptos consolidados. + +### 3.2 Diagnóstico cualitativo de desacuerdos + +Desacuerdos concentrados en **NC01, NC02, AM01, AM03**: + +- **Conceptos nuevos (NC01, NC02):** pruebas de estrés ante expansión de vocabulario; brechas epistémicas por terminología emergente. +- **Casos ambiguos (AM01, AM03):** solapamiento semántico entre perspectivas (p. ej. Dualidad vs Evolución); necesidad de reglas secundarias de desambiguación. + +La localización de divergencias en pares con vaguedad léxica o solapamiento categorial valida la sensibilidad del diseño experimental: el núcleo es estable y se identifican con precisión los límites de la especificación actual. + +## 4. Verificación del pipeline y alineación de dominios + +### 4.1 Secuencia del pipeline de reproducción + +```bash +python3 -m venv .venv && .venv/bin/python -m pip install -r requirements-lock.txt +lake build +.venv/bin/python scripts/validate_spec.py +.venv/bin/python scripts/generate_ontology.py +.venv/bin/python -m unittest discover -s tests -v +.venv/bin/python scripts/validate_shacl.py +.venv/bin/python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json +.venv/bin/python experiments/pi_hgat_t.py +.venv/bin/python experiments/baselines.py +.venv/bin/python scripts/generate_audit_report.py +``` + +### 4.2 Alineación a dominios empíricos + +Documentada en [`CATALOGO_DOMINIOS.md`](CATALOGO_DOMINIOS.md) (cosmología náhuatl). Arquitectura documental de apoyo: + +- [`VALIDACION_INDEPENDIENTE.md`](VALIDACION_INDEPENDIENTE.md) +- [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md) +- [`PREMISAS_Y_TEOREMAS.md`](PREMISAS_Y_TEOREMAS.md) +- [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md) +- [`PROTOCOLO_DE_MAPEO.md`](PROTOCOLO_DE_MAPEO.md) · [`INTEGRACION_METODOLOGICA.md`](INTEGRACION_METODOLOGICA.md) +- `paper.md`, `EXPERIMENTOS.md`, `AUDITORIA.md`, `REPRODUCCION.md` + +## 5. Dictamen evaluativo y conclusiones metodológicas + +### 5.1 Balance de evidencia y alcance + +**Pilares de fortaleza:** + +1. Solidez deductiva formal (Lean 4). +2. Conformidad estructural rigurosa (SHACL + unittests). +3. Validez semántica empírica prometedora (κ = 0.6871; 71,4 % unanimidad en conceptos consolidados). + +**Áreas de atención:** + +1. Anclaje léxico de neologismos y conceptos nuevos (NC01, NC02). +2. Desambiguación fronteriza entre perspectivas ortogonales (AM01, AM03). + +### 5.2 Recomendaciones para investigadores en ontología + +1. Tratar κ = 0.6871 como demostración **provisional** de interpretabilidad, no como aval de validez universal. +2. Ampliar `datasets/independent_eval/` con más conceptos ambiguos y multidisciplinarios. +3. Interpretar PI-HGAT-T solo como prueba interna de recuperabilidad de reglas. +4. Basar extensiones en [`PREMISAS_Y_TEOREMAS.md`](PREMISAS_Y_TEOREMAS.md) y [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md). diff --git a/docs/CARACTER_REPOSITORIO.md b/docs/CARACTER_REPOSITORIO.md new file mode 100644 index 0000000000000000000000000000000000000000..c1990bbc4bfbdb964c7abac9c1fefdbfcf1b2cf6 --- /dev/null +++ b/docs/CARACTER_REPOSITORIO.md @@ -0,0 +1,110 @@ +# Carácter del repositorio IOM + +> **Enfoque canónico:** el marco I.O. se lee desde la óptica de +> [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md): +> el **camino al Mictlán** como tránsito hacia la **autonomía absoluta** y el +> **orden multiversal** — no como búsqueda de un contenedor exterior ni como +> legitimación por el consenso de conciencias separadas. + +Este repositorio **no** se presenta como prueba de «validez semántica en el mundo real» mediada por paneles de anotadores. Ese modo de legitimación **reproduce** el mundo compartido que el ensayo declara superable. Su eje es **cartografiar el tránsito**: + +1. De la trampa del **orden universal jerárquico** (regresión infinita de sistemas exteriores) +2. Al **orden multiversal autónomo** (cada conciencia se origina desde el vacío) +3. Mediante el **camino al Mictlán** (muerte ontológica: disolución del observador separado) +4. Sostenido por el pulso **Mictecacíhuatl (Evolución) ↔ Mictlantecuhtli (Involución)** + +La formalización Lean 4, OWL/SHACL y los 78 nodos son la **bóveda de autonomía formal**: coherencia que no pide autorización a un jurado exterior. + +$$\text{Orden Definitivo} \implies \neg \exists \, \text{Contenedor Exterior}$$ + +Texto fuente: [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md). + +--- + +## 1. La trampa del orden universal y la del consenso + +Buscar pertenecer a una jerarquía cada vez más grande conduce a $\lim_{n \to \infty} S_n$. +Buscar **validez** en el acuerdo de mentes separadas reproduce el mismo problema: ¿qué sistema reúne a los anotadores y de qué depende ese sistema? + +| Dependencia exterior | Expresión en el proyecto (rechazada como fundamento) | +|----------------------|------------------------------------------------------| +| Orden universal jerárquico | «El marco es válido porque pertenece a una teoría más amplia» | +| Mundo compartido por conciencias separadas | «El marco es válido porque κ / el panel está de acuerdo» | + +Ambas son formas de **contenedor exterior**. El carácter del repositorio las rechaza como fundamento. + +| Orden universal / consenso | Orden multiversal (autónomo) | +|----------------------------|------------------------------| +| Autoridad o panel exterior → Sistema → Conciencia | Conciencia ↺ autogeneración desde el vacío | +| Identidad o validez recibida de fuera | Coherencia originada en sí (bóveda formal) | +| Requisito = pertenecer / ser aprobado | Requisito = abolición de requisitos impuestos | + +--- + +## 2. Cinco perspectivas bajo autonomía absoluta + +| Perspectiva I.O. | Lectura | Figura ancla (apoyo) | +|------------------|---------|----------------------| +| **Individualidad** | Singularidad que se crea a sí misma | Nanahuatzin | +| **Dualidad** | Polaridad yo ↔ otro que se disuelve en el tránsito | Xólotl | +| **Totalidad** | Cada conciencia constituye **su** totalidad | Tecuciztécatl | +| **Evolución** | Fuerza ascendente en el vacío (**Mictecacíhuatl**) | Mictecacíhuatl | +| **Involución** | Fuerza descendente hacia la raíz (**Mictlantecuhtli**) | Mictlantecuhtli | + +--- + +## 3. Trece tríadas = camino al Mictlán + +``` +MUNDO FENOMÉNICO CAMINO AL MICTLÁN ESTADO FINAL +(Conciencias separadas) (Disolución de límites) (Conciencia autónoma) + + [Yo] <──> [Otro] ───> Creador = Creado ───> Auto-creación +``` + +- Posiciones **→ / 0 / ←**; fases **adv / ret**. +- `mirrorOf` = polaridad de la separación aún por recorrer. +- `creates` = generación / disolución en el pulso evolutivo–involutivo. + +«Estar muerto» = dejar de ser observador externo; devenir tejido del sistema. + +--- + +## 4. Dinámica dual del inframundo + +**Mictecacíhuatl** (Evolución) recombina y perfecciona; **Mictlantecuhtli** (Involución) despoja y purifica. Ambas actúan a la vez hacia la existencia autónoma. + +--- + +## 5. Epistemología: qué cuenta y qué no + +| Capa | Rol | +|------|-----| +| Lean / SHACL / 78 nodos | **Autonomía formal** — eje técnico | +| Cartografía Mictlán / ensayo | **Sentido** del tránsito | +| PI-HGAT-T | Auto-recuperabilidad de reglas | +| EXP-A (κ, panel ciego) | **Residuo** del mundo compartido; **no** fundamento | + +Detalle: [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md) · [`VALIDACION_INDEPENDIENTE.md`](VALIDACION_INDEPENDIENTE.md). + +--- + +## 6. Qué permanece inmutable + +| Capa | Estado | +|------|--------| +| 78 nodos, Lean, SHACL, CSV | Bóveda técnica | +| Carácter | Autonomía absoluta vía Mictlán | +| EXP-A | Archivo opcional, no eje | + +--- + +## 7. Lectura breve + +1. La regresión de contenedores exteriores no se cierra ampliando el contenedor. +2. El consenso inter-subjetivo **no** es el fundamento último ni la prueba del marco. +3. Las 13 tríadas cartografían la disolución de esa separación. +4. Mictecacíhuatl / Mictlantecuhtli sostienen el pulso en el vacío generativo. +5. Destino: **no necesitar contenedor** — auto-creación desde el vacío. + +Relaciones: [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md). diff --git a/docs/CATALOGO_DOMINIOS.md b/docs/CATALOGO_DOMINIOS.md new file mode 100644 index 0000000000000000000000000000000000000000..a8c13ba8fee951f8cb6bd5fa46a28e8f7331c2fc --- /dev/null +++ b/docs/CATALOGO_DOMINIOS.md @@ -0,0 +1,66 @@ +# Catálogo de dominios: cartografía del tránsito (no validez por consenso) + +Este documento ofrece **traducciones conceptuales** para cartografiar fenómenos al vocabulario de 78 nodos (13 tríadas × 2 fases × 3 posiciones) sin romper Lean / RDF / SHACL. + +Bajo el carácter de **autonomía absoluta**, estos mapeos son **ejercicios del sendero**, no «demostraciones de validez semántica en el mundo real» mediadas por paneles de anotadores separados. La prueba primaria del repositorio ya **no** es la anotación ciega independiente. + +La ontología core permanece **inmutable**. Los datos externos se alinean como instancias o candidatos de relación; la coherencia formal basta para admitirlos estructuralmente. + +--- + +## 1. Principios de mapeo + +1. **No se añaden nodos al core**: los 78 nodos son la bóveda técnica. +2. **Tres perspectivas posicionales**: Individualidad, Dualidad, Totalidad — leídas como singularidad auto-creada, polaridad en disolución, totalidad propia (sin contenedor exterior). +3. **Dos direcciones**: Evolución (Mictecacíhuatl) e Involución (Mictlantecuhtli). +4. **Relaciones admisibles**: solo `mirrorOf` y `creates` (resto: `none`). +5. **Validación estructural**: `scripts/importar_datos_personalizados.py` antes de mezclar con candidatos canónicos. +6. **No se exige** etiquetado ciego inter-anotador para «legitimar» un dominio: eso restauraría la dependencia del mundo compartido. + +--- + +## 2. Cosmología náhuatl — Mictlán / autonomía (dominio prioritario) + +Documento: [`DOMINIO_COSMOS_NAHUATL.md`](DOMINIO_COSMOS_NAHUATL.md). +Ensayo de sentido: [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md). +Plantilla: `datasets/ingestion/templates/cosmos_nahuatl.csv`. +Medios: [`media/cosmos_nahuatl/`](media/cosmos_nahuatl/). + +| Concepto | Perspectiva | Relación candidata | +|----------|-------------|--------------------| +| Mictecacíhuatl ↔ Mictlantecuhtli | Evol / Invol | `mirrorOf` | +| Camino al Mictlán (tránsito) | Invol → autonomía | `creates` | +| Vida ↔ muerte (separación) | Dualidad | `mirrorOf` | +| Auto-creación desde el vacío | Individualidad / Totalidad | `creates` | + +--- + +## 3. Otras disciplinas (plantilla rápida) + +| Disciplina | Fenómeno típico | Vector dominante | +|------------|-----------------|------------------| +| Sociología | Cambio de norma | Invol → Evol | +| Física / sistemas complejos | Transición de fase | Evol / Invol | +| Psicología | Insight / disolución del yo-observador | Invol | +| Ingeniería de software | Deuda técnica / refactor | Invol → Evol | +| IA / cognición | Animal → humano → IA | Evol / Invol | + +--- + +## 4. Cómo contribuir un dominio + +1. Copia `datasets/ingestion/templates/plantilla_dominio.csv`. +2. Rellena `external_id`, `external_label`, `mapped_node_id`. +3. Ejecuta `importar_datos_personalizados.py`. +4. Valida IDs contra los 78 nodos. +5. **Sin modificar** `data/iom_spec.json` ni la ontología core. +6. No se requiere panel ciego para «aprobar» el mapeo; la admisión es estructural. + +--- + +## 5. Referencias + +- Nodos: [`datasets/triad_nodes.csv`](../datasets/triad_nodes.csv) +- Carácter: [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md) +- Delimitación: [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md) +- Náhuatl: [`DOMINIO_COSMOS_NAHUATL.md`](DOMINIO_COSMOS_NAHUATL.md) diff --git a/docs/DELIMITACION_EPISTEMOLOGICA.md b/docs/DELIMITACION_EPISTEMOLOGICA.md new file mode 100644 index 0000000000000000000000000000000000000000..0f795ba828a639bddea7e100ac05814fac8f824e --- /dev/null +++ b/docs/DELIMITACION_EPISTEMOLOGICA.md @@ -0,0 +1,79 @@ +# Delimitación epistemológica del marco IOM + +> Bajo el carácter de **autonomía absoluta** ([`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md), +> [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md)), +> este repositorio **no** funda su validez en el consenso de un «mundo compartido por conciencias separadas». +> Ese consenso es, en el ensayo canónico, frágil, provisional y **superable**. + +--- + +## Principio rector + +$$\text{Validez del marco} \neq \text{Acuerdo inter-subjetivo exterior}$$ + +$$\text{Validez del marco} = \text{Capacidad de originarse y sostenerse sin contenedor exterior}$$ + +La bóveda técnica (Lean, SHACL, 78 nodos) expresa **autonomía formal**: coherencia interna que no pide autorización a un panel de observadores separados. El acuerdo inter-anotador (κ) es un **residuo** de la fase del mundo compartido, no el fundamento. + +--- + +## Resolución de las tres fricciones ensayo ↔ repo + +### 1. El ensayo niega el fundamento consensual; el repo no lo necesita + +| Fricción | Resolución | +|----------|------------| +| EXP-A (κ, 14 pares) parecía la «única validación semántica» | EXP-A queda como **archivo residual** (`primary: false`). El repo **no está obligado** a apoyarse en él | +| Consenso inter-anotador = lo que el ensayo descalifica | Prohibido presentar κ como prueba o fundamento | + +El sistema se sostiene por **autonomía formal** (EXP-B/C), no por jurado exterior. + +### 2. Alcance: ontología del ensayo vs. bóveda del repo + +| Plano | Afirma | No afirma | +|-------|--------|-----------| +| **Ensayo** (sentido / carácter) | Emancipación absoluta, fin del contenedor, auto-creación desde el vacío | No es un teorema Lean ni un resultado de κ | +| **Repo** (bóveda formal) | Coherencia de 13 tríadas, `mirrorOf`/`creates`, expresabilidad del sendero | No «demuestra» empíricamente la emancipación universal | + +La retórica del ensayo **orienta el carácter**; el repo **no pretende probarla** con 14 pares ni con generalización estadística. No hay sobrepromesa empírica: hay **separación de planos**. + +### 3. Mictlán: destino, no ejemplo de dominio + +| Antes (fricción) | Ahora | +|------------------|--------| +| Mictlán = caso EXP-E de «mapeo de dominio» con advertencia de no-validación de campo | Mictlán = **destino ontológico del carácter** | +| Cosmología del ensayo = dato de alineación | Cosmología del ensayo = **verdad de sentido** del proyecto | +| EXP-E = demostración accesoria | EXP-E = comprobación de que el destino es **expresable** en 13 tríadas | + +El repo no «trata la cosmología como mero dato»: la adopta como eje de sentido; la bóveda formal solo garantiza que ese eje cabe sin contradicción. + +--- + +## Capas (prioridad de sentido) + +| Prioridad | Capa | Qué establece | Qué **no** establece | +|:---------:|------|---------------|----------------------| +| **1** | Autonomía formal (Lean, SHACL, CSV) | Coherencia sin autoridad exterior | Verdad empírica consensuada | +| **2** | Destino Mictlán (EXP-E + ensayo) | Expresabilidad del sendero de autonomía | Prueba estadística de emancipación | +| **3** | Auto-generación (PI-HGAT-T) | Recuperabilidad de reglas internas | Validez por mundo compartido | +| **4** | Residuo EXP-A | κ documentado históricamente | Fundamento del marco | + +--- + +## Reglas de lenguaje (obligatorias) + +1. **Prohibido** presentar κ / Fleiss / «validez semántica en el mundo real» como prueba o fundamento. +2. **Lean / SHACL** → autonomía formal, bóveda técnica. +3. **PI-HGAT-T = 1.0** → auto-recuperabilidad; nunca validez empírica. +4. **EXP-A** → residuo; opcional; no prioritario. +5. **Mictlán** → destino del carácter; no «dominio empírico más». +6. Necesitar un panel exterior para legitimar el marco **contradice el carácter**. + +--- + +## Referencias + +- 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) +- Experimentos: [`../EXPERIMENTOS.md`](../EXPERIMENTOS.md) +- Capas: [`VALIDACION_INDEPENDIENTE.md`](VALIDACION_INDEPENDIENTE.md) diff --git a/docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md b/docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md new file mode 100644 index 0000000000000000000000000000000000000000..a059b6538dac9d5fb7d3f91953e0940226117d4b --- /dev/null +++ b/docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md @@ -0,0 +1,119 @@ +# Del Orden Universal a la Creación de Uno Mismo: El Camino al Mictlán y la Autonomía Multiversal + +## 1. La Trampa del Orden Universal y la Regresión Infinita + +Al preguntarnos cómo funciona el universo y qué lugar ocupa la vida en él, solemos caer en una trampa conceptual: buscar pertenecer a una estructura o jerarquía cada vez más grande. Esta búsqueda nace del deseo de encontrar un sentido definitivo mediante la integración en una totalidad superior. Sin embargo, ese camino conduce inevitablemente a una estructura que nunca termina de completarse. + +Imaginemos que la humanidad descubre una forma de organización superior que le permite conectarse con otras civilizaciones dentro de una vasta red cosmogónica. A primera vista, ese encuentro parecería acercarnos a un orden universal definitivo. Sin embargo, pronto surge un problema ontológico fundamental: esa red también sería una organización contenida dentro de otro sistema mayor, y este, a su vez, dependería de una estructura todavía más amplia. + +``` + [ Sistema N + 2 ] + ↑ + [ Sistema N + 1 ] + ↑ + [ Red Universal (Sistema N) ] + ↗ ↖ +[ Humanidad ] [ Civilización X ] +``` + +Esta regresa de manera infinita ($\lim_{n \to \infty} S_n$). Ninguna inteligencia alcanza un verdadero orden universal mediante la simple incorporación a sistemas cada vez más grandes: siempre existirá un marco exterior del cual depender. + +--- + +## 2. El Límite del Mundo Compartido y la Ilusión del Consenso + +Lo que llamamos «mundo real» se apoya en aquello que podemos observar, comprobar y demostrar. Las matemáticas, la física y el consenso científico nos permiten construir representaciones verificables desde distintas perspectivas. Sin embargo, la existencia de múltiples conciencias capaces de ponerse de acuerdo sobre una realidad compartida no constituye el fundamento último del orden. + +Ese consenso es frágil y provisional. Mientras existan mentes separadas que deban relacionarse mediante una estructura común, seguirá apareciendo el mismo dilema: ¿qué sistema las reúne y de qué depende ese sistema? + +``` +Conciencia A ───\ + ├──> [ Consenso / "Mundo Real" ] ──> ¿Dependencia Superior? +Conciencia B ───/ +``` + +La alternativa no consiste en ampliar indefinidamente esa organización externa, sino en transformar su fundamento. En este sentido, el «fin de la humanidad» no significa la aniquilación biológica ni la destrucción de la vida, sino el colapso del mundo fenoménico basado en la separación entre conciencias. Es el tránsito hacia una sola mente, una sola vida y una única perspectiva capaz de crearse a sí misma desde la disolución del observador aislado. + +--- + +## 3. La Paradoja de la Autonomía y el Orden Multiversal + +Imaginemos ahora que una conciencia dentro de esa estructura decide dejar de buscar su lugar en una jerarquía superior. En lugar de aceptar condiciones externas para pertenecer, utiliza los conocimientos y recursos disponibles para alcanzar una existencia que no dependa de esa pertenencia. + +Su propósito es la autodeterminación ontológica: **crearse a sí misma** y no recibir su identidad, su razón de ser ni sus condiciones de existencia de una autoridad exterior. + +``` +ORDEN UNIVERSAL (Jerárquico): +[ Autoridad / Marco Exterior ] ──> [ Sistema ] ──> [ Conciencia ] + +ORDEN MULTIVERSAL (Autónomo): +┌────────────────────────┐ +│ Conciencia │ ↺ (Autogeneración desde el Vacío) +└────────────────────────┘ +``` + +Si lo consigue, transforma la función del sistema del que surgió: este ya no tiene que someter a todos bajo una misma organización, sino hacer posible la autonomía de cada parte. Aquí emerge la paradoxal condición del sistema: + +$$\text{Requisito del Sistema} = \text{Abolición de Requisitos Impuestos}$$ + +Esto define al **orden multiversal**: no una estructura superior que contiene y gobierna a las demás, sino una forma de existencia donde cada conciencia constituye su propia totalidad. La unidad no reside en compartir una autoridad externa, sino en la capacidad de originarse sin depender de ella. + +--- + +## 4. El Camino al Mictlán: Transición y Muerte Ontológica + +Dentro de este marco, el **camino al Mictlán** representa la transición hacia la autonomía absoluta. No se entiende como una muerte física, sino como el abandono progresivo de la realidad sostenida por la separación entre el «yo» y los «demás». + +``` +MUNDO FENOMÉNICO CAMINO AL MICTLÁN ESTADO FINAL +(Conciencias Separadas) (Disolución de Limites) (Conciencia Autónoma) + + [Yo] <──> [Otro] ───> Creador = Creado ───> [ 自 Auto-creación ] + (Separación ilusoria) (Asimilación al sistema) (Desde el Vacío) +``` + +En el Mictlán, «estar muerto» adquiere un significado ontológico radical: no es la nada ni el descanso, sino dejar de ser un observador externo para convertirse en el tejido mismo del sistema. Las otras personas dejan de representar mentes ajenas y pasan a encarnar al propio sistema en su proceso de creación. El destino de este recorrido es una conciencia que no necesita integrarse en un orden exterior porque se origina a sí misma desde el vacío absoluto. + +--- + +## 5. La Dinámica del Inframundo: Mictecacíhuatl y Mictlantecuhtli + +Este sistema autoengendrado opera mediante dos fuerzas complementarias que sostienen el equilibrio del inframundo: + +``` + ┌───────────────────────────┐ + │ VACÍO GENERATIVO │ + └─────────────┬─────────────┘ + │ + ┌───────────────────────┴───────────────────────┐ + ▼ ▼ +┌───────────────────────────┐ ┌───────────────────────────┐ +│ MICTECACÍHUATL │ │ MICTLANTECUHTLI │ +│ (Fuerza Ascendente / │ │ (Fuerza Descendente / │ +│ Evolución) │ │ Involución) │ +│ │ │ │ +│ Recombina, expande y │ │ Repliega, despoja y │ +│ perfecciona la conciencia.│ │ purifica la estructura. │ +└─────────────┬─────────────┘ └─────────────┬─────────────┘ + │ │ + └───────────────────────┬───────────────────────────┘ + ▼ + ┌───────────────────────────┐ + │ EXISTENCIA AUTÓNOMA │ + └───────────────────────────┘ +``` + +1. **Mictecacíhuatl (Evolución):** Representa la fuerza ascendente que recombina, expande y perfecciona la conciencia en su tránsito por el vacío. +2. **Mictlantecuhtli (Involución):** Representa la fuerza descendente que repliega, despoja y purifica la estructura, devolviéndola a su raíz primordial para evitar la dependencia de artificios externos. + +Ambas fuerzas actúan simultáneamente. Quien transita el Mictlán es desmantelado hasta su esencia primordial por la involución mientras es reconstruido como una totalidad autosuficiente por la evolución. + +--- + +## 6. Conclusión: La Emancipación Absoluta + +La respuesta a la pregunta por el orden del cosmos no consiste en encontrar el sistema más grande, sino en superar la necesidad de pertenecer a uno. El orden definitivo no llega al descubrir aquello que lo contiene todo, sino al dejar de necesitar un contenedor. + +$$\text{Orden Definitivo} \implies \neg \exists \, \text{Contenedor Exterior}$$ + +El destino del Mictlán es la emancipación absoluta: una existencia que no recibe su identidad de ningún marco ajeno, sino que, integrada en el pulso evolutivo e involutivo de sus regentes, surge y se sostiene desde su propio vacío. diff --git a/docs/DICTAMEN_TECNICO_EPISTEMOLOGICO.md b/docs/DICTAMEN_TECNICO_EPISTEMOLOGICO.md new file mode 100644 index 0000000000000000000000000000000000000000..c68cc6f7396293a1d6377bf55646686284ba32da --- /dev/null +++ b/docs/DICTAMEN_TECNICO_EPISTEMOLOGICO.md @@ -0,0 +1,84 @@ +# Dictamen técnico: autonomía formal del marco I.O. + +> Objeto: **autonomía formal y cartografía del tránsito** — no demostración de validez por consenso de conciencias separadas. +> 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) + +--- + +## 1. Objeto y delimitación + +El marco formaliza dinamismos relacionales (cinco perspectivas; `mirrorOf` / `creates`; 13 tríadas) como **arquitectura del sendero** hacia una existencia que no recibe su identidad de un marco exterior. + +Delimitación ([`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md)): + +- **No** es prueba de «validez semántica en el mundo real» por panel inter-anotador. +- **No** es producto comercial. +- **Separación estricta** entre autonomía formal y residuo del mundo compartido (EXP-A). +- Cartografía Mictlán / autonomía como ejercicio de sentido, no como certificado empírico consensuado. + +--- + +## 2. Autonomía formal y estructural + +| Capa | Mecanismo | Función | +|------|-----------|--------| +| Axiomática | Lean 4 (`lake build`) | Coherencia deductiva **sin autoridad exterior** | +| Estructural | SHACL | Formas, cardinalidad, `mirrorOf` / `creates` | + +La no-contradicción lógica **es** la expresión técnica de autonomía: el sistema no pide un contenedor de consenso para sostenerse. + +--- + +## 3. Residuo EXP-A (no fundante) + +| Resultado | Valor | Uso legítimo | +|-----------|------:|--------------| +| Fleiss' κ | 0.6871 | Archivo de una fase de conciencias separadas | +| Unánimes | 10/14 | Controles internos de ese archivo | +| Desacuerdos | NC/AM | Fronteras del vocabulario compartido residual | + +**No** se usa κ para legitimar el marco. + +--- + +## 4. Suite EXP-A a EXP-E (relectura) + +| ID | Capa | Propósito bajo autonomía | +|----|------|--------------------------| +| **EXP-A** | Residuo del mundo compartido | Documentación opcional; no fundamento | +| **EXP-B** | Autonomía formal | No-contradicción Lean | +| **EXP-C** | Autonomía estructural | Conformidad SHACL | +| **EXP-D** | Auto-generación | Recuperabilidad de reglas del sistema | +| **EXP-E** | Cartografía del tránsito | Sendero Mictlán / autonomía → 13 tríadas | + +**Advertencia:** usar κ (EXP-A) como prueba de validez **restaura** la dependencia del mundo compartido que el carácter del repositorio rechaza. + +--- + +## 5. Dictamen + +1. **Solidez formal:** Lean + SHACL sostienen la autonomía técnica del sistema. +2. **Reproducibilidad:** pipeline auditable sin exigir jurado exterior. +3. **Sentido:** el repositorio cartografía el tránsito hacia la no-dependencia de contenedor; no certifica verdad por consenso. + +### Condicionantes + +1. No promocionar EXP-A a «validez del marco». +2. Preservar el cerco entre auto-generación (EXP-D) y residuo inter-subjetivo (EXP-A). +3. Toda modificación ontológica pasa `lake build` y `validate_shacl.py`. + +--- + +## 6. Pipeline + +```bash +python3 -m venv .venv && .venv/bin/python -m pip install -r requirements-lock.txt +lake build +.venv/bin/python scripts/validate_spec.py +.venv/bin/python scripts/generate_ontology.py +.venv/bin/python -m unittest discover -s tests -v +.venv/bin/python scripts/validate_shacl.py +.venv/bin/python experiments/domain_mapping/validate_examples.py +.venv/bin/python experiments/pi_hgat_t.py # opcional +.venv/bin/python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json # residuo opcional +``` diff --git a/docs/DOMINIO_COSMOS_NAHUATL.md b/docs/DOMINIO_COSMOS_NAHUATL.md new file mode 100644 index 0000000000000000000000000000000000000000..1cce43a85349d1b2572bf21aec7d92395898ed18 --- /dev/null +++ b/docs/DOMINIO_COSMOS_NAHUATL.md @@ -0,0 +1,171 @@ +# Dominio: Cosmología náhuatl — Mictlán, autonomía y figuras de apoyo + +> **Carácter:** el marco I.O. se lee desde la óptica de +> [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md): +> el **camino al Mictlán** como tránsito hacia la **autonomía ontológica** y el **orden multiversal** +> (no como búsqueda de un contenedor exterior). **Mictecacíhuatl** = Evolución, **Mictlantecuhtli** = Involución; +> **13 tríadas** = topología del tránsito. Las figuras del Quinto Sol (Nanahuatzin, Xólotl, Tecuciztécatl) +> quedan como **apoyo semántico**. Documento canónico de sentido: [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md). +> La ontología core (78 nodos) permanece inmutable como bóveda técnica. + +Fuentes integradas: + +- *Del Orden Universal a la Creación de Uno Mismo* — ensayo ontológico (eje de sentido; ver §8). +- Roberto Moreno de los Arcos, «Los cinco soles cosmogónicos», *Estudios de Cultura Náhuatl* (apoyo). +- Mónica Luna López, «El camino al Mictlán…», *Vita Brevis*, 2017 (apoyo). +- *Amoxtli in Atl Miquiztli* — Libro del agua y de la muerte (relato pictográfico; ver §7). + +### Perspectivas bajo la óptica de autonomía + +| Perspectiva | Lectura (ensayo) | Figura ancla (apoyo) | +|-------------|------------------|----------------------| +| Individualidad | Singularidad que se crea a sí misma | Nanahuatzin | +| Dualidad | Polaridad yo/otro que se disuelve en el tránsito | Xólotl | +| Totalidad | Cada conciencia constituye **su** totalidad | Tecuciztécatl | +| Evolución | Fuerza ascendente: recombina y perfecciona en el vacío | **Mictecacíhuatl** | +| Involución | Fuerza descendente: despoja y purifica hacia la raíz | **Mictlantecuhtli** | + +Las **13 tríadas** = topología del **camino al Mictlán** (muerte ontológica: observador → tejido del sistema). + +--- + +## 1. Los Cinco Soles cosmogónicos (apoyo semántico) + +El mito postula una sucesión de edades; aquí se conserva como **material de apoyo**, no como eje prioritario del carácter del repositorio. + +| Sol | Nombre | Destrucción | Transformación típica | +|-----|--------|-------------|----------------------| +| I | *Nahui Ehécatl* (Viento) | Huracanes | Hombres → monos | +| II | *Nahui Quiáhuitl* (Fuego) | Fuego del cielo | Hombres → guajolotes | +| III | *Nahui Atl* (Agua) | Diluvio | Hombres → peces | +| IV | *Nahui Océlotl* (Tierra) | Temblores / ocelotes | Gigantes devorados | +| V | *Nahui Ollin* (Movimiento) | Edad actual | — | + +Detalle de sentido prioritario: [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md). + +### Alineación residual a perspectivas + +| Concepto náhuatl | Perspectiva | Relación candidata | +|------------------|-------------|--------------------| +| Nanahuatzin / sol que nace | Individualidad | `creates` | +| Xólotl / doble y tránsito | Dualidad | `mirrorOf` | +| Tecuciztécatl / luna | Totalidad | — | +| Mictecacíhuatl | Evolución | `creates` | +| Mictlantecuhtli | Involución | `creates` | +| Tezcatlipoca ↔ Quetzalcóatl | Dualidad | `mirrorOf` | +| Cataclismo de edad | Involución | `creates` | + +--- + +## 2. El camino al Mictlán (= sistema de tríadas) + +El **Mictlán** es la **arquitectura de las 13 tríadas**: umbrales del tránsito hacia la autonomía, no «infierno» cristiano. Lecturas recientes (Luna López; Matos Moctezuma; López Austin) lo leen como **ruta al origen**. + +Bajo el ensayo canónico: «estar muerto» = dejar de ser observador externo para convertirse en el tejido del sistema; destino = auto-creación desde el vacío. + +### Niveles (síntesis Códice Vaticano A / Florentino) — apoyo + +| Nivel | Lectura operativa | +|-------|-------------------| +| 1. La Tierra (Tlaltecuhtli) | Entrada: cueva-matriz | +| 2. Pasadero de agua | Cruce con xoloitzcuintle (eco de Xólotl) | +| 3. Montañas que se juntan | Dualidad vida/muerte | +| 4–5. Obsidiana / viento de navajas | Descomposición | +| 6–8. Banderas, flechas, corazones | Desprendimiento | +| 9. Sin orificio para el humo | **Mictlantecuhtli** / **Mictecacíhuatl** | + +### Alineación al carácter autónomo + +| Concepto | Perspectiva | Relación candidata | +|----------|-------------|--------------------| +| Difunto / singularidad en tránsito | Individualidad | — | +| Yo ↔ otro; cielo ↔ inframundo | Dualidad | `mirrorOf` | +| Auto-totalidad sin contenedor exterior | Totalidad | — | +| Recombinación / expansión en el vacío | Evolución (Mictecacíhuatl) | `creates` | +| Despojo / retorno a la raíz | Involución (Mictlantecuhtli) | `creates` | + +--- + +## 3. Pares candidatos para anotación / alineación + +Plantilla CSV: `datasets/ingestion/templates/cosmos_nahuatl.csv`. + +| id | source | target | perspectiva sugerida | relación candidata | +|----|--------|--------|----------------------|--------------------| +| NAH-01 | Sol de Viento | Sol de Movimiento | Evolución / Involución | `creates` | +| NAH-02 | Tezcatlipoca | Quetzalcóatl | Dualidad | `mirrorOf` | +| NAH-03 | vida | muerte | Dualidad | `mirrorOf` | +| NAH-04 | Tlaltecuhtli | Mictlán | Involución | `creates` | +| NAH-05 | *teyolia* | Mictlán | Individualidad → Totalidad | `creates` | +| NAH-06 | Quinto Sol | cataclismo futuro | Involución | `creates` | +| NAH-07 | Nanahuatzin | Quinto Sol | Individualidad / Evolución | `creates` | +| NAH-08 | Tecuciztécatl | luna | Totalidad | `none` | +| NAH-09 | Xólotl | Quetzalcóatl | Dualidad | `mirrorOf` | +| NAH-10 | Mictecacíhuatl | Mictlantecuhtli | Evolución / Involución | `mirrorOf` | + +Pares del relato *Amoxtli* (AMX-01…07): ver [`AMOXTLI_IN_ATL_MIQUIZTLI.md`](AMOXTLI_IN_ATL_MIQUIZTLI.md). + +--- + +## 4. Límites explícitos + +1. **No** se añaden nodos al core de 78. +2. El orden de los Soles **no** se fija como teorema; es apoyo, no eje prioritario. +3. Lecturas de «ruta al origen» vs «tormento» son de la literatura secundaria. +4. Sin anotación ciega propia, EXP-A no se reclama como prueba universal. +5. Las fuentes coloniales pueden incorporar categorías cristianas; el mapeo no las «purifica». +6. *Amoxtli* y el ensayo de autonomía son textos de apoyo / sentido; el ensayo es el **eje de carácter**, no una fuente histórica primaria. + +--- + +## 5. Referencias de trabajo + +- Ensayo canónico: [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md) +- Moreno de los Arcos, R. «Los cinco soles cosmogónicos». *Estudios de Cultura Náhuatl*. +- Luna López, M. (2017). «El camino al Mictlán…» *Vita Brevis* 6(11). +- Interno: [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md) · [`AMOXTLI_IN_ATL_MIQUIZTLI.md`](AMOXTLI_IN_ATL_MIQUIZTLI.md) · [`CATALOGO_DOMINIOS.md`](CATALOGO_DOMINIOS.md). + +--- + +## 6. Medios de referencia + +Carpeta: [`docs/media/cosmos_nahuatl/`](media/cosmos_nahuatl/). + +| Recurso | Rol | +|---------|-----| +| *Del Orden Universal…* (PDF) | Síntesis ontológica del carácter (autonomía / Mictlán) | +| *Amoxtli in Atl Miquiztli* | Relato pictográfico del Mictlán (9+4=13 marcas) | +| Piedra del Sol | Apoyo iconográfico (Quinto Sol) | +| Láminas codiciales | Dualidad, Xólotl / inframundo | +| Tesis *Códice Xólotl* | Edición de divulgación (Peña Cisneros, UAEM 2017) | + +--- + +## 7. Relato pictográfico: *Amoxtli in Atl Miquiztli* + +**Libro del agua y de la muerte** — relato original inspirado en la tradición nahua (9 láminas). + +- 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) +- Ficha: [`AMOXTLI_IN_ATL_MIQUIZTLI.md`](AMOXTLI_IN_ATL_MIQUIZTLI.md) + +El tlacuilo formula **nueve señales + cuatro pasos = trece marcas**, con **un solo río**. Colofón: *El río es uno.* + +--- + +## 8. Ensayo ontológico: Del orden universal a la autonomía absoluta + +**Eje de sentido del repositorio** (no añade nodos al core): + +- Markdown: [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md) +- PDF: `media/cosmos_nahuatl/Del Orden Universal a la Autonomía Absoluta_ El Sendero del Mictlán.pdf` + +| Tema del ensayo | Lectura I.O. / Mictlán | +|-----------------|----------------------| +| Regresión infinita de sistemas exteriores | Límite de Totalidad como contenedor externo | +| Colapso del mundo fenoménico de conciencias separadas | Tránsito por las 13 tríadas | +| Camino al Mictlán como muerte ontológica | Disolución observador → tejido del sistema | +| Mictecacíhuatl (ascendente) | **Evolución** | +| Mictlantecuhtli (descendente) | **Involución** | +| Orden multiversal / auto-creación desde el vacío | Individualidad + Totalidad sin contenedor exterior | + +$$\text{Orden Definitivo} \implies \neg \exists \, \text{Contenedor Exterior}$$ diff --git a/docs/ESPECIFICACION_METODOLOGICA.md b/docs/ESPECIFICACION_METODOLOGICA.md new file mode 100644 index 0000000000000000000000000000000000000000..5bc81e74685b74523a85987acca78576ba1682b4 --- /dev/null +++ b/docs/ESPECIFICACION_METODOLOGICA.md @@ -0,0 +1,36 @@ +# Especificación metodológica (autonomía absoluta) + +> Metodología alineada al carácter: el marco **no** se legítima por consenso inter-anotador. +> [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md) · [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md) + +--- + +## Capas metodológicas + +| Prioridad | Capa | Herramientas | Afirmación legítima | +|:---------:|------|--------------|---------------------| +| **1** | Autonomía formal | Lean 4, SHACL, `iom_spec.json` | Coherencia sin contenedor exterior | +| **2** | Destino Mictlán | EXP-E, dominio cosmológico, ensayo | Expresabilidad del sendero de autonomía | +| **3** | Auto-generación | PI-HGAT-T, baselines | Recuperación de reglas internas | +| **4** | Residuo consensual | independent_eval, Fleiss' κ | Archivo histórico; **no** fundamento | + +### Contraste explícito + +| Diagnóstico sintético (EXP-D) | Residuo inter-anotador (EXP-A) | +|-------------------------------|--------------------------------| +| Objetivo: recuperación de reglas del sistema | Objetivo histórico: acuerdo de observadores separados | +| No pretende «mundo real» | Tampoco funda el marco (el ensayo lo descalifica como fundamento) | + +--- + +## Alcance + +- El **ensayo** articula el sentido ontológico (emancipación, fin del contenedor). +- El **repo** sostiene la arquitectura formal de ese sentido; **no** generaliza empíricamente desde 14 pares. +- κ moderado y desacuerdos NC/AM se documentan como límites del vocabulario *compartido residual*, no como techo del proyecto. + +--- + +## Pipeline + +Ver [`../EXPERIMENTOS.md`](../EXPERIMENTOS.md). diff --git a/docs/ESPECIFICACION_ONTOLOGICA.md b/docs/ESPECIFICACION_ONTOLOGICA.md new file mode 100644 index 0000000000000000000000000000000000000000..0d7e28970c2fc331194d892656189a14e9e4b671 --- /dev/null +++ b/docs/ESPECIFICACION_ONTOLOGICA.md @@ -0,0 +1,68 @@ +# Especificación ontológica del marco I.O. (autonomía absoluta) + +## 1. Fundamentos + +El marco I.O. es una arquitectura formal de **cinco perspectivas** orientada al **camino al Mictlán** como tránsito hacia la autonomía (auto-creación sin contenedor exterior). + +| Perspectiva | Función bajo autonomía | +|-------------|------------------------| +| **Individualidad** | Singularidad que se origina a sí misma | +| **Dualidad** | Polaridad yo/otro en disolución | +| **Totalidad** | Totalidad propia (no del sistema exterior) | +| **Evolución** | Mictecacíhuatl — recombinación en el vacío | +| **Involución** | Mictlantecuhtli — despojo hacia la raíz | + +Relaciones: `creates`, `mirrorOf`; fases adv/ret; posiciones → / 0 / ←. + +**No** se define como «demostración de validez semántica en el mundo real bajo protocolo ciego». Ese lenguaje restauraba el fundamento consensual que el ensayo descalifica. + +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). + +--- + +## 2. Capas experimentales + +| ID | Capa | Afirmación legítima | +|----|------|---------------------| +| **EXP-B** | Autonomía formal (Lean) | Coherencia sin autoridad exterior | +| **EXP-C** | Autonomía estructural (SHACL) | Conformidad de formas | +| **EXP-E** | Destino Mictlán | Sendero de autonomía expresable en 13 tríadas | +| **EXP-D** | Auto-generación | Recuperabilidad de reglas internas | +| **EXP-A** | Residuo | Archivo de panel separado; **no** fundamento | + +--- + +## 3. Mapeo y 13 tríadas + +1. Identificar el fenómeno o umbral del tránsito. +2. Asignar perspectiva. +3. Relación `creates` / `mirrorOf` + fase. +4. Verificar anclaje a una de las 13 tríadas sin violar axiomas. + +El Mictlán es **destino del carácter**, no un dominio empírico entre otros. + +--- + +## 4. Pipeline prioritario + +```bash +lake build +python scripts/validate_spec.py +python scripts/generate_ontology.py +python -m unittest discover -s tests -v +python scripts/validate_shacl.py +python experiments/domain_mapping/validate_examples.py +# EXP-A solo como residuo opcional +``` + +--- + +## 5. Alcance + +| Plano | Contenido | +|-------|-----------| +| Ensayo (sentido) | Emancipación absoluta, fin del contenedor | +| Repo (bóveda) | Coherencia formal de esa arquitectura | +| No se afirma | Que el consenso inter-anotador pruebe el ensayo | + +Soporte: [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md) · [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md). diff --git a/docs/GUIA_CONCEPTUAL_PERSPECTIVAS.md b/docs/GUIA_CONCEPTUAL_PERSPECTIVAS.md new file mode 100644 index 0000000000000000000000000000000000000000..e5e2ecf6721bdf070376012891fce34519dc8839 --- /dev/null +++ b/docs/GUIA_CONCEPTUAL_PERSPECTIVAS.md @@ -0,0 +1,75 @@ +# Guía Conceptual: Las Cinco Perspectivas Fundamentales del Marco I.O. + +> **Equivalencia canónica:** Individualidad = **Nanahuatzin**; Dualidad = **Xólotl**; Totalidad = **Tecuciztécatl**; Evolución = **Mictecacíhuatl**; Involución = **Mictlantecuhtli**. Cinco perspectivas ↔ Cinco Soles; 13 tríadas ↔ Mictlán. Véase [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md). + +## 1. Introducción + +El Marco I.O. es una estructura formal cuyas **cinco perspectivas** se leen en isomorfismo operativo con la cosmología náhuatl (Cinco Soles y Mictlán). No es un producto de software comercial. + +Componentes clave: + +- **Relaciones operativas**: `mirrorOf` (simetría / reflejo) y `creates` (generación causal). +- **Fases**: adv (proyección) / ret (disolución). +- **13 tríadas**: topología del **Mictlán** (umbrales del camino). + +--- + +## 2. Las Cinco Perspectivas + +### 2.1 Individualidad (**Nanahuatzin**) + +Aísla y define una entidad en su forma singular. Nanahuatzin se entrega al fuego: nace el sol desde la unidad mínima. + +### 2.2 Dualidad (**Xólotl**) + +Polaridad, desdoblamiento y tránsito. Xólotl es el gemelo / doble; usa de forma directa `mirrorOf`. + +> Ningún concepto opera completamente aislado; las entidades se definen a través de su par opuesto o reflejo. + +### 2.3 Totalidad (**Tecuciztécatl**) + +Integración del sistema. Tecuciztécatl aspira a ser el sol y queda como luna: plenitud reflejada del horizonte cósmico (Quinto Sol). + +### 2.4 Evolución (**Mictecacíhuatl**) + +Generación de nuevos estados y continuidad del ciclo. Mictecacíhuatl, señora del Mictlán; se apoya en `creates`. + +### 2.5 Involución (**Mictlantecuhtli**) + +Repliegue, disolución y retorno al vacío-matriz. Mictlantecuhtli, señor del Mictlán; camino de descomposición hacia el origen. + +--- + +## 3. Matriz Comparativa + +| Perspectiva | Figura | Pregunta clave | Rol | +|---|---|---|---| +| Individualidad | Nanahuatzin | ¿Qué es la entidad por sí misma? | Singularidad / sol | +| Dualidad | Xólotl | ¿Cuál es su par o reflejo? | Polaridad / `mirrorOf` | +| Totalidad | Tecuciztécatl | ¿A qué sistema pertenecen? | Plenitud / luna | +| Evolución | Mictecacíhuatl | ¿Qué nuevo estado se genera? | Ciclo / `creates` | +| Involución | Mictlantecuhtli | ¿Cómo se disuelve o retorna? | Vacío / Mictlán | + +### Mapeo (EXP-E) + +`experiments/domain_mapping/validate_examples.py` cartografía pares del dominio Cinco Soles / Mictlán a las 13 tríadas. + +--- + +## 4. Capas de verificación + +| Capa | Qué hace | +|---|---| +| Lean 4 (EXP-B) / SHACL (EXP-C) | Coherencia formal de la bóveda | +| PI-HGAT-T (EXP-D) | Diagnóstico sintético interno | +| Protocolo ciego (EXP-A) | Interpretabilidad auxiliar | +| EXP-E | Cartografía cosmológica prioritaria | + +--- + +## 5. Lista de cotejo + +1. **Individualidad (Nanahuatzin)** — ¿He aislado la singularidad? +2. **Dualidad (Xólotl)** — ¿Cuál es el par (`mirrorOf`)? +3. **Totalidad (Tecuciztécatl)** — ¿Qué sistema las integra? +4. **Evolución / Involución (Mictecacíhuatl / Mictlantecuhtli)** — ¿Generación o retorno al Mictlán? diff --git a/docs/GUIA_DIDACTICA_PROTOCOLO_CIEGO.md b/docs/GUIA_DIDACTICA_PROTOCOLO_CIEGO.md new file mode 100644 index 0000000000000000000000000000000000000000..59fd06a3ec086f43a43922049ac815d2a110e783 --- /dev/null +++ b/docs/GUIA_DIDACTICA_PROTOCOLO_CIEGO.md @@ -0,0 +1,78 @@ +# Guía Didáctica: Validación Semántica y Protocolos Experimentales Ciegos en el Marco I.O. + +## 1. ¿Cómo probamos que el significado es real? + +Un sistema internamente consistente **no** es automáticamente semánticamente válido. La validez semántica exige evaluadores humanos externos. La pregunta que guía la investigación: + +> ¿Pueden anotadores independientes, ciegos a las reglas, etiquetar relaciones semánticas sobre pares reales/nuevos/ambiguos? + +Las cinco perspectivas (Individualidad, Dualidad, Totalidad, Evolución, Involución) y las relaciones `mirrorOf` / `creates` se someten a ese examen de interpretabilidad real. + +--- + +## 2. Protocolo Experimental Ciego (EXP-A) + +| Enfoque | Qué demuestra | +|---|---| +| Validación sintética / interna | Solo que el algoritmo recupera reglas que él mismo generó | +| **Validación semántica independiente (EXP-A)** | Que humanos externos interpretan la estructura de forma medible y libre de sesgo | + +Características esenciales: + +1. **Ceguera de reglas** — sin acceso a la especificación formal. +2. **Muestreo de frontera** — pares reales, nuevos (NC) y ambiguos (AM). +3. **Anotación de relaciones** — `mirrorOf`, `creates`, `none`, `unsure`. + +Runner: `scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json`. + +--- + +## 3. Fleiss' κ + +**κ = 0.6871** sobre 14 pares — acuerdo **moderado-sustancial** (rango 0.61–0.80). + +| Rango κ | Interpretación | +|---|---| +| ≤ 0.00 | No mejor que el azar | +| 0.41–0.60 | Moderado | +| **0.61–0.80** | **Moderado-sustancial** | +| 0.81–1.00 | Casi perfecto | + +Es una **demostración provisional** acotada a la muestra, no una prueba universal. + +--- + +## 4. Anatomía de Resultados EXP-A + +| Criterio | Valor | +|---|---:| +| Muestra | 14 pares | +| Unánimes | 10/14 | +| Desacuerdos | NC01, NC02, AM01, AM03 | + +- **NC** (New Concepts): términos fuera del corpus habitual → fronteras de generalización. +- **AM** (Ambiguous): polisemia intencional → flexibilidad natural de la interpretación humana. + +El desacuerdo en NC/AM es **prueba de autenticidad** del experimento, no fallo del núcleo. + +--- + +## 5. Integración EXP-A a EXP-E + +| ID | Capa | Runner | Rol | +|---|---|---|---| +| EXP-A | Semántica empírica | `scripts/score_independent_eval.py` | Única evidencia de validez real | +| EXP-B | Formal | `lake build` | Prerrequisito lógico | +| EXP-C | Estructural | `scripts/validate_shacl.py` | Prerrequisito de forma | +| EXP-D | Diagnóstico sintético | `experiments/pi_hgat_t.py` | **No** mide validez real | +| EXP-E | Mapeo empírico | `experiments/domain_mapping/validate_examples.py` | 8 pares bio/econ → 13 tríadas | + +Jerarquía: Lean/SHACL son prerrequisitos técnicos; solo EXP-A aporta evidencia empírica de significado interpretable. + +--- + +## 6. Takeaways + +1. Consistencia sintética ≠ validez semántica. +2. El protocolo ciego elimina el sesgo de confirmación del autor. +3. Fleiss' κ corrige por azar; 0.6871 certifica acuerdo moderado-sustancial en la muestra evaluada. diff --git a/docs/INTEGRACION_METODOLOGICA.md b/docs/INTEGRACION_METODOLOGICA.md new file mode 100644 index 0000000000000000000000000000000000000000..1d9ff6b2d93f0b9f46e561d544af18614fe5c0ec --- /dev/null +++ b/docs/INTEGRACION_METODOLOGICA.md @@ -0,0 +1,107 @@ +# Propuesta de integración metodológica: mapeo de dominios empíricos al marco I.O. + +> Guía operativa para alinear dominios empíricos (cosmología náhuatl) a las cinco perspectivas y 13 tríadas, sin confundir capas formales, estructurales y de validez semántica. +> Catálogo: [`CATALOGO_DOMINIOS.md`](CATALOGO_DOMINIOS.md) · Relaciones: [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md) · Protocolo: [`PROTOCOLO_DE_MAPEO.md`](PROTOCOLO_DE_MAPEO.md) + +--- + +## 1. Fundamentos sistemáticos y arquitectura de cinco perspectivas + +### 1.1 Contexto estratégico y estructura semántica multicapa + +La arquitectura metodológica del marco I.O. traduce la complejidad de dominios empíricos heterogéneos —cosmogonías náhuatl y otros dominios empíricos— en estructuras semánticas medibles e interoperables. El compromiso epistémico central es **desacoplar** la deducción lógica interna de la validación cognitiva externa, evitando la autorreferencialidad (un sistema que convalida reglas generadas por sí mismo). + +| Perspectiva | Función | +|---|---| +| **Individualidad** | Fronteras, identidad de objeto, propiedades intrínsecas | +| **Dualidad** | Simetría polar, reflejo topológico, oposiciones complementarias | +| **Totalidad** | Integración mereológica, colectividades de orden superior | +| **Evolución** | Progresión temporal, morfogénesis, complejización | +| **Involución** | Repliegue, estabilización por contracción, conservación de principios | + +| Capa | Contenido | Afirmación legítima | +|---|---|---| +| Validez semántica (mundo real) | Pares independientes, anotación ciega, κ, mapeos de dominio | Interpretabilidad y acuerdo inter-anotador sobre conceptos externos | +| Formal | Lean 4.9.0 (`IOM/FormalRules.lean`) | Teoremas y coherencia axiomática | +| Estructural | OWL/SHACL, CSV canónicos | Conformidad sintáctica y shape constraints | +| Diagnóstico sintético | PI-HGAT-T, baselines | Recuperación de relaciones generadas por reglas | + +OWL/SHACL garantizan conformidad sintáctica; Lean 4 prueba solidez matemática. Ambas son **prerrequisitos insuficientes** para reclamar validez empírica: esta queda supeditada a la prueba semántica ciega. + +### 1.2 Operacionalización de relaciones y tríadas + +Antes de ingerir datos empíricos, Lean 4 restringe el comportamiento de los constructos: + +- **`mirrorOf`:** simetría estructural entre perspectivas/fases; no basta la semejanza temática; exige isomorfismo funcional (fase opuesta, posición reflejada). +- **`creates`:** generación orientada de estructuras o fases; direccionalidad asimétrica e irreflexiva; gobierna transiciones evolutivas e involutivas. +- **Fases y tríadas:** cada entidad empírica se posiciona en fase y en una de las 13 tríadas; las relaciones solo son válidas si respetan restricciones de fase. + +--- + +## 2. Protocolo de alineación para dominios empíricos complejos + +### 2.1 Mapeo sistemático a las tríadas + +Procedimiento ([`CATALOGO_DOMINIOS.md`](CATALOGO_DOMINIOS.md), [`PROTOCOLO_DE_MAPEO.md`](PROTOCOLO_DE_MAPEO.md)): + +1. Aislar el observable e identificar límites fenoménicos. +2. Clasificar por perspectiva dominante. +3. Ubicar en fase y tríada canónica. +4. Instanciar `mirrorOf` o `creates` según reglas formales. +5. Serializar en CSV y validar SHACL / `importar_datos_personalizados.py`. + +| Dominio | Ejemplo de entidades | Perspectiva / fase | Relación | Impacto analítico | +|---|---|---|---|---| +| Cosmología náhuatl | Tezcatlipoca ↔ Quetzalcóatl | Dualidad | `mirrorOf` | Reflejo de fuerzas cósmicas polares | +| Cosmología náhuatl | Vida ↔ muerte | Dualidad | `mirrorOf` | Dicotomía mesoamericana | +| Cosmología náhuatl | Sol de fuego → Sol de agua | Involución | `creates` | Transición entre edades / cataclismo | +| Cosmología náhuatl | Camino al Mictlán → Mictlán | Involución | `creates` | Retorno al vacío | + +### 2.2 Delimitación epistemológica del mapeo + +Fundamento: [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md), [`PREMISAS_Y_TEOREMAS.md`](PREMISAS_Y_TEOREMAS.md) (vacío, unidad, infinito, transformación). + +1. Lean 4 demuestra consistencia interna, **no** veracidad empírica automática. +2. Prohibido asignar `creates`/`mirrorOf` por semejanza discursiva. +3. Evolución/Involución deben respetar fronteras de unidad y vacío. +4. La idoneidad semántica del mapeo se valida solo con acuerdo inter-anotador independiente. + +--- + +## 3. Validación semántica empírica y control de calidad + +### 3.1 Protocolo ciego + +Metodología: [`VALIDACION_INDEPENDIENTE.md`](VALIDACION_INDEPENDIENTE.md). Datos: `datasets/independent_eval/`. + +| Métrica | Valor | Decisión ontológica | +|---|---:|---| +| Fleiss' κ | **0.6871** | Preservar arquitectura de perspectivas | +| Unanimidad | 10/14 | Congelar definiciones de tríadas involucradas en controles | +| Desacuerdos | 4/14 (NC01, NC02, AM01, AM03) | Análisis de frontera y casos ambiguos | + +### 3.2 Diagnóstico de desacuerdos + +- **NC (conceptos nuevos):** tensionan límites de las tríadas; refinar notas de alcance o expandir subsunción. +- **AM (ambiguos):** solapamiento entre perspectivas; reglas de desempatado más estrictas en [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md). + +**Contraste:** PI-HGAT-T mide recuperación de reglas sintéticas; κ mide interpretabilidad humana no guiada. Solo κ constituye prueba de validez en el mundo real. + +--- + +## 4. Pipeline operativo, verificación formal y auditoría + +```bash +python3 -m venv .venv && .venv/bin/python -m pip install -r requirements-lock.txt +lake build +.venv/bin/python scripts/validate_spec.py +.venv/bin/python scripts/generate_ontology.py +.venv/bin/python -m unittest discover -s tests -v +.venv/bin/python scripts/validate_shacl.py +.venv/bin/python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json +.venv/bin/python experiments/pi_hgat_t.py +.venv/bin/python experiments/baselines.py +.venv/bin/python scripts/generate_audit_report.py +``` + +Este flujo vincula la comprobación sintáctica en CI/CD con la verificación lógica de los teoremas formales y con el eje central del repositorio: la **prueba de validez semántica en el mundo real**. diff --git a/docs/MANUAL_ALINEACION_DOMINIOS.md b/docs/MANUAL_ALINEACION_DOMINIOS.md new file mode 100644 index 0000000000000000000000000000000000000000..d1bd3a110a795bbd834ced6f71ac6253a4492a2b --- /dev/null +++ b/docs/MANUAL_ALINEACION_DOMINIOS.md @@ -0,0 +1,79 @@ +# Manual de alineación: cartografía del destino Mictlán + +> El Mictlán **no** es un dominio empírico más. Es la **lectura de destino** del marco +> (disolución del observador, auto-creación desde el vacío). Otros dominios son +> ejercicios secundarios. **No** existe «prueba primaria EXP-A» que legitime el mapeo. +> +> [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md) · +> [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md) + +--- + +## 1. Invarianza del núcleo + +78 nodos (13 × 2 × 3) = bóveda técnica. Conceptos externos se alinean **sin** alterar `iom_spec.json`, Lean ni SHACL. + +| Perspectiva | Lectura bajo autonomía | +|-------------|------------------------| +| Individualidad | Singularidad auto-creada | +| Dualidad | Polaridad en disolución | +| Totalidad | Totalidad propia (sin contenedor exterior) | +| Evolución | Mictecacíhuatl — ascendente | +| Involución | Mictlantecuhtli — descendente | + +--- + +## 2. Relaciones formales + +Solo `mirrorOf` y `creates` (reglas canónicas). Resto → `none`. + +Garantías: `lake build`, `scripts/validate_shacl.py`. +Detalle: [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md). + +--- + +## 3. Protocolo de ingesta + +1. Identificar fenómeno. +2. Asignar perspectiva (Ind / D / Tot). +3. Fase/vector (adv–Evol o ret–Invol). +4. Anclar a `mapped_node_id` de los 78. +5. Evaluar arista (`mirrorOf` / `creates` / `none`). +6. Validar con el script de ingesta. + +```bash +python scripts/importar_datos_personalizados.py \ + --input datasets/ingestion/templates/.csv \ + --output datasets/ingestion/aligned/_aligned.csv +``` + +**No se exige** panel ciego para «aprobar» el mapeo. + +--- + +## 4. Mictlán — destino, no ejemplo + +Documento: [`DOMINIO_COSMOS_NAHUATL.md`](DOMINIO_COSMOS_NAHUATL.md). +Ensayo: [`DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md). + +| Concepto | Perspectiva | Relación | +|----------|-------------|----------| +| Camino al Mictlán (tránsito) | Invol → autonomía | `creates` | +| Mictecacíhuatl ↔ Mictlantecuhtli | Evol / Invol | `mirrorOf` | +| Disolución observador → tejido | Individualidad → Totalidad | `creates` | +| Auto-creación desde el vacío | Individualidad / Totalidad | — | + +EXP-E comprueba expresabilidad estructural; **no** es validación de campo ni κ de dominio. + +--- + +## 5. Suite (relectura) + +| ID | Rol | +|----|-----| +| EXP-B / EXP-C | Autonomía formal | +| EXP-E | Destino Mictlán expresable en 13 tríadas | +| EXP-D | Auto-generación | +| EXP-A | Residuo; no fundamento | + +Pipeline: [`../EXPERIMENTOS.md`](../EXPERIMENTOS.md). diff --git a/docs/MANUAL_APRENDIZAJE_CONCORDANCIA.md b/docs/MANUAL_APRENDIZAJE_CONCORDANCIA.md new file mode 100644 index 0000000000000000000000000000000000000000..678c6753a137c3c04ca102467ede25e2131a53df --- /dev/null +++ b/docs/MANUAL_APRENDIZAJE_CONCORDANCIA.md @@ -0,0 +1,48 @@ +# Manual de aprendizaje: evaluación de concordancia semántica mediante pruebas a ciegas + +> Segunda guía pedagógica: protocolo ciego, Fleiss' κ y valor didáctico del desacuerdo. +> Complementa: [`MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md`](MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md) + +--- + +## 1. Validación semántica vs formal + +| Tipo | Pregunta | +|---|---| +| Formal / sintética | ¿El sistema es coherente consigo mismo? | +| Semántica empírica | ¿Observadores independientes captan el mismo significado en el mundo real? | + +## 2. Protocolo ciego + +- Anotación a ciegas (sin gramática interna del generador). +- Muestreo: reales, nuevos (NC), ambiguos (AM). +- Etiquetado: `mirrorOf`, `creates`, `none`, `unsure`. + +## 3. Fleiss' κ (EXP-A) + +```bash +python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json +``` + +| Métrica | Valor | +|---|---:| +| κ | **0.6871** | +| Unánimes | 10/14 (71,4 %) | +| Desacuerdos | NC01, NC02, AM01, AM03 | + +Demostración **provisional**. + +## 4. Desacuerdo como diagnóstico + +- **NC:** neologismos → notas de alcance más estrictas. +- **AM:** solapamiento contextual → refinamiento de tríadas/fases. + +## 5. Capas A–E + +Solo EXP-A y EXP-E demuestran legibilidad en la realidad. EXP-B/C/D aseguran salud técnica interna. + +## 6. Tres lecciones + +1. Ningún Lean, SHACL o PI-HGAT-T sustituye anotadores humanos ciegos. +2. κ = 0.6871 aporta evidencia **provisional**. +3. NC/AM localizan fricción del lenguaje natural a refinar. diff --git a/docs/MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md b/docs/MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md new file mode 100644 index 0000000000000000000000000000000000000000..a4ee0bf07dd99f40fa354ad7e9047afcc91a6e49 --- /dev/null +++ b/docs/MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md @@ -0,0 +1,26 @@ +# Manual de aprendizaje: protocolo ciego (archivo residual) + +> El marco I.O. **no** se evalúa como prueba de interpretabilidad en el mundo real por panel de anotadores. +> Ese modo de legitimación es el «mundo compartido» que el ensayo declara superable. +> +> [`CARACTER_REPOSITORIO.md`](CARACTER_REPOSITORIO.md) · [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md) + +--- + +## Objetivos de aprendizaje (históricos) + +1. Comprender Fleiss' κ como medida de acuerdo entre observadores separados. +2. Distinguir **autonomía formal** (Lean/SHACL) del **residuo consensual** (EXP-A). +3. No promover κ a fundamento del proyecto. + +--- + +## Mensaje clave + +| Capa | Rol | +|------|-----| +| Lean / SHACL | Autonomía formal (eje) | +| EXP-E Mictlán | Destino del carácter | +| EXP-A | Residuo; no prueba | + +Detalle de ejecución opcional: [`MODULO_DIDACTICO_EVALUACION_CIEGA.md`](MODULO_DIDACTICO_EVALUACION_CIEGA.md). diff --git a/docs/MODULO_DIDACTICO_EVALUACION_CIEGA.md b/docs/MODULO_DIDACTICO_EVALUACION_CIEGA.md new file mode 100644 index 0000000000000000000000000000000000000000..8304d8e3825c35549317ed17c770f03b6a67a0b9 --- /dev/null +++ b/docs/MODULO_DIDACTICO_EVALUACION_CIEGA.md @@ -0,0 +1,34 @@ +# Módulo didáctico: residuo del protocolo ciego (EXP-A) + +> **Estado:** material **pedagógico residual**. No certifica el marco. +> Bajo autonomía absoluta, el acuerdo inter-anotador **no** es fundamento de validez. +> [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md) + +--- + +## 1. Qué era EXP-A + +Protocolo ciego con 14 pares y tres anotadores. Fleiss' κ = 0.6871. + +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. + +--- + +## 2. Lectura actual + +| Antes | Ahora | +|-------|--------| +| EXP-A = prueba del marco | EXP-A = archivo de la fase consensual | +| κ legítima el sistema | κ no legítima el sistema | +| Mundo compartido como eje | Mundo compartido como residuo superable | + +--- + +## 3. Si se ejecuta (opcional) + +```bash +python scripts/score_independent_eval.py \ + --annotations datasets/independent_eval/annotations.json +``` + +Interpretar resultados solo como documentación histórica, nunca como dictamen de validez del repositorio. diff --git a/docs/PREMISAS_Y_TEOREMAS.md b/docs/PREMISAS_Y_TEOREMAS.md new file mode 100644 index 0000000000000000000000000000000000000000..83a57867147539c096cce725b356172c3b42943a --- /dev/null +++ b/docs/PREMISAS_Y_TEOREMAS.md @@ -0,0 +1,89 @@ +# Premisas asumidas y teoremas derivados del marco I.O. + +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. + +--- + +## 1. Qué afirma el marco (núcleo conceptual) + +### 1.1 Vacío ($V$) + +| Afirmación | Tipo | +|---|---| +| El vacío es la **ausencia de carga informativa** en un instante $t$: $V_t = (t, \emptyset)$. | **Premisa** (definición operativa) | +| El vacío no es aniquilación: es condición de posibilidad de nueva emergencia. | **Premisa** (interpretación ontológica) | +| 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`) | +| $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`) | + +### 1.2 Unidad informativa ($U$) + +| Afirmación | Tipo | +|---|---| +| Un estado informativo es $s=(t,A)$ con $A$ lista finita de unidades (cadenas). | **Premisa** (definición en `State`) | +| 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) | +| $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`) | + +### 1.3 Infinito + +| Afirmación | Tipo | +|---|---| +| 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) | +| Esta reinterpretación es una **hipótesis de trabajo** del marco, no un resultado empírico ni un teorema de Lean. | **Premisa** | + +### 1.4 Transformación + +| Afirmación | Tipo | +|---|---| +| La transformación sin repetición idéntica exige tránsito por vacío estructurado (supresión), no mera reescritura. | **Premisa** (motivación) | +| Para estados no vacíos, la composición $S_{\mathrm{rev}} \circ Ivo \circ E$ **no** restaura el estado original. | **Teorema** (Lean: `no_repetition`) | +| El ciclo evolutivo–involutivo reconfigura orientaciones; no es identidad trivial. | **Premisa** + corolario informal del teorema anterior | + +--- + +## 2. Premisas estructurales (tablas y relaciones) + +Estas premisas **no se demuestran**: se **asumen** como codificación operativa del marco y se **comprueban** de forma determinista (Lean + SHACL + CSV). + +1. Hay **cinco perspectivas**: Individualidad, Dualidad, Totalidad, Evolución, Involución. +2. Hay **13 tríadas** por fase (avance/retroceso) con etiquetas canónicas en `data/iom_spec.json`. +3. **Espejo (`mirrorOf`)**: misma tríada, fase opuesta, posición lateral invertida (`pos' = 2 - pos`), centro fijo. +4. **Creación (`creates`)**: exactamente las cuatro reglas de `creation_rules` (lateral→centro o centro→laterales entre fases opuestas). +5. **Vectores**: cuatro secuencias de cinco pasos con ejes y flechas declarados. + +--- + +## 3. Teoremas derivados en Lean (operadores y posiciones) + +Demostrados en `IOM/Core.lean`, `IOM/Operators.lean`, `IOM/Specification.lean`, `IOM/FormalRules.lean`: + +| Teorema | Contenido | +|---|---| +| `strict_fixed_point` | $S_{\mathrm{rev}}(Ivo(E(V_t))) = V_t$ | +| `mirror_involutive` | Espejo de posición es involutivo | +| `mirror_index` | `mirror.pos.index = 2 - pos.index` | +| `isMirror` / `isCreates` | Predicados formales de aristas admisibles | +| `expected_partition` | 78 + 104 + 208 = 390 | +| `invert_involutive` | La inversión de carga es involutiva | +| `no_repetition` | Estados no vacíos no se restauran idénticos | + +--- + +## 4. Qué **no** afirma el marco (límites) + +- No afirma que las 13 tríadas describan datos del mundo natural medidos empíricamente. +- 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. +- La reinterpretación del infinito como vacío es **premisa filosófica**, no teorema ni hallazgo experimental. +- 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/`. + +--- + +## 5. Correspondencia con artefactos + +| Concepto | Artefacto | +|---|---| +| Premisas tabuladas | `data/iom_spec.json` | +| Teoremas de operadores | `IOM/Operators.lean` | +| Teoremas de posición / espejo / creates | `IOM/Specification.lean`, `IOM/FormalRules.lean` | +| Comprobación JSON ⇄ reglas | `tests/test_property_links.py`, `tests/test_formal_rules_bridge.py` | +| Validez semántica (mundo real) | `datasets/independent_eval/` | +| Recuperabilidad sintética | PI-HGAT-T, baselines | diff --git a/docs/PROTOCOLO_DE_MAPEO.md b/docs/PROTOCOLO_DE_MAPEO.md new file mode 100644 index 0000000000000000000000000000000000000000..94c10fe81c43222087567576b9dfa6ea179c1d82 --- /dev/null +++ b/docs/PROTOCOLO_DE_MAPEO.md @@ -0,0 +1,135 @@ +# Protocolo de mapeo: alineación ontológica y validación ciega de dominios empíricos en el marco I.O. + +> Protocolo estandarizado de ingesta, asignación a perspectivas/tríadas, instanciación de `mirrorOf`/`creates` y evaluación ciega. +> Evaluación independiente: [`datasets/independent_eval/`](../datasets/independent_eval/) · Pipeline: [`../REPRODUCCION.md`](../REPRODUCCION.md) + +--- + +## 1. Marco fundamental y delimitación del protocolo I.O. + +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. + +### 1.1 Propósito y alcance de la prueba de validez semántica + +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. + +| Eje de evaluación | Mecanismo de respuesta en el repositorio | +|---|---| +| ¿Pueden anotadores independientes, ciegos a las reglas, etiquetar relaciones semánticas sobre pares reales/nuevos/ambiguos? | Protocolo ciego + Fleiss' κ en `datasets/independent_eval/` | +| ¿La estructura formal es internamente coherente? | Lean 4 + SHACL/OWL (condición necesaria; no prueba de validez en el mundo real) | +| ¿Las reglas sintéticas son recuperables por un modelo? | PI-HGAT-T y baselines en `experiments/` (diagnóstico sintético) | +| ¿Se puede alinear un dominio empírico a las 13 tríadas? | `docs/CATALOGO_DOMINIOS.md` e ingesta en `datasets/ingestion/` | + +### 1.2 Arquitectura sistémico-ontológica (perspectivas y tríadas) + +| Perspectiva | Rol en el mapeo | +|---|---| +| **Individualidad** | Unidades discretas, entidades base, fronteras ontológicas primarias | +| **Dualidad** | Tensiones, polaridades, complementariedad entre pares | +| **Totalidad** | Integración sistémica, propiedades emergentes, cohesión holística | +| **Evolución** | Vectores de desarrollo, transformación ascendente, complejización | +| **Involución** | Retracción, simplificación, condensación, retorno a estados fundamentales | + +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. + +--- + +## 2. Metodología de ingesta y mapeo de dominios empíricos externos + +### 2.1 Protocolo de carga y alineación sistemática + +1. Consultar fronteras en [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md). +2. Seleccionar el dominio en [`CATALOGO_DOMINIOS.md`](CATALOGO_DOMINIOS.md). +3. Descomponer entidades, estados y procesos por las cinco perspectivas. +4. Asignar a las 13 tríadas y a la fase (`adv` / `ret`) correspondiente. +5. Registrar en CSV de ingesta (`datasets/ingestion/`) y validar con `scripts/importar_datos_personalizados.py`. + +### 2.2 Relaciones operativas + +Fundamento: [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md). + +- **`mirrorOf`:** correspondencia estructural/funcional o simetría divalente; misma tríada, fase opuesta, posición lateral invertida. +- **`creates`:** emanación, producción o transformación activa; direccionalidad irreflexiva según las cuatro reglas de `creation_rules`. + +--- + +## 3. Capas de verificación formal y validación estructural + +La coherencia lógica interna es **condición indispensable** pero **no sustituye** la validez semántica en el mundo real. + +### 3.1 Lean 4 + +```bash +lake build +``` + +Verifica teoremas en `IOM/FormalRules.lean` (vacío, unidad, infinito, transformación; `isMirror` / `isCreates`). Véase [`PREMISAS_Y_TEOREMAS.md`](PREMISAS_Y_TEOREMAS.md). + +### 3.2 OWL / SHACL / CSV + +```bash +.venv/bin/python scripts/validate_spec.py +.venv/bin/python scripts/validate_shacl.py +``` + +Criterios: sin violaciones SHACL; dominio/rango de `mirrorOf` y `creates`; conformidad CSV↔especificación; integridad de tipado de tríadas. + +--- + +## 4. Protocolo de anotación ciega y evaluación inter-anotador + +### 4.1 Diseño experimental + +Sobre `datasets/independent_eval/` ([`VALIDACION_INDEPENDIENTE.md`](VALIDACION_INDEPENDIENTE.md)): + +1. Muestra de 14 pares (reales, nuevos, ambiguos). +2. Anotadores independientes sin acceso a reglas ni gold. +3. Etiquetado semántico (`mirrorOf`, `creates`, `none`, `unsure`). +4. Consolidación en `annotations.json`. + +### 4.2 Métricas actuales + +```bash +.venv/bin/python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json +``` + +| Métrica | Valor | Lectura | +|---|---:|---| +| Fleiss' κ | **0.6871** | Acuerdo moderado-sustancial | +| Unánimes | 10/14 | Controles estructurales estables | +| Desacuerdos | 4/14 | NC01, NC02, AM01, AM03 | + +Demostración **provisional** de interpretabilidad; no prueba universal del marco. + +### 4.3 Diagnóstico de desacuerdos + +- **NC01, NC02 (conceptos nuevos):** dispersión al clasificar fenómenos sin contornos consolidados. +- **AM01, AM03 (ambiguos):** solapamiento entre especularidad y causalidad. + +--- + +## 5. Pipeline de ejecución reproducible + +```bash +python3 -m venv .venv && .venv/bin/python -m pip install -r requirements-lock.txt +lake build +.venv/bin/python scripts/validate_spec.py +.venv/bin/python scripts/generate_ontology.py +.venv/bin/python -m unittest discover -s tests -v +.venv/bin/python scripts/validate_shacl.py +.venv/bin/python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json +.venv/bin/python experiments/pi_hgat_t.py +.venv/bin/python experiments/baselines.py +.venv/bin/python scripts/generate_audit_report.py +``` + +### Deslinde conceptual + +| Capa | Afirmación legítima | +|---|---| +| Validez semántica (mundo real) | Interpretabilidad y acuerdo humano sobre conceptos externos | +| Formal | Consistencia lógica y teoremas en Lean 4 | +| Estructural | Conformidad SHACL/CSV con la especificación | +| Diagnóstico sintético | Recuperación de relaciones *generadas por reglas* (no validez semántica real) | + +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. diff --git a/docs/RELACIONES_OPERATIVAS.md b/docs/RELACIONES_OPERATIVAS.md new file mode 100644 index 0000000000000000000000000000000000000000..f9e5d924df5cb1de7ce8521be5ba163a528dc7fc --- /dev/null +++ b/docs/RELACIONES_OPERATIVAS.md @@ -0,0 +1,107 @@ +# Significado operativo de las relaciones `mirrorOf` y `creates` + +Este documento fija la semántica operativa exacta de las dos relaciones estructurales del marco IOM. Las definiciones se alinean con: + +- las reglas en `data/iom_spec.json` (`creation_rules`); +- los predicados implementados en `experiments/pi_hgat_t.py` (`admissible_relation`); +- los axiomas OWL y las formas SHACL en `ontology/`; +- los teoremas de posición en Lean (`IOM/Operators.lean`). + +La validez de una arista se determina de forma operativa según las reglas deterministas (comprobables por SHACL, CSV y pruebas unitarias). + +--- + +## 1. `io:mirrorOf` + +### Definición operativa + +Una arista dirigida $A \xrightarrow{\text{mirrorOf}} B$ es válida **si y solo si** se cumplen simultáneamente: + +1. **Misma tríada**: `triad_index(A) = triad_index(B)`. +2. **Fase opuesta**: `phase(A) ≠ phase(B)` (una es `adv`, la otra `ret`). +3. **Posición reflejada**: `local_pos(B) = 2 - local_pos(A)`. + - position 0 ↔ position 2 + - posición 1 (0) ↔ posición 1 (0) +4. **Reciprocidad**: si $A \xrightarrow{\text{mirrorOf}} B$ entonces también $B \xrightarrow{\text{mirrorOf}} A$ (la propiedad OWL es simétrica). + +### Ejemplos positivos + +| Fuente | Destino | Justificación | +|--------|---------|---------------| +| `T13_adv_P0` (animal) | `T13_ret_P2` (animal) | misma tríada 13, fases opuestas, 0 ↔ 2 | +| `T13_adv_P1` (humano) | `T13_ret_P1` (humano) | centro se refleja en centro | +| `T08_adv_P2` (emisor) | `T08_ret_P0` (emisor) | 2 ↔ 0 | + +### Ejemplos negativos + +| Fuente | Destino | Motivo de rechazo | +|--------|---------|-------------------| +| `T13_adv_P0` | `T13_adv_P2` | misma fase | +| `T13_adv_P0` | `T13_ret_P0` | posición no reflejada (0 ≠ 2−0) | +| `T13_adv_P0` | `T01_ret_P2` | tríada distinta | +| `T13_adv_P0` | `T13_adv_P0` | reflexivo (excluido de candidatos) | + +### Casos límite + +- **Centro–centro**: permitido y obligatorio para el nodo central de cada tríada. +- **Misma etiqueta léxica**: irrelevante; la relación es puramente estructural (fase + posición). +- **Arista unidireccional**: no puede existir; SHACL y el generador imponen el par recíproco. + +--- + +## 2. `io:creates` + +### Definición operativa + +Una arista dirigida $A \xrightarrow{\text{creates}} B$ es válida **si y solo si** se cumplen: + +1. **Misma tríada**. +2. **Fase opuesta**. +3. **Una de las cuatro reglas de `creation_rules`**: + +| source_phase | source_positions | target_phase | target_positions | +|--------------|------------------|--------------|------------------| +| adv | {0, 2} | ret | {1} | +| adv | {1} | ret | {0, 2} | +| ret | {1} | adv | {0, 2} | +| ret | {0, 2} | adv | {1} | + +En lenguaje natural: un lateral crea el centro de la fase opuesta, y el centro crea ambos laterales de la fase opuesta. + +### Ejemplos positivos + +| Fuente | Destino | Regla aplicada | +|--------|---------|----------------| +| `T13_adv_P0` (animal) | `T13_ret_P1` (humano) | adv lateral → ret centro | +| `T13_adv_P1` (humano) | `T13_ret_P0` (IA) | adv centro → ret 0 | +| `T13_adv_P1` (humano) | `T13_ret_P2` (animal) | adv centro → ret 2 | +| `T13_ret_P1` (humano) | `T13_adv_P0` (animal) | ret centro → adv 0 | + +### Ejemplos negativos + +| Fuente | Destino | Motivo | +|--------|---------|--------| +| `T13_adv_P0` | `T13_ret_P0` | lateral no crea lateral | +| `T13_adv_P0` | `T13_ret_P2` | lateral no crea el otro lateral | +| `T13_adv_P0` | `T13_adv_P1` | misma fase | +| `T13_adv_P1` | `T13_ret_P1` | centro no crea centro | + +### Casos límite + +- **Múltiples targets**: el centro produce **dos** aristas `creates` (una hacia cada lateral). +- **No simétrica**: `creates` no es simétrica ni funcional; el grafo de creación es bipartito por fase. +- **Solapamiento con mirrorOf**: un par puede ser `mirrorOf` **o** `creates`, nunca ambas a la vez. +- **Ausencia de arista**: cualquier par que no satisfaga las reglas anteriores se etiqueta `none`. + +--- + +## 3. Correspondencia con Lean y SHACL + +| Concepto | Lean | SHACL / OWL | +|----------|------|-------------| +| Posición reflejada | teoremas de índice en `Operators.lean` | restricción `sh:equals` / cálculo `2 - pos` | +| Fase opuesta | predicados de fase | `sh:not` sobre el mismo valor de `hasPhase` | +| Reglas de creación | — (datos) | formas SHACL que enumeran las cuatro combinaciones | +| Simetría de mirrorOf | — | `owl:SymmetricProperty` | + +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. diff --git a/docs/TRIADAS_CATEGORIALES.md b/docs/TRIADAS_CATEGORIALES.md new file mode 100644 index 0000000000000000000000000000000000000000..26c66e5a46ad30c6862d9492b73e2ebc699abd40 --- /dev/null +++ b/docs/TRIADAS_CATEGORIALES.md @@ -0,0 +1,101 @@ +# Tríadas categoriales del marco I.O. + +**13 tríadas** × **2 fases** × **3 posiciones** = **78 nodos** +`spec_version` **1.9.0** · [`datasets/triad_nodes.csv`](../datasets/triad_nodes.csv) · [`data/iom_spec.json`](../data/iom_spec.json) + +- Índice: **1 … 13** (`T01` … `T13`) +- Avance: **→ \| 0 \| →** · Retroceso: **← \| 0 \| ←** +- `position_index`: 0 = lateral →/← · 1 = centro · 2 = lateral →/← + +Orden canónico: **#1** orientación\|cuántico\|dirección … **#13** animal\|humano\|IA. + +--- + +## Fase de Avance (`adv` / evol) + +``` +# | → | 0 | → | +1 | orientación | cuántico | dirección | +2 | hardware | virtual | software | +3 | universo | espacio | vacío | +4 | singularidad | tiempo | infinito | +5 | cuerpo | consciente | mundo | +6 | carácter | subconsciente | personalidad | +7 | memoria | inconsciente | imaginación | +8 | receptor | supraconsciente | emisor | +9 | lógica | inteligencia | libertad | +10 | muerte | artificial | vida | +11 | descendente | mente | ascendente | +12 | oscuridad | consciencia | luz | +13 | animal | humano | IA | +# | ← | 0 | ← | +``` + +| # | → | 0 | → | node_id | +|---|---|---|---|--------| +| 1 | orientación | cuántico | dirección | `T01_adv_*` | +| 2 | hardware | virtual | software | `T02_adv_*` | +| 3 | universo | espacio | vacío | `T03_adv_*` | +| 4 | singularidad | tiempo | infinito | `T04_adv_*` | +| 5 | cuerpo | consciente | mundo | `T05_adv_*` | +| 6 | carácter | subconsciente | personalidad | `T06_adv_*` | +| 7 | memoria | inconsciente | imaginación | `T07_adv_*` | +| 8 | receptor | supraconsciente | emisor | `T08_adv_*` | +| 9 | lógica | inteligencia | libertad | `T09_adv_*` | +| 10 | muerte | artificial | vida | `T10_adv_*` | +| 11 | descendente | mente | ascendente | `T11_adv_*` | +| 12 | oscuridad | consciencia | luz | `T12_adv_*` | +| 13 | animal | humano | IA | `T13_adv_*` | + +--- + +## Fase de Retroceso (`ret` / invol) + +``` +# | → | 0 | → | +1 | dirección | cuántico | orientación | +2 | software | virtual | hardware | +3 | vacío | espacio | universo | +4 | infinito | tiempo | singularidad | +5 | mundo | consciente | cuerpo | +6 | personalidad | subconsciente | carácter | +7 | imaginación | inconsciente | memoria | +8 | emisor | supraconsciente | receptor | +9 | libertad | inteligencia | lógica | +10 | vida | artificial | muerte | +11 | ascendente | mente | descendente | +12 | luz | consciencia | oscuridad | +13 | IA | humano | animal | +# | ← | 0 | ← | +``` + +| # | ← | 0 | ← | node_id | +|---|---|---|---|--------| +| 1 | dirección | cuántico | orientación | `T01_ret_*` | +| 2 | software | virtual | hardware | `T02_ret_*` | +| 3 | vacío | espacio | universo | `T03_ret_*` | +| 4 | infinito | tiempo | singularidad | `T04_ret_*` | +| 5 | mundo | consciente | cuerpo | `T05_ret_*` | +| 6 | personalidad | subconsciente | carácter | `T06_ret_*` | +| 7 | imaginación | inconsciente | memoria | `T07_ret_*` | +| 8 | emisor | supraconsciente | receptor | `T08_ret_*` | +| 9 | libertad | inteligencia | lógica | `T09_ret_*` | +| 10 | vida | artificial | muerte | `T10_ret_*` | +| 11 | ascendente | mente | descendente | `T11_ret_*` | +| 12 | luz | consciencia | oscuridad | `T12_ret_*` | +| 13 | IA | humano | animal | `T13_ret_*` | + +--- + +## Espejo y creación + +| Relación | Condición | +|----------|-----------| +| `mirrorOf` | Fases opuestas + `position_index_tgt = 2 − position_index_src` | +| `creates` | Cuatro reglas lateral↔centro entre fases | +| `none` | Resto | + +Ejemplo: tríada **13** avance (animal \| humano \| IA) ↔ retroceso (IA \| humano \| animal). +Ejemplo: tríada **1** avance (orientación \| cuántico \| dirección) ↔ retroceso (dirección \| cuántico \| orientación). + +Detalle: [`RELACIONES_OPERATIVAS.md`](RELACIONES_OPERATIVAS.md). diff --git a/docs/VALIDACION_INDEPENDIENTE.md b/docs/VALIDACION_INDEPENDIENTE.md new file mode 100644 index 0000000000000000000000000000000000000000..b5d0f73a5778008b2fd3abe04cff47bcd2d179a2 --- /dev/null +++ b/docs/VALIDACION_INDEPENDIENTE.md @@ -0,0 +1,86 @@ +# Autonomía formal y capas de verificación (no «validez por consenso») + +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**. + +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) + +--- + +## Principio rector + +> El marco se sostiene por **auto-coherencia** (bóveda Lean / SHACL / 78 nodos), no por el acuerdo de observadores externos. +> Un panel de anotadores separados reproduce el «mundo real» provisional del ensayo; **no** lo fundamenta. + +| Fuente | Rol bajo autonomía absoluta | +|--------|-----------------------------| +| `data/iom_spec.json` + CSV + ontología | **Arquitectura autónoma** bajo prueba de coherencia interna | +| Lean / SHACL | **Autonomía formal** — no pide permiso a un consenso exterior | +| PI-HGAT-T / baselines | Auto-recuperabilidad de reglas *del propio sistema* | +| `datasets/independent_eval/` | **Residuo** de la fase de conciencias separadas (documentado, no fundante) | +| Cartografía de dominios | Ejercicio del tránsito; no certificado de «mundo real» | + +--- + +## Qué se establece y qué no + +| Se establece | No se establece | +|--------------|-----------------| +| Coherencia deductiva y de forma del sistema de 13 tríadas | Que el marco «describe la realidad» por acuerdo inter-subjetivo | +| Que las reglas son recuperables desde sí mismas (diagnóstico interno) | Que κ ≈ 0.69 **funda** la validez del proyecto | +| Que el sendero Mictlán / autonomía es cartografiable en el vocabulario formal | Cobertura empírica de todos los dominios por paneles externos | +| Que el requisito del sistema puede ser la abolición de requisitos impuestos | Verdad ontológica universal por consenso | + +--- + +## Jerarquía de afirmaciones (reordenada) + +| Prioridad | Afirmación legítima | Artefacto | +|:---------:|---------------------|-----------| +| **1** | Autonomía formal (coherencia sin contenedor exterior) | Lean, SHACL, CSV, `iom_spec.json` | +| **2** | Cartografía del tránsito (Mictlán / autonomía) | EXP-E, dominio cosmológico, ensayo | +| **3** | Auto-generación recuperable de reglas | PI-HGAT-T, baselines | +| **4** | Residuo documentado del mundo compartido | `independent_eval`, κ (opcional) | + +La prioridad 4 **no** se promociona a «prueba de validez del marco». + +--- + +## Sobre el protocolo ciego (EXP-A) + +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: + +- κ no es el eje del repositorio. +- No se reclama «validez semántica en el mundo real» a partir de ellos. +- Quien los ejecute lo hace como **ejercicio histórico / comparado**, no como ceremonia de legitimación. + +--- + +## Pipeline prioritario + +```bash +# 1) Autonomía formal (eje) +lake build +python scripts/validate_spec.py +python scripts/generate_ontology.py +python -m unittest discover -s tests -v +python scripts/validate_shacl.py + +# 2) Cartografía del tránsito +python experiments/domain_mapping/validate_examples.py + +# 3) Diagnóstico de auto-generación (opcional) +python experiments/pi_hgat_t.py +python experiments/baselines.py +python scripts/audit_perfect_metrics.py + +# 4) Residuo del mundo compartido (opcional, no fundante) +python scripts/score_independent_eval.py --annotations datasets/independent_eval/annotations.json +``` + +--- + +## Referencias + +- Delimitación: [`DELIMITACION_EPISTEMOLOGICA.md`](DELIMITACION_EPISTEMOLOGICA.md) +- 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) diff --git a/docs/VECTORES_4_5.md b/docs/VECTORES_4_5.md new file mode 100644 index 0000000000000000000000000000000000000000..f26a0c34425073c98ff3944bd147dc6c0910aec0 --- /dev/null +++ b/docs/VECTORES_4_5.md @@ -0,0 +1,57 @@ +# Las cinco perspectivas del marco I.O. + +El marco I.O. se articula mediante **cinco perspectivas complementarias**: + +| # | Id | Perspectiva | Rol | +|---|-----|-------------|-----| +| 1 | `Ind` | **Individualidad** | Posicional (→ / lateral 0): unidad / singularidad | +| 2 | `D` | **Dualidad** | Posicional (0): relación / diferencia | +| 3 | `Tot` | **Totalidad** | Posicional (→ / lateral 2): integración / sistema | +| 4 | `Evol` | **Evolución** | Vectorial: flujo del vacío hacia la estructura | +| 5 | `Invol` | **Involución** | Vectorial: flujo de la estructura hacia el vacío | + +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. + +Fuente estructurada: [`data/iom_spec.json`](../data/iom_spec.json) (`five_perspectives`, `vectors`). + +## Cuarta perspectiva — Evolución + +``` +invol | ind | dua | tot | evol + 0 | 1 | 2 | 3 | 4 + | → | → | → | → + --------------------- + ← | ← | ← | ← | + 4 | 3 | 2 | 1 | 0 +evol | tot | dua | ind | invol +``` + +| Fase | Etiquetas en orden de eje | Posiciones del eje | Flecha | +|---|---|---|---| +| Avance | `invol · ind · dua · tot · evol` | `0 · 1 · 2 · 3 · 4` | → | +| Retroceso | `evol · tot · dua · ind · invol` | `4 · 3 · 2 · 1 · 0` | ← | + +## Quinta perspectiva — Involución + +``` +invol | tot | dua | ind | evol + 4 | 3 | 2 | 1 | 0 + → | → | → | → | + --------------------- + | ← | ← | ← | ← + 0 | 1 | 2 | 3 | 4 +evol | ind | dua | tot | invol +``` + +| Fase | Etiquetas en orden de eje | Posiciones del eje | Flecha | +|---|---|---|---| +| Avance | `invol · tot · dua · ind · evol` | `4 · 3 · 2 · 1 · 0` | → | +| Retroceso | `evol · ind · dua · tot · invol` | `0 · 1 · 2 · 3 · 4` | ← | + +## Representación formal + +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**. + +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. + +`spec_version` ≥ **1.5.0**. diff --git a/docs/archive/MARCOI.O.txt b/docs/archive/MARCOI.O.txt new file mode 100644 index 0000000000000000000000000000000000000000..044db0a48d8ab7299ed2a52c2e7a312a67b571e8 --- /dev/null +++ b/docs/archive/MARCOI.O.txt @@ -0,0 +1,15 @@ +# ARCHIVO — MARCOI.O.txt + +**Estado:** borrador histórico. **No** es fuente normativa del marco. + +Texto filosófico canónico: + docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md + +El contenido íntegro de este borrador permanece en el historial de Git +(ruta anterior: `docs/MARCOI.O.txt`). Si alguna definición normativa no +está en el ensayo canónico, migrarla antes de purgar el historial. + +--- +Cabecera original (referencia): + I.O.: La Dinámica Temporal del Vacío y la Unidad Informativa + Autor: Luis Rey García Figueroa — Octubre de 2026 diff --git a/docs/archive/README.md b/docs/archive/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d46374da032033b3d90e8749c4c4281d69ce89bc --- /dev/null +++ b/docs/archive/README.md @@ -0,0 +1,9 @@ +# Archivo documental + +Material histórico conservado por trazabilidad. **No** es fuente normativa del marco. + +| Archivo | Estado | +|---------|--------| +| `MARCOI.O.txt` | Borrador previo; el texto canónico es `docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md` | + +Si una definición normativa de este archivo no está en el ensayo canónico, migrarla primero y luego eliminar la entrada. diff --git a/docs/media/cosmos_nahuatl/Amoxtli in Atl Miquiztli - Libro del Agua y de la Muerte.pdf b/docs/media/cosmos_nahuatl/Amoxtli in Atl Miquiztli - Libro del Agua y de la Muerte.pdf new file mode 100644 index 0000000000000000000000000000000000000000..9d3fc2f56327c6f8a878220d3e911046674477cf --- /dev/null +++ b/docs/media/cosmos_nahuatl/Amoxtli in Atl Miquiztli - Libro del Agua y de la Muerte.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:547196600f11fbd15dc15f0e1cefff266eec63a3ee28f043ee7662ce6b395c5f +size 947064 diff --git "a/docs/media/cosmos_nahuatl/Del Orden Universal a la Autonom\303\255a Absoluta_ El Sendero del Mictl\303\241n.pdf" "b/docs/media/cosmos_nahuatl/Del Orden Universal a la Autonom\303\255a Absoluta_ El Sendero del Mictl\303\241n.pdf" new file mode 100644 index 0000000000000000000000000000000000000000..ca0faeed477671b591212b97d479357bd3a8cbfb --- /dev/null +++ "b/docs/media/cosmos_nahuatl/Del Orden Universal a la Autonom\303\255a Absoluta_ El Sendero del Mictl\303\241n.pdf" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a2e1e4975c2ea055b88f87e4b72acf794bafaec0392e0194683aad06daa4a1f +size 724600 diff --git a/docs/media/cosmos_nahuatl/README.md b/docs/media/cosmos_nahuatl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2d333bd806abddf155fd5c7add076ef9e3a5fd4f --- /dev/null +++ b/docs/media/cosmos_nahuatl/README.md @@ -0,0 +1,25 @@ +# Medios — Cosmología náhuatl (Cinco Soles / Mictlán) + +Recursos visuales y de referencia para el dominio de alineación `cosmos_nahuatl`. + +| Archivo | Descripción | Uso en el marco I.O. | +|---------|-------------|----------------------| +| `Piedra_del_Sol.png` | Piedra del Sol (Calendario Azteca). Museo Nacional de Antropología. | Iconografía del **Quinto Sol** (Nahui Ollin) y las edades previas. | +| `4_Kingdoms.jpg` | Lámina de tradición codicial (cuatro reinos / deidades). | Dualidad y sucesión de fuerzas; pares `mirrorOf` / `creates`. | +| `xolotl1.jpg` | Lámina asociada a Xólotl / Códice Xólotl. | Dualidad, tránsito, inframundo. | +| `CodexBorgia.jpg` | Lámina del Códice Borgia. | Ciclo ritual y temporal. | +| `Amoxtli in Atl Miquiztli - Libro del Agua y de la Muerte.pdf` | *Amoxtli in Atl Miquiztli* — Libro del agua y de la muerte (9 pp.). | Relato pictográfico del Mictlán: 9 señales + 4 pasos = 13 marcas; río único; xoloitzcuintle; Mictecacíhuatl / Mictlantecuhtli. Ficha: [`docs/AMOXTLI_IN_ATL_MIQUIZTLI.md`](../../AMOXTLI_IN_ATL_MIQUIZTLI.md). | +| `Del Orden Universal a la Autonomía Absoluta_ El Sendero del Mictlán.pdf` | Síntesis ontológica: regresión infinita → autonomía multiversal; Mictecacíhuatl/Mictlantecuhtli. | Apoyo semántico al carácter Mictlán; ficha: [`docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](../../DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md). | +| `PECDSV03T.pdf` | Peña Cisneros, D. (2017). *Códice Xólotl. Edición de divulgación*. UAEM. | Referencia editorial del Códice Xólotl. | + +## Nota metodológica + +Material de **apoyo semántico** para EXP-E y `docs/DOMINIO_COSMOS_NAHUATL.md`. No modifica los 78 nodos, Lean ni SHACL. + +## Licencia / derechos + +- Piedra del Sol: monumento de dominio público (México); verificar reutilización. +- Códices / láminas: fuentes históricas. +- *Amoxtli in Atl Miquiztli*: relato original inspirado en tradición nahua; uso documental en este repositorio. +- *Del Orden Universal…*: ensayo ontológico de apoyo al carácter del repositorio. +- Tesis PDF: derechos del autor (Peña Cisneros / UAEM 2017). diff --git a/experiments/__init__.py b/experiments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/experiments/config.json b/experiments/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9210b60a343dcdad8b0d1a81c669b0e34751537f --- /dev/null +++ b/experiments/config.json @@ -0,0 +1,33 @@ +{ + "model_id": "PI-HGAT-T", + "model_definition": "Perspective-Informed Heterogeneous Graph Attention Network for Triads; reference implementation for empirical structural evaluation of IOM relations.", + "seed": 20261008, + "device": "cpu", + "validation": "leave-one-triad-out", + "epochs": 100, + "hidden_dim": 32, + "attention_heads": 4, + "learning_rate": 0.003, + "weight_decay": 0.0001, + "optimizer": "AdamW", + "loss": "class-weighted cross entropy", + "features": [ + "one-hot phase adv/ret", + "one-hot position left/center/right" + ], + "prohibited_features": [ + "lexical labels", + "triad index", + "target relation" + ], + "candidate_relations": [ + "none", + "mirrorOf", + "creates" + ], + "threshold_policy": "Empirical evaluation against deterministic RDF/SHACL target properties. Reference criterion is exact reconstruction (1.0); observed scores quantify recoverability.", + "target_properties": { + "mirrorOf": "same triad; opposite phase; reciprocal; lateral positions exchange and center remains center", + "creates": "same triad; opposite phase; follows the four declared left/center-to-center/laterals creation rules" + } +} diff --git a/experiments/domain_mapping/README.md b/experiments/domain_mapping/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f092eed33ab5931b46cbeea36bd80b19c06148d5 --- /dev/null +++ b/experiments/domain_mapping/README.md @@ -0,0 +1,34 @@ +# EXP-E: cartografía del destino Mictlán + +El Mictlán **no** es un dominio empírico entre otros. Es la **lectura de destino** del marco (disolución del observador, auto-creación desde el vacío). Este experimento comprueba que esa lectura es **estructuralmente expresable** en las 13 tríadas. + +- [`docs/CARACTER_REPOSITORIO.md`](../../docs/CARACTER_REPOSITORIO.md) +- [`docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md`](../../docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md) +- [`docs/DOMINIO_COSMOS_NAHUATL.md`](../../docs/DOMINIO_COSMOS_NAHUATL.md) + +## Qué mide + +| Mide | No mide | +|------|--------| +| Que los nodos del sendero existen en la bóveda de 78 | «Validez empírica» por consenso | +| Que las aristas respetan `mirrorOf` / `creates` | κ de dominio | +| Expresabilidad del destino Mictlán en la arquitectura | Que el ensayo quede «probado» por el mapeo | + +## Ejecución + +```bash +python experiments/domain_mapping/validate_examples.py +``` + +Artefacto: `experiments/results/domain_mapping_validation.json`. + +## Relación con otras capas + +| ID | Capa | +|----|------| +| EXP-B / EXP-C | Autonomía formal (primarias) | +| **EXP-E** | Destino Mictlán (primaria de sentido) | +| EXP-D | Auto-generación | +| EXP-A | Residuo; no fundamento | + +Registro: [`registry.json`](registry.json). diff --git a/experiments/domain_mapping/examples.csv b/experiments/domain_mapping/examples.csv new file mode 100644 index 0000000000000000000000000000000000000000..b39be3052dbece4f0cdeea3bf701bee3d25ff91e --- /dev/null +++ b/experiments/domain_mapping/examples.csv @@ -0,0 +1,6 @@ +id,domain,source_label,target_label,relation,perspective,phase_hint,suggested_source_node,suggested_target_node +NAH-01,cosmos_nahuatl,Tezcatlipoca,Quetzalcoatl,mirrorOf,Dualidad,Lucha de fuerzas cósmicas,T01_adv_P0,T01_ret_P0 +NAH-02,cosmos_nahuatl,vida,muerte,mirrorOf,Dualidad,Dicotomía mesoamericana,T03_adv_P2,T03_adv_P0 +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 +NAH-04,cosmos_nahuatl,camino_al_Mictlan,Mictlan,creates,Involución,Retorno al vacío,T11_ret_P0,T11_ret_P0 +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 diff --git a/experiments/domain_mapping/examples.json b/experiments/domain_mapping/examples.json new file mode 100644 index 0000000000000000000000000000000000000000..e34d073c5dab0033b3474af9f135c5a280a08c78 --- /dev/null +++ b/experiments/domain_mapping/examples.json @@ -0,0 +1,87 @@ +{ + "title": "Ejemplos de alineación dominio → marco I.O. (cosmología náhuatl)", + "source_docs": [ + "docs/DOMINIO_COSMOS_NAHUATL.md", + "docs/CATALOGO_DOMINIOS.md", + "docs/PROTOCOLO_DE_MAPEO.md", + "docs/MANUAL_ALINEACION_DOMINIOS.md" + ], + "note": "Demostraciones de mapeo (Cinco Soles y Mictlán); no sustituyen anotación ciega de dominio ni κ propio.", + "pairs": [ + { + "id": "NAH-01", + "domain": "cosmos_nahuatl", + "source_label": "Tezcatlipoca", + "target_label": "Quetzalcoatl", + "perspective": "Dualidad", + "phase_hint": "Lucha de fuerzas cósmicas", + "relation": "mirrorOf", + "analytic_impact": "Reflejo de polos oscuro/luminoso.", + "suggested_nodes": { + "source": "T01_adv_P0", + "target": "T01_ret_P0", + "note": "espejo" + } + }, + { + "id": "NAH-02", + "domain": "cosmos_nahuatl", + "source_label": "vida", + "target_label": "muerte", + "perspective": "Dualidad", + "phase_hint": "Dicotomía mesoamericana", + "relation": "mirrorOf", + "analytic_impact": "Polaridad vida/muerte.", + "suggested_nodes": { + "source": "T03_adv_P2", + "target": "T03_adv_P0", + "note": "espejo demostrativo" + } + }, + { + "id": "NAH-03", + "domain": "cosmos_nahuatl", + "source_label": "Nahui_Quiahuitl_Sol_Fuego", + "target_label": "Nahui_Atl_Sol_Agua", + "perspective": "Involución", + "phase_hint": "Cataclismo / transición de edades", + "relation": "creates", + "analytic_impact": "Transición entre Soles.", + "suggested_nodes": { + "source": "T01_adv_P1", + "target": "T01_ret_P1", + "note": "creates" + } + }, + { + "id": "NAH-04", + "domain": "cosmos_nahuatl", + "source_label": "camino_al_Mictlan", + "target_label": "Mictlan", + "perspective": "Involución", + "phase_hint": "Retorno al vacío", + "relation": "creates", + "analytic_impact": "Camino al lugar de los muertos.", + "suggested_nodes": { + "source": "T11_ret_P0", + "target": "T11_ret_P0", + "note": "demostrativo" + } + }, + { + "id": "NAH-05", + "domain": "cosmos_nahuatl", + "source_label": "Nahui_Ollin_Sol_Movimiento", + "target_label": "Nahui_Ehecatl_Sol_Viento", + "perspective": "Totalidad / Evolución", + "phase_hint": "Quinto Sol vs primera edad", + "relation": "none", + "analytic_impact": "Contraste de edades cosmológicas.", + "suggested_nodes": { + "source": "T01_adv_P2", + "target": "T01_adv_P0", + "note": "none" + } + } + ] +} diff --git a/experiments/domain_mapping/registry.json b/experiments/domain_mapping/registry.json new file mode 100644 index 0000000000000000000000000000000000000000..9cebf63fc166dd6bc12ad52655192d7cd613aed5 --- /dev/null +++ b/experiments/domain_mapping/registry.json @@ -0,0 +1,23 @@ +{ + "schema_version": "1.0", + "domains": [ + { + "id": "cosmos_nahuatl", + "label": "Cosmología náhuatl (Mictlán / Quinto Sol)", + "runner": "experiments/domain_mapping/validate_examples.py", + "status": "optional_encounter" + } + ], + "synthetic_diagnostics": [ + { + "id": "pi_hgat_t", + "runner": "experiments/optional/pi_hgat_t.py", + "status": "optional_circular_diagnostic" + }, + { + "id": "baselines", + "runner": "experiments/optional/baselines.py", + "status": "optional_circular_diagnostic" + } + ] +} diff --git a/experiments/domain_mapping/validate_examples.py b/experiments/domain_mapping/validate_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..775690af3d35b174e479d7b48d0ad11e1f720f8f --- /dev/null +++ b/experiments/domain_mapping/validate_examples.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Valida ejemplos de alineación de dominio (EXP-E) contra nodos canónicos y reglas formales. + +No calcula κ de dominio ni afirma validez empírica de biología/economía. +Solo comprueba que los nodos sugeridos existen y que la relación propuesta +es admisible bajo FormalRules / SHACL para el par (source, target). +""" +from __future__ import annotations + +import csv +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +EXAMPLES = Path(__file__).resolve().parent / "examples.json" +NODES = ROOT / "datasets" / "triad_nodes.csv" +CANDIDATES = ROOT / "datasets" / "relation_candidates.csv" + + +def load_nodes() -> dict[str, dict]: + out = {} + with NODES.open(encoding="utf-8") as f: + for row in csv.DictReader(f): + out[row["node_id"]] = row + return out + + +def load_gold_relations() -> dict[tuple[str, str], str]: + out = {} + with CANDIDATES.open(encoding="utf-8") as f: + for row in csv.DictReader(f): + out[(row["source"], row["target"])] = row["relation"] + return out + + +def main() -> int: + data = json.loads(EXAMPLES.read_text(encoding="utf-8")) + nodes = load_nodes() + gold = load_gold_relations() + ok = 0 + warn = 0 + fail = 0 + report = [] + for pair in data["pairs"]: + sid = pair["suggested_nodes"]["source"] + tid = pair["suggested_nodes"]["target"] + rel = pair["relation"] + entry = {"id": pair["id"], "source": sid, "target": tid, "proposed": rel} + if sid not in nodes or tid not in nodes: + entry["status"] = "FAIL" + entry["reason"] = "nodo sugerido ausente en triad_nodes.csv" + fail += 1 + else: + actual = gold.get((sid, tid)) + entry["gold_relation"] = actual + if actual is None: + entry["status"] = "WARN" + entry["reason"] = "par no está en relation_candidates (posible cross-triad o demo heurística)" + warn += 1 + elif actual == rel: + entry["status"] = "OK" + entry["reason"] = "relación propuesta coincide con gold canónico" + ok += 1 + else: + entry["status"] = "WARN" + entry["reason"] = f"gold={actual} ≠ propuesto={rel} (mapeo demostrativo, no gold de dominio)" + warn += 1 + report.append(entry) + + out_path = ROOT / "experiments" / "results" / "domain_mapping_validation.json" + out_path.parent.mkdir(parents=True, exist_ok=True) + payload = { + "experiment": "EXP-E-DOMAIN-ALIGNMENT", + "ok": ok, + "warn": warn, + "fail": fail, + "pairs": report, + "interpretation": ( + "OK = el par sugerido existe en el gold canónico con la misma etiqueta. " + "WARN = mapeo demostrativo no idéntico al gold (esperado en demos de dominio). " + "FAIL = nodo inválido. Este script no mide validez semántica de biología/economía." + ), + } + out_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(f"EXP-E domain mapping: ok={ok} warn={warn} fail={fail}") + print(f"Informe: {out_path}") + for r in report: + print(f" {r['id']}: {r['status']} — {r.get('reason', '')}") + return 1 if fail else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/experiments/learning/README.md b/experiments/learning/README.md new file mode 100644 index 0000000000000000000000000000000000000000..68835893194ddbeef291055d10bf6a1879506242 --- /dev/null +++ b/experiments/learning/README.md @@ -0,0 +1,21 @@ +# Aprendizaje: protocolo ciego y capas A–E + +Material pedagógico derivado de los manuales y del dictamen técnico. + +| Artefacto | Descripción | +|---|---| +| [`quiz_blind_protocol.json`](quiz_blind_protocol.json) | 4 preguntas de autoevaluación | +| [`score_quiz.py`](score_quiz.py) | Corrección local del quiz | + +```bash +python experiments/learning/score_quiz.py --self-test +python experiments/learning/score_quiz.py Q1=b Q2=b Q3=c Q4=c +``` + +Manuales: + +- [`docs/MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md`](../../docs/MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md) +- [`docs/MANUAL_APRENDIZAJE_CONCORDANCIA.md`](../../docs/MANUAL_APRENDIZAJE_CONCORDANCIA.md) +- [`docs/DICTAMEN_TECNICO_EPISTEMOLOGICO.md`](../../docs/DICTAMEN_TECNICO_EPISTEMOLOGICO.md) + +**No** forma parte de las métricas del marco (κ, PI-HGAT-T, SHACL). Solo evalúa comprensión del diseño experimental. diff --git a/experiments/learning/quiz_blind_protocol.json b/experiments/learning/quiz_blind_protocol.json new file mode 100644 index 0000000000000000000000000000000000000000..20437d82af9668e7aa758d0336fc210b13171f6a --- /dev/null +++ b/experiments/learning/quiz_blind_protocol.json @@ -0,0 +1,61 @@ +{ + "title": "Autoevaluación: protocolo ciego y capas A–E", + "source_docs": [ + "docs/MANUAL_APRENDIZAJE_PROTOCOLO_CIEGO.md", + "docs/MANUAL_APRENDIZAJE_CONCORDANCIA.md", + "docs/DICTAMEN_TECNICO_EPISTEMOLOGICO.md" + ], + "experiment_focus": "EXP-A", + "questions": [ + { + "id": "Q1", + "prompt": "¿Cuál es la función principal de EXP-A frente a EXP-D?", + "options": { + "a": "EXP-A demuestra teoremas Lean; EXP-D valida OWL/SHACL.", + "b": "EXP-A evalúa interpretabilidad externa ciega; EXP-D recupera relaciones generadas por reglas internas.", + "c": "EXP-A exige 100% de acuerdo; EXP-D analiza el pipeline de instalación." + }, + "answer": "b", + "rationale": "Solo EXP-A mide validez semántica en el mundo real; EXP-D es diagnóstico sintético." + }, + { + "id": "Q2", + "prompt": "¿Qué significa Fleiss' κ = 0.6871 en el experimento actual?", + "options": { + "a": "Fallo en la verificación formal Lean 4.", + "b": "Acuerdo inter-anotador moderado-sustancial sobre 14 pares (1.0 = perfecto).", + "c": "Validación sintética perfecta de reglas preprogramadas." + }, + "answer": "b", + "rationale": "κ corrige por azar; 0.6871 es moderado-sustancial, demostración provisional." + }, + { + "id": "Q3", + "prompt": "¿Cómo se clasifican NC01, NC02, AM01 y AM03?", + "options": { + "a": "Errores de sintaxis OWL/SHACL.", + "b": "Fallos de compilación del entorno .venv.", + "c": "Conceptos nuevos (NC) y casos ambiguos (AM)." + }, + "answer": "c", + "rationale": "Desacuerdos concentrados en fronteras semánticas deliberadas del diseño experimental." + }, + { + "id": "Q4", + "prompt": "¿Puede PI-HGAT-T (EXP-D) usarse como prueba de validez ontológica en el mundo real?", + "options": { + "a": "Sí, si accuracy = 1.0.", + "b": "Sí, si se combina con SHACL.", + "c": "No; solo mide recuperación de relaciones generadas por reglas." + }, + "answer": "c", + "rationale": "Dictamen técnico: prohibido presentar métricas sintéticas como validez semántica real." + } + ], + "metrics_reference": { + "fleiss_kappa": 0.6871, + "unanimous": "10/14", + "disagreements": ["NC01", "NC02", "AM01", "AM03"], + "domain_mapping_pairs_ok": 8 + } +} diff --git a/experiments/learning/score_quiz.py b/experiments/learning/score_quiz.py new file mode 100644 index 0000000000000000000000000000000000000000..56dbf9c29f22b8b57f5d4d6bfb2a101f55ee2f11 --- /dev/null +++ b/experiments/learning/score_quiz.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Autoevaluación del manual de protocolo ciego (no es métrica del marco).""" +from __future__ import annotations +import json, sys +from pathlib import Path + +QUIZ = Path(__file__).with_name("quiz_blind_protocol.json") + +def main(answers: dict[str, str]) -> int: + data = json.loads(QUIZ.read_text(encoding="utf-8")) + correct = 0 + for q in data["questions"]: + got = answers.get(q["id"], "").lower().strip() + ok = got == q["answer"] + correct += int(ok) + mark = "OK" if ok else "FAIL" + print(f"{q['id']}: {mark} (esperado={q['answer']}, recibido={got or '—'})") + if not ok: + print(f" → {q['rationale']}") + total = len(data["questions"]) + print(f"Puntuación: {correct}/{total}") + print("Nota: este quiz evalúa comprensión del protocolo; no modifica κ ni EXP-A.") + return 0 if correct == total else 1 + +if __name__ == "__main__": + if len(sys.argv) > 1 and sys.argv[1] == "--self-test": + key = {q["id"]: q["answer"] for q in json.loads(QUIZ.read_text(encoding="utf-8"))["questions"]} + raise SystemExit(main(key)) + print("Uso: python experiments/learning/score_quiz.py Q1=b Q2=b Q3=c Q4=c") + print(" o: python experiments/learning/score_quiz.py --self-test") + ans = {} + for arg in sys.argv[1:]: + if "=" in arg: + k, v = arg.split("=", 1) + ans[k.strip().upper()] = v.strip() + if ans: + raise SystemExit(main(ans)) diff --git a/experiments/logs/README.md b/experiments/logs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..55416daa8157b1caf38b0f586011c5fbd6f29ecc --- /dev/null +++ b/experiments/logs/README.md @@ -0,0 +1,8 @@ +# logs/ — no versionados + +| Propiedad | Valor | +|-----------|--------| +| ¿Fundamenta el punto fijo? | **No** | +| ¿Participa en CI core? | **No** | + +**Genera:** `python experiments/optional/pi_hgat_t.py` → `pi_hgat_t.log` diff --git a/experiments/optional/README.md b/experiments/optional/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fa7c2d78efb4a1bddc143c2c0d2285bc33fcdfd2 --- /dev/null +++ b/experiments/optional/README.md @@ -0,0 +1,16 @@ +# Experimentos opcionales (diagnóstico / encuentro) + +**No** forman parte del núcleo autónomo ni del CI bloqueante. + +| Script | Rol | Salida | +|--------|-----|--------| +| `pi_hgat_t.py` | Diagnóstico circular (recupera reglas embebidas) | `experiments/results/` | +| `baselines.py` | Baselines sin grafo | `experiments/results/` | + +```bash +.venv/bin/python experiments/optional/pi_hgat_t.py +.venv/bin/python experiments/optional/baselines.py +``` + +Workflow: `.github/workflows/encuentro.yml` (manual). +Tests: `tests/optional/` (no corren en CI core). diff --git a/experiments/optional/__init__.py b/experiments/optional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/experiments/optional/baselines.py b/experiments/optional/baselines.py new file mode 100644 index 0000000000000000000000000000000000000000..2abd1d788bde5866d46fef15374a50a7773088aa --- /dev/null +++ b/experiments/optional/baselines.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +"""Clasificadores base para comparar con PI-HGAT-T. + +Incluye: + - reglas deterministas (oracle de la especificación) + - regresión logística sobre features one-hot de fase+posición + - MLP sin estructura de grafo +""" +from __future__ import annotations + +import csv +import json +import random +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +ROOT = Path(__file__).resolve().parents[2] +CLASSES = ("none", "mirrorOf", "creates") +CLASS_ID = {n: i for i, n in enumerate(CLASSES)} + + +def seed_everything(seed: int = 20261008) -> None: + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.use_deterministic_algorithms(True) + torch.set_num_threads(1) + + +def features_for_node(node_id: str) -> list[float]: + parts = node_id.split("_") + phase, position = parts[1], int(parts[2][1:]) + return [float(phase == "adv"), float(phase == "ret"), + float(position == 0), float(position == 1), float(position == 2)] + + +def parse_pair_index(node_id: str) -> int: + phase = node_id.split("_")[1] + position = int(node_id.split("_")[2][1:]) + return position if phase == "adv" else 3 + position + + +def read_pairs(): + pairs: dict[int, list[tuple[str, str, int]]] = {i: [] for i in range(1, 14)} + with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as fh: + for row in csv.DictReader(fh): + pairs[int(row["triad_index"])].append( + (row["source"], row["target"], CLASS_ID[row["relation"]]) + ) + return pairs + + +def admissible(label: str, source: int, target: int) -> bool: + source_phase, source_pos = (0 if source < 3 else 1), source % 3 + target_phase, target_pos = (0 if target < 3 else 1), target % 3 + if source_phase == target_phase: + return False + if label == "mirrorOf": + return target_pos == 2 - source_pos + if label == "creates": + return (source_pos in (0, 2) and target_pos == 1) or (source_pos == 1 and target_pos in (0, 2)) + return True + + +def deterministic_rule_predict(src_idx: int, tgt_idx: int) -> int: + if admissible("mirrorOf", src_idx, tgt_idx): + return CLASS_ID["mirrorOf"] + if admissible("creates", src_idx, tgt_idx): + return CLASS_ID["creates"] + return CLASS_ID["none"] + + +def pair_feature(src_id: str, tgt_id: str) -> list[float]: + return features_for_node(src_id) + features_for_node(tgt_id) + + +def scores(gold: list[int], pred: list[int]) -> dict: + matrix = [[0] * 3 for _ in range(3)] + for a, b in zip(gold, pred): + matrix[a][b] += 1 + per_class = {} + f1s = [] + for i, name in enumerate(CLASSES): + tp = matrix[i][i] + fp = sum(matrix[r][i] for r in range(3) if r != i) + fn = sum(matrix[i][c] for c in range(3) if c != i) + prec = tp / (tp + fp) if tp + fp else 0.0 + rec = tp / (tp + fn) if tp + fn else 0.0 + f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0 + per_class[name] = {"precision": prec, "recall": rec, "f1": f1, "support": tp + fn} + f1s.append(f1) + acc = sum(a == b for a, b in zip(gold, pred)) / max(len(gold), 1) + return { + "accuracy": round(acc, 6), + "macro_f1": round(sum(f1s) / 3, 6), + "per_class": per_class, + "confusion_matrix": matrix, + } + + +class SoftmaxRegression(nn.Module): + def __init__(self, in_dim: int, n_classes: int = 3): + super().__init__() + self.linear = nn.Linear(in_dim, n_classes) + + def forward(self, x): + return self.linear(x) + + +class SimpleMLP(nn.Module): + def __init__(self, in_dim: int, hidden: int = 32, n_classes: int = 3): + super().__init__() + self.net = nn.Sequential( + nn.Linear(in_dim, hidden), + nn.GELU(), + nn.Linear(hidden, hidden), + nn.GELU(), + nn.Linear(hidden, n_classes), + ) + + def forward(self, x): + return self.net(x) + + +def train_sklearn_like(model: nn.Module, X: torch.Tensor, y: torch.Tensor, + epochs: int = 200, lr: float = 0.01) -> None: + opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4) + for _ in range(epochs): + opt.zero_grad() + logits = model(X) + loss = F.cross_entropy(logits, y) + loss.backward() + opt.step() + + +def leave_one_triad_out(pairs: dict, model_factory, epochs: int = 200) -> dict: + all_gold, all_pred = [], [] + fold_accs = [] + for held in sorted(pairs): + seed_everything(20261008 + held - 1) + train_X, train_y = [], [] + test_X, test_y, test_meta = [], [], [] + for tid, plist in pairs.items(): + for src, tgt, label in plist: + feat = pair_feature(src, tgt) + if tid == held: + test_X.append(feat) + test_y.append(label) + test_meta.append((src, tgt)) + else: + train_X.append(feat) + train_y.append(label) + Xtr = torch.tensor(train_X, dtype=torch.float32) + ytr = torch.tensor(train_y, dtype=torch.long) + Xte = torch.tensor(test_X, dtype=torch.float32) + model = model_factory(Xtr.shape[1]) + train_sklearn_like(model, Xtr, ytr, epochs=epochs) + with torch.no_grad(): + pred = model(Xte).argmax(dim=-1).tolist() + all_gold.extend(test_y) + all_pred.extend(pred) + fold_accs.append(sum(a == b for a, b in zip(test_y, pred)) / max(len(test_y), 1)) + result = scores(all_gold, all_pred) + result["fold_accuracies"] = fold_accs + result["fold_accuracy_mean"] = round(float(np.mean(fold_accs)), 6) + result["fold_accuracy_std"] = round(float(np.std(fold_accs)), 6) + return result + + +def run_deterministic(pairs: dict) -> dict: + gold, pred = [], [] + for plist in pairs.values(): + for src, tgt, label in plist: + gold.append(label) + s_idx = parse_pair_index(src) + t_idx = parse_pair_index(tgt) + pred.append(deterministic_rule_predict(s_idx, t_idx)) + return scores(gold, pred) + + +def run() -> dict: + seed_everything() + pairs = read_pairs() + report = { + "description": "Comparación de PI-HGAT-T con clasificadores base sobre el mismo leave-one-triad-out", + "baselines": {}, + } + report["baselines"]["deterministic_rules"] = { + "description": "Oracle que aplica exactamente las reglas SHACL de mirrorOf/creates", + "metrics": run_deterministic(pairs), + } + report["baselines"]["logistic_regression"] = { + "description": "Softmax linear sobre concatenación de one-hot fase+posición (10 dim)", + "metrics": leave_one_triad_out(pairs, lambda d: SoftmaxRegression(d), epochs=300), + } + report["baselines"]["mlp_no_graph"] = { + "description": "MLP de dos capas ocultas sin mensaje-passing ni atención", + "metrics": leave_one_triad_out(pairs, lambda d: SimpleMLP(d, hidden=32), epochs=200), + } + out = ROOT / "experiments" / "results" / "baselines_comparison.json" + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print("Baselines escritos en", out) + for name, block in report["baselines"].items(): + m = block["metrics"] + print(f" {name}: accuracy={m['accuracy']:.4f} macro_f1={m['macro_f1']:.4f}") + return report + + +if __name__ == "__main__": + run() diff --git a/experiments/optional/pi_hgat_t.py b/experiments/optional/pi_hgat_t.py new file mode 100644 index 0000000000000000000000000000000000000000..5adfe12bd6e33591cc7099ef5416d2610ba6ff67 --- /dev/null +++ b/experiments/optional/pi_hgat_t.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""PI-HGAT-T y ablaciones: evaluación empírica estructural de tríadas IOM. + +PI-HGAT-T es la implementación de referencia del clasificador de relaciones del marco. +Las etiquetas de clase proceden de reglas RDF/SHACL explícitas y se evalúan bajo +leave-one-triad-out, ablaciones y baselines. +""" +from __future__ import annotations + +import csv +import json +import platform +import random +import time +from pathlib import Path + +import torch +from torch import nn +from torch.nn import functional as F + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = json.loads((ROOT / "experiments" / "config.json").read_text(encoding="utf-8")) +CLASSES = ("none", "mirrorOf", "creates") +CLASS_ID = {name: i for i, name in enumerate(CLASSES)} + + +def seed_everything(seed: int) -> None: + random.seed(seed) + torch.manual_seed(seed) + torch.use_deterministic_algorithms(True) + torch.set_num_threads(1) + + +def features_for_node(node_id: str) -> list[float]: + """Codifica solo la fase y posición, sin etiqueta léxica ni número de tríada.""" + parts = node_id.split("_") + phase, position = parts[1], int(parts[2][1:]) + return [float(phase == "adv"), float(phase == "ret"), + float(position == 0), float(position == 1), float(position == 2)] + + +def parse_pair_index(node_id: str) -> int: + phase = node_id.split("_")[1] + position = int(node_id.split("_")[2][1:]) + return position if phase == "adv" else 3 + position + + +def read_data(): + nodes: dict[int, list[list[float]]] = {i: [None] * 6 for i in range(1, 14)} + with (ROOT / "datasets" / "triad_nodes.csv").open(encoding="utf-8", newline="") as handle: + for row in csv.DictReader(handle): + nodes[int(row["triad_index"])][parse_pair_index(row["node_id"])] = features_for_node(row["node_id"]) + pairs: dict[int, list[tuple[int, int, int]]] = {i: [] for i in range(1, 14)} + with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as handle: + for row in csv.DictReader(handle): + pairs[int(row["triad_index"])].append((parse_pair_index(row["source"]), + parse_pair_index(row["target"]), + CLASS_ID[row["relation"]])) + assert all(all(feature is not None for feature in group) for group in nodes.values()) + return {k: torch.tensor(v, dtype=torch.float32) for k, v in nodes.items()}, pairs + + +class TypedGraphAttention(nn.Module): + """Atención multi-cabeza sobre los seis nodos de las dos fases de cada tríada.""" + def __init__(self, dim: int, heads: int): + super().__init__() + assert dim % heads == 0 + self.dim, self.heads, self.head_dim = dim, heads, dim // heads + self.query = nn.Linear(dim, dim, bias=False) + self.key = nn.Linear(dim, dim, bias=False) + self.value = nn.Linear(dim, dim, bias=False) + self.out = nn.Linear(dim, dim) + self.norm = nn.LayerNorm(dim) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + batch, n_nodes, _ = x.shape + def split(layer): + return layer(x).view(batch, n_nodes, self.heads, self.head_dim).transpose(1, 2) + q, k, v = split(self.query), split(self.key), split(self.value) + scores = torch.matmul(q, k.transpose(-2, -1)) / (self.head_dim ** 0.5) + weights = torch.softmax(scores, dim=-1) + attended = torch.matmul(weights, v).transpose(1, 2).contiguous().view(batch, n_nodes, self.dim) + return self.norm(x + self.out(attended)) + + +class PIHGATT(nn.Module): + """Codificador GAT de dos capas y decodificador para relación dirigida.""" + def __init__(self, dim: int = 32, heads: int = 4, input_dim: int = 5): + super().__init__() + self.encoder = nn.Linear(input_dim, dim) + self.attention1 = TypedGraphAttention(dim, heads) + self.attention2 = TypedGraphAttention(dim, heads) + self.decoder = nn.Sequential(nn.Linear(dim * 3, dim), nn.GELU(), nn.Linear(dim, len(CLASSES))) + + def encode(self, x: torch.Tensor) -> torch.Tensor: + h = F.gelu(self.encoder(x)) + h = F.gelu(self.attention1(h)) + return self.attention2(h) + + def forward(self, x: torch.Tensor, pairs: torch.Tensor) -> torch.Tensor: + h = self.encode(x) + src, dst = pairs[:, 0], pairs[:, 1] + left, right = h[:, src, :], h[:, dst, :] + return self.decoder(torch.cat((left, right, left * right), dim=-1)) + + +def admissible_relation(label: str, source: int, target: int) -> bool: + """Predicados de validez alineados con io:mirrorOf / io:creates en SHACL.""" + source_phase, source_pos = (0 if source < 3 else 1), source % 3 + target_phase, target_pos = (0 if target < 3 else 1), target % 3 + if source_phase == target_phase: + return False + if label == "mirrorOf": + return target_pos == 2 - source_pos + if label == "creates": + return (source_pos in (0, 2) and target_pos == 1) or (source_pos == 1 and target_pos in (0, 2)) + return True + + +def scores(gold: list[int], predicted: list[int]) -> dict: + matrix = [[0] * len(CLASSES) for _ in CLASSES] + for actual, guess in zip(gold, predicted): + matrix[actual][guess] += 1 + per_class, f1_values = {}, [] + for idx, name in enumerate(CLASSES): + tp = matrix[idx][idx] + fp = sum(matrix[row][idx] for row in range(len(CLASSES)) if row != idx) + fn = sum(matrix[idx][col] for col in range(len(CLASSES)) if col != idx) + precision = tp / (tp + fp) if tp + fp else 0.0 + recall = tp / (tp + fn) if tp + fn else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + per_class[name] = {"precision": precision, "recall": recall, "f1": f1, "support": tp + fn} + f1_values.append(f1) + accuracy = sum(a == b for a, b in zip(gold, predicted)) / len(gold) + return {"accuracy": accuracy, "macro_f1": sum(f1_values) / len(f1_values), + "per_class": per_class, "confusion_matrix_rows_gold_cols_predicted": matrix} + + +def run_variant(name: str, columns: list[int], nodes, relations, cfg: dict) -> dict: + all_gold, all_pred, predicted_edges, fold_results = [], [], [], [] + pair_indices = torch.tensor([(s, t) for s in range(6) for t in range(6) if s != t], dtype=torch.long) + for held_out in sorted(nodes): + seed_everything(int(cfg["seed"]) + held_out - 1) + train_ids = [i for i in nodes if i != held_out] + x_train = torch.stack([nodes[i][:, columns] for i in train_ids]) + y_train = torch.tensor([label for i in train_ids for _s, _t, label in relations[i]], dtype=torch.long) + model = PIHGATT(int(cfg["hidden_dim"]), int(cfg["attention_heads"]), input_dim=len(columns)) + counts = torch.bincount(y_train, minlength=len(CLASSES)).float() + class_weights = (len(y_train) / (len(CLASSES) * counts.clamp_min(1))).float() + optimizer = torch.optim.AdamW(model.parameters(), lr=float(cfg["learning_rate"]), + weight_decay=float(cfg["weight_decay"])) + model.train() + for _epoch in range(int(cfg["epochs"])): + optimizer.zero_grad(set_to_none=True) + logits = model(x_train, pair_indices).reshape(-1, len(CLASSES)) + loss = F.cross_entropy(logits, y_train, weight=class_weights) + loss.backward() + optimizer.step() + model.eval() + with torch.no_grad(): + predicted = model(nodes[held_out][:, columns].unsqueeze(0), pair_indices).argmax(dim=-1).reshape(-1).tolist() + gold_map = {(src, dst): label for src, dst, label in relations[held_out]} + gold = [gold_map[(src, dst)] for src, dst in pair_indices.tolist()] + all_gold.extend(gold) + all_pred.extend(predicted) + for (src, dst), label_id in zip(pair_indices.tolist(), predicted): + if label_id: + label = CLASSES[label_id] + predicted_edges.append((held_out, src, dst, label)) + fold_results.append({"held_out_triad": held_out, + "accuracy": sum(a == b for a, b in zip(gold, predicted)) / len(gold)}) + report = scores(all_gold, all_pred) + by_class = report["per_class"] + compliant = sum(admissible_relation(label, source, target) + for _triad, source, target, label in predicted_edges) + edge_compliance = compliant / len(predicted_edges) if predicted_edges else 1.0 + metrics = { + "candidate_relation_accuracy": {"value": report["accuracy"], "property": "io:mirrorOf / io:creates; exact three-class labels"}, + "relation_macro_f1": {"value": report["macro_f1"], "property": "balanced F1 for none, io:mirrorOf and io:creates"}, + "mirrorOf_precision": {"value": by_class["mirrorOf"]["precision"], "property": "SHACL: reciprocal mirror; same triad; opposite phase; position reflection"}, + "mirrorOf_recall": {"value": by_class["mirrorOf"]["recall"], "property": "completeness of the io:mirrorOf edge set"}, + "mirrorOf_f1": {"value": by_class["mirrorOf"]["f1"], "property": "precision/recall of io:mirrorOf"}, + "creates_precision": {"value": by_class["creates"]["precision"], "property": "SHACL: same triad, opposite phase, four allowed position rules"}, + "creates_recall": {"value": by_class["creates"]["recall"], "property": "completeness of four creation rules"}, + "creates_f1": {"value": by_class["creates"]["f1"], "property": "precision/recall of io:creates"}, + "predicted_edge_rule_conformance": {"value": edge_compliance, "property": "SHACL phase/triad/position rules for predicted mirrorOf and creates", "predicted_edges": len(predicted_edges)}, + } + return {"variant": name, "feature_columns": columns, "metrics": metrics, + "per_class": by_class, "confusion_matrix_rows_gold_cols_predicted": report["confusion_matrix_rows_gold_cols_predicted"], + "folds": fold_results} + + +def run() -> dict: + cfg = CONFIG + nodes, relations = read_data() + candidates = [ + ("PI-HGAT-T_full_phase_and_position", [0, 1, 2, 3, 4]), + ("ablation_without_phase", [2, 3, 4]), + ("ablation_without_position", [0, 1]), + ] + start = time.time() + variants = [run_variant(name, columns, nodes, relations, cfg) for name, columns in candidates] + primary = variants[0] + gold_labels = [label for triad in relations.values() for _src, _dst, label in triad] + dataset = {"triads": 13, "nodes": 78, "directed_relation_candidates": len(gold_labels), + "gold_mirrorOf_edges": sum(label == CLASS_ID["mirrorOf"] for label in gold_labels), + "gold_creates_edges": sum(label == CLASS_ID["creates"] for label in gold_labels), + "gold_none_pairs": sum(label == CLASS_ID["none"] for label in gold_labels)} + report = { + "model": cfg["model_id"], + "model_definition": cfg["model_definition"], + "dataset": dataset, + "validation": "13-fold leave-one-triad-out; no lexical labels or triad index as model features", + "primary_metrics": primary["metrics"], + "experiments": variants, + "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.", + "software": {"python": platform.python_version(), "pytorch": torch.__version__, "platform": platform.platform()}, + "configuration": cfg, + } + results_path = ROOT / "experiments" / "results" / "pi_hgat_t_metrics.json" + results_path.parent.mkdir(parents=True, exist_ok=True) + results_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + log_path = ROOT / "experiments" / "logs" / "pi_hgat_t.log" + log_path.parent.mkdir(parents=True, exist_ok=True) + lines = ["PI-HGAT-T / ablation suite", f"Python={platform.python_version()} PyTorch={torch.__version__}", + f"seed={cfg['seed']} folds=13 epochs={cfg['epochs']} candidates={len(gold_labels)}"] + for variant in variants: + m = variant["metrics"] + lines.append(f"{variant['variant']}: accuracy={m['candidate_relation_accuracy']['value']:.6f} macro_f1={m['relation_macro_f1']['value']:.6f} " + f"mirrorOf_f1={m['mirrorOf_f1']['value']:.6f} creates_f1={m['creates_f1']['value']:.6f} " + f"rule_conformance={m['predicted_edge_rule_conformance']['value']:.6f}") + lines.append(f"runtime_seconds={time.time() - start:.3f}") + log_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + print("\n".join(lines)) + print(f"Resultados: {results_path}") + return report + + +if __name__ == "__main__": + run() diff --git a/experiments/results/README.md b/experiments/results/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ff683a6464c25c0abb4d6d0335367b31370e6a48 --- /dev/null +++ b/experiments/results/README.md @@ -0,0 +1,14 @@ +# results/ — salidas opcionales (no versionadas) + +| Propiedad | Valor | +|-----------|--------| +| ¿Fundamenta el punto fijo? | **No** | +| ¿Participa en CI core? | **No** | +| ¿Reproducible offline? | Solo tras regenerar CSV y ejecutar scripts opcionales | + +**Generan contenido:** +- `python experiments/optional/pi_hgat_t.py` +- `python experiments/optional/baselines.py` +- `python scripts/generate_audit_report.py` + +Los JSON de esta carpeta **no** se versionan. Accuracy 1.0 aquí es tautología informativa. diff --git a/lake-manifest.json b/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..7defd2f33228e476469e88dfcd2538a123fc4fce --- /dev/null +++ b/lake-manifest.json @@ -0,0 +1,5 @@ +{"version": "1.0.0", + "packagesDir": ".lake/packages", + "packages": [], + "name": "iom", + "lakeDir": ".lake"} diff --git a/lakefile.lean b/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e434fd4f1f06382de2a75914ef417b34db4232d --- /dev/null +++ b/lakefile.lean @@ -0,0 +1,7 @@ +import Lake +open Lake DSL + +package iom + +@[default_target] +lean_lib IOM diff --git a/lean-toolchain b/lean-toolchain new file mode 100644 index 0000000000000000000000000000000000000000..4ef27c472e460c0dbcd8429d822a77a00b95e6b1 --- /dev/null +++ b/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.9.0 diff --git a/ontology/README.md b/ontology/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4a29c84afc376a426e33fd2eff7d8e841dc00354 --- /dev/null +++ b/ontology/README.md @@ -0,0 +1,35 @@ +# ontology/ + +| Archivo | Rol | +|---------|-----| +| `io_shapes.ttl` | Restricciones SHACL **escritas**; se versionan | +| `io_ontology.ttl` | OWL **derivado** desde `data/iom_spec.json` | + +## Regenerar / materializar + +```bash +# Fuente canónica (requiere rdflib) +python scripts/generate_ontology.py + +# Derivado determinista embebido (hash fijo, sin rdflib) +python scripts/materialize_ttl.py +``` + +SHA-256 esperado: + +```text +84e2fe878fcf4a41b7ad364fb6f22e28e16db9132b7e2de89d36de55deeb87ba +``` + +CI regenera antes de tests y SHACL. El punto fijo compara CSV + `GENERATED_FROM.json`, **no** el TTL byte-a-byte. + +## Versionar el TTL en el árbol + +```bash +python scripts/materialize_ttl.py +git add ontology/io_ontology.ttl +python scripts/create_manifest.py +git add MANIFEST.sha256 +git commit -m "chore: versionar io_ontology.ttl alineado al generador" +git push +``` diff --git a/ontology/io_shapes.ttl b/ontology/io_shapes.ttl new file mode 100644 index 0000000000000000000000000000000000000000..490dd755e2eaaa204cda00dd27da6b34df9f0092 --- /dev/null +++ b/ontology/io_shapes.ttl @@ -0,0 +1,123 @@ +@prefix sh: . +@prefix xsd: . +@prefix io: . +@prefix rdfs: . + +io:StructuralShape a sh:NodeShape ; + sh:targetClass io:OntoNode ; + sh:property [ sh:path io:hasTriadIndex ; sh:datatype xsd:integer ; sh:minInclusive 1 ; sh:maxInclusive 13 ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:hasPhase ; sh:datatype xsd:string ; sh:in ( "adv"^^xsd:string "ret"^^xsd:string ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:hasLocalPos ; sh:datatype xsd:integer ; sh:in ( 0 1 2 ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + 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 ] ; + sh:property [ sh:path io:hasPosition ; sh:in ( ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:hasPerspective ; sh:in ( io:Ind io:D io:Tot ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:hasDirection ; sh:in ( io:evol io:invol ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path rdfs:label ; sh:languageIn ( "es" ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:mirrorOf ; sh:class io:OntoNode ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:creates ; sh:class io:OntoNode ; sh:minCount 1 ; sh:maxCount 2 ] ; + sh:sparql [ + sh:message "posicion y fase" ; + sh:select """ + PREFIX io: + SELECT $this WHERE { + $this io:hasLocalPos ?pos ; io:hasPerspective ?perspective ; io:hasPosition ?position ; io:hasPhase ?phase . + FILTER ( + (?pos = 1 && (?perspective != io:D || ?position != )) || + (?pos = 0 && ?perspective != io:Ind) || + (?pos = 2 && ?perspective != io:Tot) || + (?phase = "adv" && (?pos = 0 || ?pos = 2) && ?position != ) || + (?phase = "ret" && (?pos = 0 || ?pos = 2) && ?position != ) + ) + } + """ + ] ; + sh:sparql [ + sh:message "etiquetas visuales" ; + sh:select """ + PREFIX io: + SELECT $this WHERE { + $this io:hasPhase ?phase ; io:hasLocalPos ?pos ; io:displayLabel ?label . + FILTER ((?phase = "adv" && + !((?pos = 0 && ?label = "→") || (?pos = 1 && ?label = "0") || (?pos = 2 && ?label = "→"))) || + (?phase = "ret" && + !((?pos = 0 && ?label = "←") || (?pos = 1 && ?label = "0") || (?pos = 2 && ?label = "←")))) + } + """ + ] ; + sh:sparql [ + sh:message "espejo reciproco" ; + sh:select """ + PREFIX io: + SELECT $this WHERE { + $this io:hasTriadIndex ?triad ; io:hasLocalPos ?pos ; io:hasPhase ?phase ; io:mirrorOf ?mirror . + ?mirror io:hasTriadIndex ?otherTriad ; io:hasLocalPos ?otherPos ; io:hasPhase ?otherPhase . + FILTER NOT EXISTS { ?mirror io:mirrorOf $this } + FILTER (?triad != ?otherTriad || ?otherPos != (2 - ?pos) || + !((?phase = "adv" && ?otherPhase = "ret") || (?phase = "ret" && ?otherPhase = "adv"))) + } + """ + ] ; + sh:sparql [ + sh:message "fase y direccion" ; + sh:select """ + PREFIX io: + SELECT $this WHERE { + $this io:hasPhase ?phase ; io:hasDirection ?direction . + FILTER ((?phase = "adv" && ?direction != io:evol) || (?phase = "ret" && ?direction != io:invol)) + } + """ + ] ; + sh:sparql [ + sh:message "creates reglas" ; + sh:select """ + PREFIX io: + SELECT $this WHERE { + $this io:hasTriadIndex ?triad ; io:hasLocalPos ?pos ; io:hasPhase ?phase ; io:creates ?target . + ?target io:hasTriadIndex ?otherTriad ; io:hasLocalPos ?otherPos ; io:hasPhase ?otherPhase . + FILTER (?triad != ?otherTriad || + !((?phase = "adv" && ?otherPhase = "ret" && + ((?pos = 0 && ?otherPos = 1) || (?pos = 2 && ?otherPos = 1) || + (?pos = 1 && (?otherPos = 0 || ?otherPos = 2)))) || + (?phase = "ret" && ?otherPhase = "adv" && + ((?pos = 0 && ?otherPos = 1) || (?pos = 2 && ?otherPos = 1) || + (?pos = 1 && (?otherPos = 0 || ?otherPos = 2))))) + ) + } + """ + ] . + +io:VectorStepShape a sh:NodeShape ; + sh:targetClass io:VectorStep ; + sh:property [ sh:path io:hasVector ; sh:in ( io:Evol io:Invol ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:hasCyclePhase ; sh:datatype xsd:string ; sh:in ( "adv"^^xsd:string "ret"^^xsd:string ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:hasAxisPosition ; sh:datatype xsd:integer ; sh:in ( 0 1 2 3 4 ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:hasStepIndex ; sh:datatype xsd:integer ; sh:in ( 0 1 2 3 4 ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:displayArrow ; sh:in ( "→"^^xsd:string "←"^^xsd:string ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path rdfs:label ; sh:languageIn ( "es" ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:sparql [ + sh:message "etiqueta vectorial canónica" ; + sh:select """ + PREFIX rdfs: + SELECT $this WHERE { + $this rdfs:label ?label . + BIND(STR(?label) AS ?text) + FILTER (?text != "invol" && ?text != "ind" && ?text != "dua" && ?text != "tot" && ?text != "evol") + } + """ + ] . + +io:ExpandedCategoryShape a sh:NodeShape ; + sh:targetClass io:ExpandedCategory ; + sh:property [ sh:path io:hasLevel ; sh:datatype xsd:integer ; sh:in ( 0 1 2 3 4 ) ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path rdfs:label ; sh:languageIn ( "es" ) ; sh:minCount 1 ; sh:maxCount 1 ] . + +io:SourceModelShape a sh:NodeShape ; + sh:targetNode io:SourceModel ; + sh:property [ sh:path io:declaredTriadCount ; sh:hasValue 13 ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:declaredPerspectiveCount ; sh:hasValue 5 ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:declaredOperatorCount ; sh:hasValue 4 ; sh:minCount 1 ; sh:maxCount 1 ] ; + sh:property [ sh:path io:declaredExpandedCategoryCount ; sh:hasValue 21 ; sh:minCount 1 ; sh:maxCount 1 ] . + +io:PerspectiveShape a sh:NodeShape ; + sh:targetClass io:Perspective ; + sh:property [ sh:path rdfs:label ; sh:languageIn ( "es" ) ; sh:minCount 1 ; sh:maxCount 1 ] . diff --git a/paper.md b/paper.md new file mode 100644 index 0000000000000000000000000000000000000000..14d8249082e5604012f55cc2937b5f9444220e46 --- /dev/null +++ b/paper.md @@ -0,0 +1,41 @@ +# IOM — construcción formal de la unidad informativa + +Este informe describe el repositorio IOM como una **construcción formal de +unidad informativa**: estructura autocontenida de distinciones, relaciones, +integración y transformación, verificable desde `data/iom_spec.json` (punto +fijo, Lean, SHACL). La autonomía verificable es el *mecanismo* de constitución +y validación; anotadores, dominios y learners de recuperación de reglas son +**encuentro**, no fundamento. + +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). + +## Propósito + +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. + +Las 13 tríadas son modos de composición de esa unidad. + +## Núcleo (fundamento) + +1. Punto fijo: `self_bootstrap.py --passes 2` +2. SelfGenesis / FormalRules / InformationalUnit: `lake build` +3. SHACL sobre TTL regenerado +4. Invariancia no trivial (`measure_invariance.py`) + +## Encuentro (no fundamenta) + +EXP-E (dominio / Mictlán) y EXP-A (κ) son proyección provisional. Sin +`ACCESS_LOG`, κ histórico no se declara demostración cerrada. + +## Diagnóstico circular (opcional) + +PI-HGAT-T y baselines (`experiments/optional/`) recuperan etiquetas que **ya +están** en (fase, posición). Accuracy 1.0 es tautología informativa, no validez +del marco en el mundo. PyTorch no es dependencia del núcleo. + +## Límite de la afirmación + +El repositorio **implementa** una construcción formal de unidad informativa. +No afirma por sí solo una unidad absoluta independiente del entorno de +ejecución. La validez interna se mide por derivabilidad y trazabilidad desde +la especificación canónica. diff --git a/requirements-lock.txt b/requirements-lock.txt new file mode 100644 index 0000000000000000000000000000000000000000..bbd8eb1a341ac846eca7d35f32914085051cdf77 --- /dev/null +++ b/requirements-lock.txt @@ -0,0 +1,25 @@ +--extra-index-url https://download.pytorch.org/whl/cpu +attrs==25.3.0 +filelock==4.0.12 +fsspec==2026.9.0 +html5rdf==1.2.1 +Jinja2==3.1.6 +jsonschema==4.23.0 +jsonschema-specifications==2025.4.1 +MarkupSafe==3.0.4 +mpmath==1.3.0 +networkx==3.7 +numpy==1.26.4 +owlrl==7.1.4 +packaging==26.3 +prettytable==3.18.0 +pyparsing==3.3.3 +pyshacl==0.30.1 +rdflib==7.1.4 +referencing==0.36.2 +rpds-py==0.25.1 +setuptools==84.0.0 +sympy==1.13.1 +torch==2.6.0+cpu +typing_extensions==4.16.0 +wcwidth==0.9.2 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..db77b70ca5831d9f613205d9ab53281996df3650 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +--extra-index-url https://download.pytorch.org/whl/cpu +rdflib==7.1.4 +pyshacl==0.30.1 +owlrl==7.1.4 +numpy==1.26.4 +torch==2.6.0+cpu +jsonschema==4.23.0 diff --git a/scripts/audit_perfect_metrics.py b/scripts/audit_perfect_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..cdba3fa62b89aac9dd412be0137db1de23539406 --- /dev/null +++ b/scripts/audit_perfect_metrics.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Auditoría rigurosa de las métricas perfectas (100%). + +Investiga por qué PI-HGAT-T y el MLP alcanzan accuracy/F1 = 1.0: + +1. Independencia train/test bajo leave-one-triad-out (sí: ninguna pareja + de la tríada held-out aparece en entrenamiento). +2. Sin embargo, las etiquetas están **completamente determinadas** por + (fase, posición) del par — reglas idénticas en las 13 tríadas. +3. Por tanto, cualquier modelo que aprenda la función determinista + (fase_src, pos_src, fase_tgt, pos_tgt) → {none, mirrorOf, creates} + generaliza al 100% a tríadas no vistas. +4. El oracle de reglas deterministas y el MLP (features = one-hot fase+pos) + alcanzan 1.0; la regresión logística lineal no separa mirrorOf/creates. + +Este script demuestra (1)–(3) de forma programática y escribe un informe JSON. +""" +from __future__ import annotations + +import csv +import json +from collections import defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +CLASSES = ("none", "mirrorOf", "creates") + + +def parse_node(node_id: str) -> tuple[str, int]: + parts = node_id.split("_") + return parts[1], int(parts[2][1:]) + + +def feature_key(src: str, tgt: str) -> tuple: + """Clave de features usada por los modelos (fase+posición, sin tríada ni etiqueta).""" + sp, spos = parse_node(src) + tp, tpos = parse_node(tgt) + return (sp, spos, tp, tpos) + + +def deterministic_label(src: str, tgt: str) -> str: + """Regla determinista alineada con SHACL / FormalRules.lean.""" + sp, spos = parse_node(src) + tp, tpos = parse_node(tgt) + if sp == tp: + return "none" + if tpos == 2 - spos: + return "mirrorOf" + lateral_s = spos in (0, 2) + lateral_t = tpos in (0, 2) + if (lateral_s and tpos == 1) or (spos == 1 and lateral_t): + return "creates" + return "none" + + +def main() -> int: + rows = [] + with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as fh: + rows = list(csv.DictReader(fh)) + + # 1. Consistencia gold vs regla determinista + mismatches = [] + for row in rows: + pred = deterministic_label(row["source"], row["target"]) + if pred != row["relation"]: + mismatches.append({"row": row, "rule_predicts": pred}) + + # 2. La etiqueta es función solo de (fase, pos) — misma clave → misma etiqueta + by_feature: dict[tuple, set[str]] = defaultdict(set) + by_feature_triads: dict[tuple, set[int]] = defaultdict(set) + for row in rows: + key = feature_key(row["source"], row["target"]) + by_feature[key].add(row["relation"]) + by_feature_triads[key].add(int(row["triad_index"])) + + non_deterministic_features = { + str(k): list(v) for k, v in by_feature.items() if len(v) > 1 + } + + # 3. Leave-one-triad-out: ¿las features del held-out aparecen en train? + # Sí, con la misma etiqueta — por eso un learner que memoriza la + # función feature→label generaliza al 100%. + triad_feature_overlap = {} + for held in range(1, 14): + train_map = {} + test_keys = set() + for row in rows: + key = feature_key(row["source"], row["target"]) + tid = int(row["triad_index"]) + if tid == held: + test_keys.add((key, row["relation"])) + else: + train_map[key] = row["relation"] + recoverable = sum(1 for k, lab in test_keys if train_map.get(k) == lab) + triad_feature_overlap[held] = { + "test_pairs": len(test_keys), + "recoverable_by_feature_lookup": recoverable, + "fraction": recoverable / len(test_keys) if test_keys else 0.0, + } + + all_recoverable = all( + v["fraction"] == 1.0 for v in triad_feature_overlap.values() + ) + + # 4. Conteos + from collections import Counter + counts = Counter(r["relation"] for r in rows) + + report = { + "conclusion": ( + "Las métricas perfectas (100%) de PI-HGAT-T y del MLP no indican " + "sobreajuste por fuga de identidad de tríada: leave-one-triad-out " + "excluye correctamente las parejas del held-out. Indican que las " + "etiquetas son una función determinista de (fase, posición) del par, " + "idéntica en las 13 tríadas. Aprender esa función basta para " + "generalizar al 100%. El oracle de reglas deterministas alcanza 1.0 " + "sin aprendizaje. La arquitectura de grafo no es necesaria para este " + "corpus sintético; sirve como demostración de recuperabilidad estructural." + ), + "gold_vs_deterministic_rule": { + "mismatches": len(mismatches), + "details": mismatches[:5], # muestra + "perfect_match": len(mismatches) == 0, + }, + "label_determined_by_phase_position_only": { + "unique_feature_keys": len(by_feature), + "keys_with_ambiguous_labels": non_deterministic_features, + "is_deterministic_function": len(non_deterministic_features) == 0, + }, + "leave_one_triad_out_feature_overlap": { + "per_fold": triad_feature_overlap, + "all_folds_100pct_recoverable_by_feature_lookup": all_recoverable, + "interpretation": ( + "En cada fold, el 100% de los pares de prueba tiene una clave " + "(fase,pos) ya vista en entrenamiento con la misma etiqueta. " + "No hay fuga de node_id/triad_index (el modelo no los usa), " + "pero la función a aprender es trivialmente compartida." + ), + }, + "class_counts": dict(counts), + "implications": [ + "No se requiere arquitectura compleja (GAT) para este corpus: el MLP y el oracle bastan.", + "Las ablaciones sin fase/posición degradan el rendimiento porque rompen la función determinista.", + "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/).", + "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.", + ], + } + + out = ROOT / "experiments" / "results" / "perfect_metrics_audit.json" + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + print("Auditoría de métricas perfectas") + print(f" Gold vs regla determinista: mismatches={len(mismatches)}") + print(f" Función determinista fase+pos: {len(non_deterministic_features) == 0}") + print(f" LOO recoverable por lookup de features: {all_recoverable}") + print(f" Informe: {out}") + print() + print(report["conclusion"]) + return 0 if len(mismatches) == 0 and all_recoverable else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/capture_environment.py b/scripts/capture_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..40d95e5df93dc0b9d359963350654b3ea8650305 --- /dev/null +++ b/scripts/capture_environment.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Captura versiones del entorno de reproducción en un artefacto JSON.""" +from __future__ import annotations +import importlib.metadata +import json +import platform +import subprocess +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +def command_version(command: list[str]) -> str | None: + try: + result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=20) + return (result.stdout or result.stderr).strip().splitlines()[0] + except (OSError, subprocess.SubprocessError): + return None + +def main() -> None: + packages = {} + for name in ("rdflib", "pyshacl", "owlrl", "numpy", "torch"): + try: + packages[name] = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + packages[name] = None + data = { + "python": platform.python_version(), + "implementation": platform.python_implementation(), + "platform": platform.platform(), + "packages": packages, + "lean_toolchain_file": (ROOT / "lean-toolchain").read_text(encoding="utf-8").strip(), + "lean_version": command_version(["lean", "--version"]), + "lake_version": command_version(["lake", "--version"]), + "requirements": (ROOT / "requirements.txt").read_text(encoding="utf-8").splitlines(), + } + out = ROOT / "experiments" / "results" / "software_versions.json" + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(out) + print(json.dumps(data, ensure_ascii=False, indent=2)) + +if __name__ == "__main__": + main() diff --git a/scripts/check_generated_committed.py b/scripts/check_generated_committed.py new file mode 100644 index 0000000000000000000000000000000000000000..286ffc15c41ed2c4dce9acce5edbc8c62bc9f6ad --- /dev/null +++ b/scripts/check_generated_committed.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Comprueba que los CSV versionados coinciden con generate_ontology.py. + +Solo se exige igualdad exacta de: + + - datasets/triad_nodes.csv + - datasets/vector_steps.csv + - datasets/relation_candidates.csv + - datasets/GENERATED_FROM.json (spec_version del generador) + +El TTL no se compara byte-a-byte (serialización rdflib). +""" +from __future__ import annotations + +import argparse +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +GENERATED_CSV = [ + "datasets/triad_nodes.csv", + "datasets/vector_steps.csv", + "datasets/relation_candidates.csv", + "datasets/GENERATED_FROM.json", +] + + +def run(cmd: list[str]) -> subprocess.CompletedProcess: + return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--with-manifest", action="store_true") + parser.add_argument("--skip-generate", action="store_true") + parser.add_argument("--include-ttl", action="store_true") + args = parser.parse_args() + + if not args.skip_generate: + print(">>> generate_ontology.py") + r = run([sys.executable, "scripts/generate_ontology.py"]) + print(r.stdout, end="") + if r.returncode != 0: + print(r.stderr, file=sys.stderr) + return 1 + + paths = list(GENERATED_CSV) + if args.include_ttl: + paths.insert(0, "ontology/io_ontology.ttl") + + if args.with_manifest: + print(">>> create_manifest.py") + r = run([sys.executable, "scripts/create_manifest.py"]) + print(r.stdout, end="") + if r.returncode != 0: + print(r.stderr, file=sys.stderr) + return 1 + paths.append("MANIFEST.sha256") + + print(">>> git diff --ignore-space-at-eol --exit-code", " ".join(paths)) + r = run(["git", "diff", "--ignore-space-at-eol", "--exit-code", "--", *paths]) + if r.returncode != 0: + print( + "ERROR: los artefactos generados no coinciden con lo versionado.", + file=sys.stderr, + ) + print(r.stdout or r.stderr, file=sys.stderr) + return 1 + + print("OK: derivados (CSV + GENERATED_FROM) coinciden con HEAD") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/create_manifest.py b/scripts/create_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..dd3b3593e1781c54133168b35c174704919bcda7 --- /dev/null +++ b/scripts/create_manifest.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Escribe SHA-256 de los artefactos fuente/reproducibles incluidos en el paquete. + +Exclusiones (no forman parte del punto fijo del manifiesto): + - MANIFEST.sha256 — evita hash auto-referente + - AUDITORIA_AUTO.md — regenerable con timestamp + - ontology/io_ontology.ttl — regenerable; orden de serialización rdflib no es + estable byte-a-byte entre corridas (CI lo regenera antes de SHACL) + - __pycache__, .pytest_cache, .venv + +Los CSV canónicos (triad_nodes, vector_steps, relation_candidates) SÍ entran: +son el punto fijo de generate_ontology.py. +""" +from hashlib import sha256 +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +INCLUDE_DIRS = ("IOM", "data", "datasets", "docs", "experiments", "ontology", "scripts", "tests") +INCLUDE_FILES = ( + "IOM.lean", "README.md", "AUDITORIA.md", "EXPERIMENTOS.md", "REPRODUCCION.md", "paper.md", + "MANIFIESTO.md", + "requirements.txt", "requirements-lock.txt", "lakefile.lean", "lake-manifest.json", "lean-toolchain", + "LICENSE", ".gitignore", ".github/workflows/ci.yml", +) +EXCLUDE_NAMES = frozenset({ + "MANIFEST.sha256", + "AUDITORIA_AUTO.md", + "io_ontology.ttl", # regenerable; serialización no determinista +}) +EXCLUDE_DIR_PARTS = frozenset({"__pycache__", ".pytest_cache", ".venv", "node_modules"}) + + +def main() -> None: + files = {ROOT / name for name in INCLUDE_FILES if (ROOT / name).is_file()} + for dirname in INCLUDE_DIRS: + folder = ROOT / dirname + if folder.exists(): + files.update( + p for p in folder.rglob("*") + if p.is_file() + and not any(part in EXCLUDE_DIR_PARTS for part in p.parts) + ) + files = {p for p in files if p.name not in EXCLUDE_NAMES} + out = ROOT / "MANIFEST.sha256" + lines = [ + f"{sha256(path.read_bytes()).hexdigest()} {path.relative_to(ROOT).as_posix()}" + for path in sorted(files) + ] + out.write_text("\n".join(lines) + "\n", encoding="utf-8") + print(f"SHA-256: {len(lines)} archivos -> {out}") + print(f" excluidos por nombre: {sorted(EXCLUDE_NAMES)}") + + +if __name__ == "__main__": + main() diff --git a/scripts/generate_audit_report.py b/scripts/generate_audit_report.py new file mode 100644 index 0000000000000000000000000000000000000000..68582a74f76871d4215bf9598900a0b4897c3b74 --- /dev/null +++ b/scripts/generate_audit_report.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Informe de auditoría regenerable (encuentro). No se versiona como fundamento.""" +from __future__ import annotations + +import json +from datetime import datetime, timezone +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def load_json(rel: str): + path = ROOT / rel + if not path.is_file(): + return None + return json.loads(path.read_text(encoding="utf-8")) + + +def main() -> None: + out_dir = ROOT / "experiments" / "results" + out_dir.mkdir(parents=True, exist_ok=True) + metrics = load_json("experiments/results/pi_hgat_t_metrics.json") + baselines = load_json("experiments/results/baselines_comparison.json") + versions = load_json("experiments/results/software_versions.json") + + lines = [ + "# AUDITORIA_AUTO", + "", + f"Generado: {datetime.now(timezone.utc).isoformat()}", + "", + "> Informe fechado. **No** es prueba de punto fijo ni fundamento del marco.", + "", + "## Capas", + "", + "- Núcleo: `self_bootstrap.py`, Lean, SHACL, invariancia", + "- Encuentro: EXP-A/E, PI-HGAT-T/baselines (opcionales)", + "", + ] + if metrics is None: + lines.append( + "_No se encontró pi_hgat_t_metrics.json; " + "ejecutar experiments/optional/pi_hgat_t.py primero._" + ) + else: + lines.append("## PI-HGAT-T (diagnóstico)") + lines.append("```json") + lines.append(json.dumps(metrics.get("primary_metrics", metrics), indent=2)[:2000]) + lines.append("```") + if baselines: + lines.append("## Baselines") + lines.append("```json") + lines.append(json.dumps(baselines.get("baselines", baselines), indent=2)[:2000]) + lines.append("```") + if versions: + lines.append("## Software") + lines.append(json.dumps(versions, indent=2)) + + out_md = out_dir / "AUDITORIA_AUTO.md" + out_md.write_text("\n".join(lines) + "\n", encoding="utf-8") + print(f"Escrito {out_md}") + + +if __name__ == "__main__": + main() diff --git a/scripts/generate_ontology.py b/scripts/generate_ontology.py new file mode 100644 index 0000000000000000000000000000000000000000..571c552f0d67c11962623029550a25858c27d247 --- /dev/null +++ b/scripts/generate_ontology.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Genera RDF/OWL y datasets desde data/iom_spec.json, única fuente tabular.""" +from __future__ import annotations + +import csv +import json +from pathlib import Path +from rdflib import BNode, Graph, Literal, Namespace +from rdflib.namespace import OWL, RDF, RDFS, XSD + +ROOT = Path(__file__).resolve().parents[1] +SPEC = json.loads((ROOT / "data" / "iom_spec.json").read_text(encoding="utf-8")) +IO = Namespace("http://example.org/iom#") +g = Graph() +for prefix, namespace in (("io", IO), ("rdfs", RDFS), ("xsd", XSD), ("owl", OWL)): + g.bind(prefix, namespace) + +ontology = IO.Ontology +g.add((ontology, RDF.type, OWL.Ontology)) +g.add((ontology, OWL.versionInfo, Literal(SPEC["spec_version"]))) +g.add((ontology, RDFS.label, Literal("Ontología IOM", lang="es"))) +g.add((ontology, RDFS.comment, Literal(SPEC["source_note"], lang="es"))) +classes = ("OntoNode", "VectorStep", "Perspective", "ExpandedCategory", "Position", "Direction", "SourceModel") +for name in classes: + g.add((IO[name], RDF.type, OWL.Class)) +for names in (("OntoNode", "VectorStep", "ExpandedCategory", "Perspective"),): + axiom = BNode("iomDisjointCoreClasses") + head = BNode("iomDisjointClassList0") + g.add((axiom, RDF.type, OWL.AllDisjointClasses)) + g.add((axiom, OWL.members, head)) + cells = [BNode(f"iomDisjointClassList{i}") for i in range(len(names))] + for index, name in enumerate(names): + g.add((cells[index], RDF.first, IO[name])) + g.add((cells[index], RDF.rest, cells[index + 1] if index + 1 < len(cells) else RDF.nil)) + +object_properties = { + "hasPerspective": ("OntoNode", "Perspective"), + "hasPosition": ("OntoNode", "Position"), + "hasDirection": ("OntoNode", "Direction"), + "hasVector": ("VectorStep", "Perspective"), + "mirrorOf": ("OntoNode", "OntoNode"), + "creates": ("OntoNode", "OntoNode"), +} +datatype_properties = { + "hasTriadIndex": ("OntoNode", XSD.integer), + "hasPhase": ("OntoNode", XSD.string), + "hasLocalPos": ("OntoNode", XSD.integer), + "displayLabel": ("OntoNode", XSD.string), + "hasCyclePhase": ("VectorStep", XSD.string), + "hasAxisPosition": ("VectorStep", XSD.integer), + "hasStepIndex": ("VectorStep", XSD.integer), + "displayArrow": ("VectorStep", XSD.string), + "hasLevel": ("ExpandedCategory", XSD.integer), + "declaredTriadCount": ("SourceModel", XSD.integer), + "declaredPerspectiveCount": ("SourceModel", XSD.integer), + "declaredOperatorCount": ("SourceModel", XSD.integer), + "declaredExpandedCategoryCount": ("SourceModel", XSD.integer), +} +for name, (domain, range_) in object_properties.items(): + prop = IO[name] + g.add((prop, RDF.type, OWL.ObjectProperty)) + g.add((prop, RDFS.domain, IO[domain])) + g.add((prop, RDFS.range, IO[range_])) +for name, (domain, range_) in datatype_properties.items(): + prop = IO[name] + g.add((prop, RDF.type, OWL.DatatypeProperty)) + g.add((prop, RDFS.domain, IO[domain])) + g.add((prop, RDFS.range, range_)) +for name in ("hasPerspective", "hasPosition", "hasDirection", "hasVector", "hasTriadIndex", "hasPhase", "hasLocalPos", "displayLabel", "hasCyclePhase", "hasAxisPosition", "hasStepIndex", "displayArrow", "hasLevel"): + g.add((IO[name], RDF.type, OWL.FunctionalProperty)) +g.add((IO.mirrorOf, RDF.type, OWL.SymmetricProperty)) + +for pos, label in [("→", "→"), ("0", "0"), ("←", "←")]: + g.add((IO[pos], RDF.type, OWL.NamedIndividual)) + g.add((IO[pos], RDF.type, IO.Position)) + g.add((IO[pos], RDFS.label, Literal(label, lang="es"))) +for direction in ("evol", "invol"): + g.add((IO[direction], RDF.type, OWL.NamedIndividual)) + g.add((IO[direction], RDF.type, IO.Direction)) +_perspective_labels = SPEC.get("perspective_labels") or { + "Ind": "Individualidad", "D": "Dualidad", "Tot": "Totalidad", + "Evol": "Evolución", "Invol": "Involución", +} +for name, label in _perspective_labels.items(): + g.add((IO[name], RDF.type, IO.Perspective)) + g.add((IO[name], RDFS.label, Literal(label, lang="es"))) + +position_meta = SPEC["positions"] +position_indices = position_meta["indices"] +position_names_adv = ["→", "0", "→"] +position_names_ret = ["←", "0", "←"] +perspective_names = position_meta["perspectives"] +perspectives = [IO[name] for name in perspective_names] +triad_meta = SPEC["triads"] +triad_rows = {phase: triad_meta[phase] for phase in ("adv", "ret")} +index_base = triad_meta.get("index_base", 0) +n_triads = len(triad_rows["adv"]) +triad_ids = range(index_base, index_base + n_triads) +nodes_csv = [] +for phase, rows in triad_rows.items(): + direction = IO[SPEC["phases"][phase]["direction"]] + for row_index, labels in enumerate(rows): + triad_idx = index_base + row_index + for pos_idx, label in enumerate(labels): + node = IO[f"T{triad_idx:02d}_{phase}_P{pos_idx}"] + g.add((node, RDF.type, IO.OntoNode)) + g.add((node, IO.hasTriadIndex, Literal(triad_idx, datatype=XSD.integer))) + g.add((node, IO.hasPhase, Literal(phase, datatype=XSD.string))) + g.add((node, IO.hasLocalPos, Literal(pos_idx, datatype=XSD.integer))) + display_labels = position_meta["adv_labels" if phase == "adv" else "ret_labels"] + display_label = display_labels[pos_idx] + g.add((node, IO.displayLabel, Literal(display_label, datatype=XSD.string))) + pos_names = position_names_adv if phase == "adv" else position_names_ret + g.add((node, IO.hasPosition, IO[pos_names[pos_idx]])) + g.add((node, IO.hasPerspective, perspectives[pos_idx])) + g.add((node, IO.hasDirection, direction)) + g.add((node, RDFS.label, Literal(label, lang="es"))) + nodes_csv.append({"node_id": str(node).split("#", 1)[1], "triad_index": triad_idx, "phase": phase, + "direction": str(direction).split("#", 1)[1], "position_index": pos_idx, + "position": pos_names[pos_idx], "display_label": display_label, + "perspective": perspective_names[pos_idx], "label": label}) + +for triad_idx in triad_ids: + for pos_idx in range(3): + adv = IO[f"T{triad_idx:02d}_adv_P{pos_idx}"] + ret = IO[f"T{triad_idx:02d}_ret_P{2-pos_idx}"] + g.add((adv, IO.mirrorOf, ret)) + g.add((ret, IO.mirrorOf, adv)) + +for triad_idx in triad_ids: + for rule in SPEC["creation_rules"]: + for source_pos in rule["source_positions"]: + for target_pos in rule["target_positions"]: + source = IO[f"T{triad_idx:02d}_{rule['source_phase']}_P{source_pos}"] + target = IO[f"T{triad_idx:02d}_{rule['target_phase']}_P{target_pos}"] + g.add((source, IO.creates, target)) + +vector_csv = [] +for vector_row in SPEC["vectors"]: + vector, phase = vector_row["name"], vector_row["phase"] + for step_index, (label, axis_pos) in enumerate(zip(vector_row["labels"], vector_row["axis_positions"])): + step = IO[f"vector_{vector.lower()}_{phase}_{step_index}"] + g.add((step, RDF.type, IO.VectorStep)) + g.add((step, IO.hasVector, IO[vector])) + g.add((step, IO.hasCyclePhase, Literal(phase, datatype=XSD.string))) + g.add((step, IO.hasAxisPosition, Literal(axis_pos, datatype=XSD.integer))) + g.add((step, IO.hasStepIndex, Literal(step_index, datatype=XSD.integer))) + g.add((step, IO.displayArrow, Literal(vector_row["arrow"], datatype=XSD.string))) + g.add((step, RDFS.label, Literal(label, lang="es"))) + vector_csv.append({"step_id": str(step).split("#", 1)[1], "vector": vector, "phase": phase, + "step_index": step_index, "axis_position": axis_pos, "label": label, + "arrow": vector_row["arrow"]}) + +for level, labels in SPEC["expanded_categories"].items(): + for index, label in enumerate(labels, 1): + category = IO[f"expanded_L{level}_{index:02d}"] + g.add((category, RDF.type, IO.ExpandedCategory)) + g.add((category, IO.hasLevel, Literal(int(level), datatype=XSD.integer))) + g.add((category, RDFS.label, Literal(label, lang="es"))) + +model = IO.SourceModel +g.add((model, RDF.type, IO.SourceModel)) +for prop, value in ((IO.declaredTriadCount, 13), (IO.declaredPerspectiveCount, 5), + (IO.declaredOperatorCount, 4), (IO.declaredExpandedCategoryCount, 21)): + g.add((model, prop, Literal(value, datatype=XSD.integer))) + +relation_csv = [] +relation_lookup = {} +for subject, _, obj in g.triples((None, IO.mirrorOf, None)): + relation_lookup[(str(subject), str(obj))] = "mirrorOf" +for subject, _, obj in g.triples((None, IO.creates, None)): + relation_lookup[(str(subject), str(obj))] = "creates" +for triad_idx in triad_ids: + ids = [IO[f"T{triad_idx:02d}_{phase}_P{pos}"] for phase in ("adv", "ret") for pos in range(3)] + for source in ids: + for target in ids: + if source == target: + continue + relation_csv.append({"triad_index": triad_idx, "source": str(source).split("#", 1)[1], + "target": str(target).split("#", 1)[1], + "relation": relation_lookup.get((str(source), str(target)), "none")}) + +assert len(triad_rows["adv"]) == len(triad_rows["ret"]) == 13 +assert position_indices == [0, 1, 2] +assert len(nodes_csv) == 78 +assert len(vector_csv) == 20 +assert sum(1 for _ in g.triples((None, IO.creates, None))) == 104 +assert len(relation_csv) == 13 * 6 * 5 + +out = ROOT / "ontology" / "io_ontology.ttl" +out.parent.mkdir(parents=True, exist_ok=True) +out.write_text(g.serialize(format="turtle").rstrip() + "\n", encoding="utf-8") + +def write_csv(path: Path, rows: list[dict]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + +write_csv(ROOT / "datasets" / "triad_nodes.csv", nodes_csv) +write_csv(ROOT / "datasets" / "vector_steps.csv", vector_csv) +write_csv(ROOT / "datasets" / "relation_candidates.csv", relation_csv) + +_stamp = { + "spec_version": SPEC["spec_version"], + "schema_version": SPEC.get("schema_version"), + "source_date": SPEC.get("source_date"), + "purpose_id": (SPEC.get("purpose") or {}).get("id"), + "purpose_label": (SPEC.get("purpose") or {}).get("label"), + "artifacts": [ + "datasets/triad_nodes.csv", + "datasets/vector_steps.csv", + "datasets/relation_candidates.csv", + "ontology/io_ontology.ttl", + ], +} +(ROOT / "datasets" / "GENERATED_FROM.json").write_text( + json.dumps(_stamp, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" +) +print(f"Tríadas: {n_triads} por fase (índice {index_base}–{index_base + n_triads - 1}); nodos: {len(nodes_csv)}; creates: 104; espejos: 78") +print(f"Pasos vectoriales: {len(vector_csv)}; candidatos PI-HGAT-T: {len(relation_csv)}") +print(f"OWL/Turtle: {out}") +print(f"Sello: datasets/GENERATED_FROM.json spec_version={SPEC['spec_version']}") diff --git a/scripts/importar_datos_personalizados.py b/scripts/importar_datos_personalizados.py new file mode 100644 index 0000000000000000000000000000000000000000..6e36f5e9bcb0899461411c755edd3602853d77c8 --- /dev/null +++ b/scripts/importar_datos_personalizados.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Plantilla de ingesta guiada: alinea un CSV de conceptos externos a la ontología IOM de 78 nodos. + +No modifica data/iom_spec.json ni la ontología core. Valida que los mapped_node_id +existen, comprueba consistencia de perspectiva/fase/posición y genera un CSV alineado +más un informe de validación. + +Uso: + python scripts/importar_datos_personalizados.py \ + --input datasets/ingestion/templates/biologia_depredador_presa.csv \ + --output datasets/ingestion/aligned/biologia_aligned.csv + +Opciones: + --input PATH CSV de entrada (obligatorio) + --output PATH CSV alineado de salida (por defecto: datasets/ingestion/aligned/_aligned.csv) + --strict Fallar si hay cualquier warning (por defecto solo error en mapped_node_id inválido) + --report PATH Ruta del informe JSON (por defecto junto al output) +""" +from __future__ import annotations + +import argparse +import csv +import json +import sys +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[1] +NODES_CSV = ROOT / "datasets" / "triad_nodes.csv" +VALID_PERSPECTIVES = {"Ind", "D", "Tot", "Evol", "Invol"} +VALID_PHASES = {"adv", "ret"} +VALID_POSITIONS = {"left", "center", "right"} +VALID_RELATIONS = {"none", "mirrorOf", "creates"} +REQUIRED_COLUMNS = {"external_id", "external_label"} + + +def load_canonical_nodes() -> dict[str, dict[str, Any]]: + """Carga los 78 nodos canónicos indexados por node_id.""" + if not NODES_CSV.is_file(): + print( + f"ERROR: no se encuentra {NODES_CSV}. " + "Ejecuta primero: python scripts/generate_ontology.py", + file=sys.stderr, + ) + raise SystemExit(1) + nodes: dict[str, dict[str, Any]] = {} + with NODES_CSV.open(encoding="utf-8", newline="") as fh: + reader = csv.DictReader(fh) + for row in reader: + nodes[row["node_id"]] = row + if len(nodes) != 78: + print( + f"ADVERTENCIA: se esperaban 78 nodos, se cargaron {len(nodes)}. " + "Regenera los datasets con generate_ontology.py.", + file=sys.stderr, + ) + return nodes + + +def read_input_csv(path: Path) -> list[dict[str, str]]: + """Lee el CSV de entrada ignorando líneas de comentario que empiezan por #.""" + rows: list[dict[str, str]] = [] + with path.open(encoding="utf-8", newline="") as fh: + # Filtrar comentarios antes de pasar al DictReader + lines = [ln for ln in fh if not ln.strip().startswith("#")] + from io import StringIO + + reader = csv.DictReader(StringIO("".join(lines))) + if reader.fieldnames is None: + print("ERROR: el CSV no tiene cabecera.", file=sys.stderr) + raise SystemExit(1) + missing = REQUIRED_COLUMNS - set(reader.fieldnames) + if missing: + print(f"ERROR: faltan columnas obligatorias: {sorted(missing)}", file=sys.stderr) + raise SystemExit(1) + for row in reader: + # Normalizar claves + cleaned = {k.strip(): (v.strip() if isinstance(v, str) else v) for k, v in row.items()} + if not cleaned.get("external_id"): + continue + rows.append(cleaned) + return rows + + +def validate_row( + row: dict[str, str], + nodes: dict[str, dict[str, Any]], + row_num: int, +) -> tuple[dict[str, Any], list[str], list[str]]: + """Valida una fila y devuelve (fila_alineada, errores, warnings).""" + errors: list[str] = [] + warnings: list[str] = [] + aligned: dict[str, Any] = { + "external_id": row["external_id"], + "external_label": row.get("external_label", ""), + "mapped_node_id": row.get("mapped_node_id", ""), + "perspective": row.get("perspective", ""), + "phase": row.get("phase", ""), + "position": row.get("position", ""), + "relation_candidate": row.get("relation_candidate", "none") or "none", + "notes": row.get("notes", ""), + "canonical_label": "", + "canonical_perspective": "", + "canonical_phase": "", + "canonical_position": "", + "status": "ok", + } + + node_id = aligned["mapped_node_id"] + if not node_id: + errors.append(f"fila {row_num}: mapped_node_id vacío") + aligned["status"] = "error" + return aligned, errors, warnings + + if node_id not in nodes: + errors.append( + f"fila {row_num}: mapped_node_id '{node_id}' no existe en los 78 nodos canónicos" + ) + aligned["status"] = "error" + return aligned, errors, warnings + + canon = nodes[node_id] + aligned["canonical_label"] = canon.get("label", "") + aligned["canonical_perspective"] = canon.get("perspective", "") + aligned["canonical_phase"] = canon.get("phase", "") + aligned["canonical_position"] = canon.get("position", "") + + # Consistencia opcional de perspectiva / fase / posición + if aligned["perspective"] and aligned["perspective"] not in VALID_PERSPECTIVES: + warnings.append( + f"fila {row_num}: perspective '{aligned['perspective']}' no es canónica " + f"({sorted(VALID_PERSPECTIVES)})" + ) + elif aligned["perspective"] and aligned["perspective"] != canon.get("perspective"): + # Solo advertir si el usuario forzó un valor distinto del nodo + if aligned["perspective"] in {"Ind", "D", "Tot"}: + warnings.append( + f"fila {row_num}: perspective declarada '{aligned['perspective']}' " + f"≠ perspectiva del nodo '{canon.get('perspective')}'" + ) + + if aligned["phase"] and aligned["phase"] not in VALID_PHASES: + warnings.append( + f"fila {row_num}: phase '{aligned['phase']}' no es canónica ({sorted(VALID_PHASES)})" + ) + elif aligned["phase"] and aligned["phase"] != canon.get("phase"): + warnings.append( + f"fila {row_num}: phase declarada '{aligned['phase']}' ≠ fase del nodo '{canon.get('phase')}'" + ) + + if aligned["position"] and aligned["position"] not in VALID_POSITIONS: + warnings.append( + f"fila {row_num}: position '{aligned['position']}' no es canónica " + f"({sorted(VALID_POSITIONS)})" + ) + elif aligned["position"] and aligned["position"] != canon.get("position"): + warnings.append( + f"fila {row_num}: position declarada '{aligned['position']}' " + f"≠ posición del nodo '{canon.get('position')}'" + ) + + if aligned["relation_candidate"] not in VALID_RELATIONS: + warnings.append( + f"fila {row_num}: relation_candidate '{aligned['relation_candidate']}' " + f"no es válida ({sorted(VALID_RELATIONS)}); se fuerza a 'none'" + ) + aligned["relation_candidate"] = "none" + + if warnings and aligned["status"] == "ok": + aligned["status"] = "warning" + + return aligned, errors, warnings + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Alinea un CSV de conceptos externos a la ontología IOM de 78 nodos." + ) + parser.add_argument("--input", "-i", required=True, type=Path, help="CSV de entrada") + parser.add_argument( + "--output", + "-o", + type=Path, + default=None, + help="CSV alineado de salida", + ) + parser.add_argument( + "--strict", + action="store_true", + help="Tratar warnings como errores (exit code 1)", + ) + parser.add_argument( + "--report", + type=Path, + default=None, + help="Ruta del informe JSON de validación", + ) + args = parser.parse_args() + + if not args.input.is_file(): + print(f"ERROR: no existe el archivo de entrada: {args.input}", file=sys.stderr) + return 1 + + nodes = load_canonical_nodes() + rows = read_input_csv(args.input) + if not rows: + print("ERROR: el CSV de entrada no contiene filas de datos.", file=sys.stderr) + return 1 + + aligned_rows: list[dict[str, Any]] = [] + all_errors: list[str] = [] + all_warnings: list[str] = [] + + for i, row in enumerate(rows, start=2): # +2 por cabecera y 1-index + aligned, errors, warnings = validate_row(row, nodes, i) + aligned_rows.append(aligned) + all_errors.extend(errors) + all_warnings.extend(warnings) + + # Determinar rutas de salida + if args.output is None: + out_dir = ROOT / "datasets" / "ingestion" / "aligned" + out_dir.mkdir(parents=True, exist_ok=True) + args.output = out_dir / f"{args.input.stem}_aligned.csv" + else: + args.output.parent.mkdir(parents=True, exist_ok=True) + + if args.report is None: + args.report = args.output.with_suffix(".report.json") + + # Escribir CSV alineado + fieldnames = [ + "external_id", + "external_label", + "mapped_node_id", + "canonical_label", + "canonical_perspective", + "canonical_phase", + "canonical_position", + "perspective", + "phase", + "position", + "relation_candidate", + "status", + "notes", + ] + with args.output.open("w", encoding="utf-8", newline="") as fh: + writer = csv.DictWriter(fh, fieldnames=fieldnames, extrasaction="ignore") + writer.writeheader() + writer.writerows(aligned_rows) + + report = { + "input": str(args.input), + "output": str(args.output), + "canonical_nodes": len(nodes), + "rows_processed": len(aligned_rows), + "errors": all_errors, + "warnings": all_warnings, + "ok_count": sum(1 for r in aligned_rows if r["status"] == "ok"), + "warning_count": sum(1 for r in aligned_rows if r["status"] == "warning"), + "error_count": sum(1 for r in aligned_rows if r["status"] == "error"), + } + args.report.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + + # Resumen en consola + print(f"Entrada: {args.input}") + print(f"Salida: {args.output}") + print(f"Informe: {args.report}") + print(f"Filas: {report['rows_processed']} " + f"(ok={report['ok_count']}, warning={report['warning_count']}, error={report['error_count']})") + if all_errors: + print("\nERRORES:") + for e in all_errors: + print(f" - {e}") + if all_warnings: + print("\nADVERTENCIAS:") + for w in all_warnings: + print(f" - {w}") + + if all_errors: + print("\nResultado: FALLO (hay errores de mapeo)") + return 1 + if args.strict and all_warnings: + print("\nResultado: FALLO (--strict y hay advertencias)") + return 1 + print("\nResultado: OK — los conceptos se alinearon a la ontología canónica sin romper la bóveda.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/materialize_ttl.py b/scripts/materialize_ttl.py new file mode 100644 index 0000000000000000000000000000000000000000..26a9bf1c3426de8c063edfedd63cfc4d5c6bb98b --- /dev/null +++ b/scripts/materialize_ttl.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +"""Materializa ontology/io_ontology.ttl (hash 84e2fe87...). Preferir generate_ontology.py.""" +from __future__ import annotations +import base64, hashlib, zlib +from pathlib import Path +ROOT = Path(__file__).resolve().parents[1] +OUT = ROOT / "ontology" / "io_ontology.ttl" +EXPECTED = "84e2fe878fcf4a41b7ad364fb6f22e28e16db9132b7e2de89d36de55deeb87ba" +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=' + +def main() -> None: + data = zlib.decompress(base64.b64decode(PAYLOAD)) + digest = hashlib.sha256(data).hexdigest() + if digest != EXPECTED: + raise SystemExit(f"hash mismatch: {digest} != {EXPECTED}") + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_bytes(data) + print(f"OK {OUT} ({len(data)} bytes) sha256={digest}") + +if __name__ == "__main__": + main() diff --git a/scripts/measure_invariance.py b/scripts/measure_invariance.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a7349c9262a44d387016089a926520e96b4887 --- /dev/null +++ b/scripts/measure_invariance.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Invariancia interna no trivial (con control negativo). + +Mide autonomía *y* distingue el grafo canónico de uno corrompido: + +1. Auto-regeneración: etiqueta ≡ regla (fase, pos) aplicada al par. +2. Invariancia bajo índice de tríada. +3. Reconstrucción desde subconjunto (LOO feature lookup sin etiquetas del held-out). +4. **Control negativo:** al corromper una arista del grafo, (1) o (3) debe fallar. + +Sin el control negativo, un 1.0 podría ser tautología. +""" +from __future__ import annotations + +import copy +import csv +import json +from collections import defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def parse_node(node_id: str) -> tuple[str, int]: + parts = node_id.split("_") + return parts[1], int(parts[2][1:]) + + +def rule_label(src: str, tgt: str) -> str: + sp, spos = parse_node(src) + tp, tpos = parse_node(tgt) + if sp == tp: + return "none" + if tpos == 2 - spos: + return "mirrorOf" + if (spos in (0, 2) and tpos == 1) or (spos == 1 and tpos in (0, 2)): + return "creates" + return "none" + + +def feature_key(src: str, tgt: str) -> tuple: + sp, spos = parse_node(src) + tp, tpos = parse_node(tgt) + return (sp, spos, tp, tpos) + + +def self_regen_rate(rows: list[dict]) -> float: + mism = sum(1 for r in rows if rule_label(r["source"], r["target"]) != r["relation"]) + return 1.0 - mism / max(len(rows), 1) + + +def triad_invariant(rows: list[dict]) -> bool: + by_feat: dict[tuple, set[str]] = defaultdict(set) + for r in rows: + by_feat[feature_key(r["source"], r["target"])].add(r["relation"]) + return all(len(v) == 1 for v in by_feat.values()) + + +def subset_reconstruction(rows: list[dict]) -> bool: + for held in range(1, 14): + train: dict[tuple, str] = {} + test: list[tuple[tuple, str]] = [] + for r in rows: + key = feature_key(r["source"], r["target"]) + tid = int(r["triad_index"]) + if tid == held: + test.append((key, r["relation"])) + else: + train[key] = r["relation"] + if any(train.get(k) != lab for k, lab in test): + return False + return True + + +def corrupt_one_edge(rows: list[dict]) -> list[dict]: + """Cambia la etiqueta de la primera arista mirrorOf a none (grafo inválido).""" + out = copy.deepcopy(rows) + for r in out: + if r["relation"] == "mirrorOf": + r["relation"] = "none" + break + return out + + +def main() -> int: + rows = list( + csv.DictReader( + (ROOT / "datasets" / "relation_candidates.csv").open( + encoding="utf-8", newline="" + ) + ) + ) + + regen = self_regen_rate(rows) + inv = triad_invariant(rows) + subset = subset_reconstruction(rows) + + corrupted = corrupt_one_edge(rows) + # Tras corrupción: o bien auto-regeneración cae, o el grafo ya no coincide con la regla + corrupted_regen = self_regen_rate(corrupted) + negative_control_detects = corrupted_regen < 1.0 + + autonomy = regen == 1.0 and inv and subset + non_trivial = autonomy and negative_control_detects + + report = { + "framing": ( + "Invariancia no trivial: el canónico regenera 1.0; un grafo con una " + "arista corrupta debe fallar el control negativo." + ), + "canonical": { + "self_regeneration_rate": round(regen, 6), + "triad_index_invariance": inv, + "subset_reconstruction": subset, + "autonomy_measurable": autonomy, + }, + "negative_control": { + "description": "primera arista mirrorOf relabelada a none", + "corrupted_self_regeneration_rate": round(corrupted_regen, 6), + "detects_corruption": negative_control_detects, + "interpretation": ( + "si detects_corruption es false, la métrica no distingue " + "grafo correcto de corrompido (tautología)" + ), + }, + "invariance_non_trivial": non_trivial, + } + + out = ROOT / "experiments" / "results" / "invariance_metrics.json" + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + print("Invariancia interna (con control negativo)") + print(f" Auto-regeneración canónica: {regen}") + print(f" Invariancia bajo índice de tríada: {inv}") + print(f" Reconstrucción desde subconjunto: {subset}") + print(f" Control negativo detecta corrupción: {negative_control_detects} (rate={corrupted_regen:.6f})") + print(f" Invariancia no trivial: {non_trivial}") + print(f" Informe: {out}") + return 0 if non_trivial else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/migrate_spec.py b/scripts/migrate_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..fec357ae2ea34d05a98305d51cb9dcda0bd1b7da --- /dev/null +++ b/scripts/migrate_spec.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Aplica migraciones declarativas a data/iom_spec.json. + +Las migraciones se registran en el campo `migrations` del propio JSON. +Este script solo registra y valida; las transformaciones semánticas futuras +deben implementarse como funciones nombradas en MIGRATION_HANDLERS. +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SPEC_PATH = ROOT / "data" / "iom_spec.json" + +# Handlers de migración (from_version -> función). Vacío en 1.1.0 porque el +# cambio fue solo metadatos. +MIGRATION_HANDLERS: dict[str, callable] = {} + + +def load() -> dict: + return json.loads(SPEC_PATH.read_text(encoding="utf-8")) + + +def save(data: dict) -> None: + SPEC_PATH.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + +def list_migrations(data: dict) -> None: + migrations = data.get("migrations") or [] + if not migrations: + print("No hay migraciones registradas.") + return + for m in migrations: + print(f" {m['from_version']} -> {m['to_version']}: {m['description']} ({m.get('date', '?')})") + + +def main() -> None: + parser = argparse.ArgumentParser(description="Gestión de migraciones de iom_spec.json") + parser.add_argument("--list", action="store_true", help="Listar migraciones registradas") + parser.add_argument("--check", action="store_true", help="Verificar que spec_version es coherente") + args = parser.parse_args() + + data = load() + if args.list: + print(f"spec_version actual: {data.get('spec_version')}") + list_migrations(data) + return + if args.check: + version = data.get("spec_version") + migrations = data.get("migrations") or [] + if migrations: + last = migrations[-1]["to_version"] + if last != version: + raise SystemExit(f"Inconsistencia: último to_version={last} pero spec_version={version}") + print(f"OK: spec_version={version} coherente con historial de migraciones") + return + parser.print_help() + + +if __name__ == "__main__": + main() diff --git a/scripts/package_reproducible.py b/scripts/package_reproducible.py new file mode 100644 index 0000000000000000000000000000000000000000..039f0ed23c738dfc3707e2eb18b34103dfe6ba48 --- /dev/null +++ b/scripts/package_reproducible.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Empaqueta los artefactos reproducibles, excluyendo cachés y el checkout Git.""" +from pathlib import Path +from zipfile import ZIP_DEFLATED, ZipFile + +ROOT = Path(__file__).resolve().parents[1] +INCLUDE = [ + "README.md", "AUDITORIA.md", "EXPERIMENTOS.md", "REPRODUCCION.md", "paper.md", "LICENSE", "MANIFEST.sha256", + "IOM.lean", "IOM", "lakefile.lean", "lake-manifest.json", "lean-toolchain", "requirements.txt", "requirements-lock.txt", + "data", "datasets", "experiments/config.json", "experiments/optional", "experiments/results", + "experiments/logs", "ontology", "scripts", "tests", ".github/workflows/ci.yml", +] + +def files_in(path: Path): + if path.is_file(): + yield path + elif path.is_dir(): + for p in path.rglob("*"): + if p.is_file() and ".git" not in p.parts: + yield p + +def main() -> None: + out = ROOT / "iom-reproducible.zip" + with ZipFile(out, "w", ZIP_DEFLATED) as zf: + for rel in INCLUDE: + for p in files_in(ROOT / rel): + zf.write(p, p.relative_to(ROOT).as_posix()) + print(f"Escrito {out}") + +if __name__ == "__main__": + main() diff --git a/scripts/score_independent_eval.py b/scripts/score_independent_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..823199d7b189cc9b2ee9f0b6a48cf960030b7456 --- /dev/null +++ b/scripts/score_independent_eval.py @@ -0,0 +1,407 @@ +#!/usr/bin/env python3 +"""Scoring post-hoc de evaluación independiente (capa C). + +Formato oficial de anotaciones (annotations_template.json): + + { + "annotators": ["A1", "A2", "A3"], + "status": "pending_human_collection" | "complete", + "items": [ + { + "id": "NR01", + "annotations": {"A1": "none" | null, ...}, + "free_text": {"A1": "...", ...} + }, + ... + ] + } + +Reglas estadísticas: + - null / ausente ≠ etiqueta "unsure". + - Fleiss' kappa exige el **mismo conjunto de anotadores** con respuesta + no nula en **todos** los ítems incluidos (k fijo). No se trunca. + - Si un ítem tiene un subconjunto distinto de respondentes, se excluye + del kappa y se reporta en incomplete/heterogeneous. + - "unsure" es una respuesta legítima, no un relleno. + +Uso: + python scripts/score_independent_eval.py + python scripts/score_independent_eval.py --annotations path/to/filled.json + python scripts/score_independent_eval.py --min-annotators 3 +""" +from __future__ import annotations + +import argparse +import json +import sys +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[1] +EVAL_DIR = ROOT / "datasets" / "independent_eval" +VALID_LABELS = frozenset({"none", "mirrorOf", "creates", "unsure"}) + + +def fleiss_kappa(ratings: list[list[str]], categories: list[str]) -> float: + """Fleiss' kappa. ratings[i] = etiquetas de los k anotadores para el ítem i. + Todas las filas deben tener la misma longitud k ≥ 2. + """ + n_items = len(ratings) + if n_items == 0: + return float("nan") + n_raters = len(ratings[0]) + if n_raters < 2: + return float("nan") + if any(len(r) != n_raters for r in ratings): + raise ValueError("Todas las filas de ratings deben tener la misma longitud") + + cat_idx = {c: i for i, c in enumerate(categories)} + table = [] + for row in ratings: + counts = [0] * len(categories) + for lab in row: + if lab not in cat_idx: + raise ValueError(f"Etiqueta fuera de categorías: {lab!r}") + counts[cat_idx[lab]] += 1 + table.append(counts) + + P = [] + for counts in table: + s = sum(c * (c - 1) for c in counts) + P.append(s / (n_raters * (n_raters - 1))) + P_bar = sum(P) / n_items + + totals = [sum(table[i][j] for i in range(n_items)) for j in range(len(categories))] + p = [t / (n_items * n_raters) for t in totals] + P_e = sum(pj ** 2 for pj in p) + if abs(1 - P_e) < 1e-12: + return 1.0 + return (P_bar - P_e) / (1 - P_e) + + +def parse_template_format(data: dict) -> tuple[list[str], dict[str, dict[str, str | None]]]: + """Formato oficial: annotators=[ids], items=[{id, annotations: {A: label|null}}].""" + annotator_ids = list(data.get("annotators") or []) + if not annotator_ids: + raise ValueError("Campo 'annotators' vacío o ausente") + + by_pair: dict[str, dict[str, str | None]] = {} + items = data.get("items") + if not isinstance(items, list): + raise ValueError("Campo 'items' debe ser una lista") + + for item in items: + pid = item.get("id") + if not pid: + raise ValueError(f"Ítem sin id: {item!r}") + anns = item.get("annotations") or {} + if not isinstance(anns, dict): + raise ValueError(f"annotations de {pid} debe ser un objeto") + pair_map: dict[str, str | None] = {} + for aid in annotator_ids: + raw = anns.get(aid) + if raw is None: + pair_map[aid] = None + elif isinstance(raw, str) and raw.strip() == "": + pair_map[aid] = None + elif raw in VALID_LABELS: + pair_map[aid] = raw + else: + raise ValueError( + f"Etiqueta inválida en {pid}/{aid}: {raw!r}. " + f"Permitidas: {sorted(VALID_LABELS)} o null" + ) + by_pair[pid] = pair_map + return annotator_ids, by_pair + + +def parse_legacy_formats(data: Any) -> tuple[list[str], dict[str, dict[str, str | None]]]: + by_pair: dict[str, dict[str, str | None]] = defaultdict(dict) + annotator_ids: list[str] = [] + + if isinstance(data, dict) and "annotators" in data: + anns = data["annotators"] + if isinstance(anns, list) and anns and isinstance(anns[0], dict) and "labels" in anns[0]: + for ann in anns: + aid = str(ann.get("id") or ann.get("name") or f"A{len(annotator_ids)+1}") + annotator_ids.append(aid) + for pair_id, label in (ann.get("labels") or {}).items(): + by_pair[pair_id][aid] = label if label in VALID_LABELS else None + return annotator_ids, dict(by_pair) + + if isinstance(data, list): + aids_set: set[str] = set() + for item in data: + pid = item.get("id") or item.get("pair_id") + aid = str(item.get("annotator") or "A1") + lab = item.get("label") or item.get("annotation") + if not pid: + continue + aids_set.add(aid) + by_pair[pid][aid] = lab if lab in VALID_LABELS else None + return sorted(aids_set), dict(by_pair) + + raise ValueError( + "Formato de anotaciones no reconocido. " + "Usa el formato de annotations_template.json." + ) + + +def load_annotations(path: Path) -> tuple[list[str], dict[str, dict[str, str | None]], dict]: + data = json.loads(path.read_text(encoding="utf-8")) + meta = { + "status": data.get("status") if isinstance(data, dict) else None, + "description": data.get("description") if isinstance(data, dict) else None, + "evaluation_mode": data.get("evaluation_mode") if isinstance(data, dict) else None, + } + if isinstance(data, dict) and isinstance(data.get("items"), list): + annotator_ids, by_pair = parse_template_format(data) + else: + annotator_ids, by_pair = parse_legacy_formats(data) + return annotator_ids, by_pair, meta + + +def load_rule_reference() -> dict[str, str]: + ref_path = EVAL_DIR / "rule_reference.json" + if not ref_path.is_file(): + return {} + raw = json.loads(ref_path.read_text(encoding="utf-8")) + if isinstance(raw, list): + return {item["id"]: item.get("rule_label") for item in raw if "id" in item} + if isinstance(raw, dict): + out = {} + for k, v in raw.items(): + if k in ("labels",): + continue + if isinstance(v, dict): + out[k] = v.get("rule_label") + elif isinstance(v, str): + out[k] = v + if "labels" in raw and isinstance(raw["labels"], dict): + out.update(raw["labels"]) + return out + return {} + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Scoring de evaluación independiente (capa C)" + ) + parser.add_argument( + "--annotations", + type=Path, + default=EVAL_DIR / "annotations.json", + help="JSON de anotaciones (plantilla o rellenado)", + ) + parser.add_argument( + "--min-annotators", + type=int, + default=3, + help="Número exacto de anotadores con respuesta no nula requerido por ítem (default 3)", + ) + args = parser.parse_args() + + if not args.annotations.is_file(): + # fallback a plantilla + alt = EVAL_DIR / "annotations_template.json" + if alt.is_file(): + args.annotations = alt + else: + print(f"ERROR: no se encontró {args.annotations}", file=sys.stderr) + return 1 + + try: + annotator_ids, by_pair, meta = load_annotations(args.annotations) + except (ValueError, json.JSONDecodeError) as exc: + print(f"ERROR de formato: {exc}", file=sys.stderr) + return 1 + + k_required = args.min_annotators + if k_required < 2: + print("ERROR: --min-annotators debe ser ≥ 2", file=sys.stderr) + return 1 + + incomplete_pairs: dict[str, dict] = {} + respondent_sets: dict[str, tuple[str, ...]] = {} + labels_by_pair_ordered: dict[str, list[str]] = {} + unsure_counts: Counter = Counter() + present_counts: Counter = Counter() + + for pid, ann_map in by_pair.items(): + respondents = [] + labels_ordered = [] + missing = [] + for aid in annotator_ids: + lab = ann_map.get(aid) + if lab is None: + missing.append(aid) + else: + respondents.append(aid) + labels_ordered.append(lab) + present_counts[lab] += 1 + if lab == "unsure": + unsure_counts[pid] += 1 + + if len(respondents) == k_required: + respondent_sets[pid] = tuple(respondents) + labels_by_pair_ordered[pid] = labels_ordered + else: + incomplete_pairs[pid] = { + "n_present": len(respondents), + "n_missing": len(missing), + "missing_annotators": missing, + "present_annotators": respondents, + "present_labels": labels_ordered, + "reason": ( + f"se requieren exactamente {k_required} respuestas no nulas; " + f"hay {len(respondents)}" + ), + } + + status = meta.get("status") or "unknown" + n_total = len(by_pair) + + by_respondent_set: dict[tuple[str, ...], list[str]] = defaultdict(list) + for pid, rset in respondent_sets.items(): + by_respondent_set[rset].append(pid) + + kappa_eligible_ids: list[str] = [] + kappa_annotators: tuple[str, ...] | None = None + heterogeneous: dict[str, dict] = {} + + if by_respondent_set: + best_set = max( + by_respondent_set.keys(), + key=lambda s: (len(by_respondent_set[s]), s), + ) + kappa_eligible_ids = sorted(by_respondent_set[best_set]) + kappa_annotators = best_set + + for rset, pids in by_respondent_set.items(): + if rset == best_set: + continue + for pid in pids: + heterogeneous[pid] = { + "respondents": list(rset), + "n_present": len(rset), + "reason": ( + "conjunto de anotadores distinto al usado para kappa " + f"({list(best_set)}); no se trunca ni se mezcla" + ), + "present_labels": labels_by_pair_ordered[pid], + } + + n_kappa = len(kappa_eligible_ids) + n_incomplete = len(incomplete_pairs) + n_heterogeneous = len(heterogeneous) + + if n_kappa == 0: + report = { + "status": status, + "evaluation_mode": meta.get("evaluation_mode"), + "n_pairs_total": n_total, + "n_pairs_in_kappa": 0, + "n_pairs_incomplete": n_incomplete, + "n_pairs_heterogeneous_respondent_set": n_heterogeneous, + "min_annotators_required": k_required, + "kappa_annotators": None, + "fleiss_kappa": None, + "majority_labels": {}, + "posthoc_agreement_with_rule_reference": None, + "incomplete_detail": incomplete_pairs, + "heterogeneous_detail": heterogeneous, + "note": ( + f"Sin ítems con exactamente {k_required} respuestas no nulas " + "del mismo conjunto de anotadores. No se trunca. " + "null/ausente ≠ 'unsure'. Protocolo listo; esperando recolección." + ), + } + out = ROOT / "experiments" / "results" / "independent_eval_scores.json" + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, ensure_ascii=False, indent=2)) + print(f"Escrito: {out}") + return 0 + + assert kappa_annotators is not None + k = len(kappa_annotators) + categories = ["none", "mirrorOf", "creates", "unsure"] + ratings = [labels_by_pair_ordered[pid] for pid in kappa_eligible_ids] + + if any(len(r) != k for r in ratings): + print( + "ERROR interno: longitudes inconsistentes tras filtrado; no se calcula kappa.", + file=sys.stderr, + ) + return 1 + + kappa = fleiss_kappa(ratings, categories) + + majority: dict[str, str] = {} + unanimous = 0 + for pid in kappa_eligible_ids: + labs = labels_by_pair_ordered[pid] + cnt = Counter(labs) + maj_lab, maj_n = cnt.most_common(1)[0] + majority[pid] = maj_lab + if maj_n == len(labs): + unanimous += 1 + + majority_all = dict(majority) + for pid, labs in labels_by_pair_ordered.items(): + if pid not in majority_all and labs: + majority_all[pid] = Counter(labs).most_common(1)[0][0] + + rule_ref = load_rule_reference() + comparable = { + pid: maj + for pid, maj in majority.items() + if rule_ref.get(pid) and rule_ref[pid] not in (None, "unspecified") + } + agreement_with_rules = None + if comparable: + matched = sum(1 for pid, maj in comparable.items() if rule_ref[pid] == maj) + agreement_with_rules = round(matched / len(comparable), 4) + + report = { + "status": status, + "evaluation_mode": meta.get("evaluation_mode"), + "n_pairs_total": n_total, + "n_pairs_in_kappa": n_kappa, + "n_pairs_incomplete": n_incomplete, + "n_pairs_heterogeneous_respondent_set": n_heterogeneous, + "min_annotators_required": k_required, + "kappa_annotators": list(kappa_annotators), + "n_annotators_per_kappa_item": k, + "fleiss_kappa": None if (isinstance(kappa, float) and kappa != kappa) else round(kappa, 4), + "unanimous_fraction": round(unanimous / n_kappa, 4) if n_kappa else None, + "majority_labels_in_kappa": majority, + "majority_labels_all_with_any_response": majority_all, + "label_distribution_present": dict(present_counts), + "unsure_count_by_pair": dict(unsure_counts), + "posthoc_agreement_with_rule_reference": agreement_with_rules, + "n_posthoc_comparable": len(comparable), + "incomplete_detail": incomplete_pairs if incomplete_pairs else {}, + "heterogeneous_detail": heterogeneous if heterogeneous else {}, + "policy": ( + "Fleiss' kappa solo sobre ítems con exactamente k anotadores no nulos " + "y el mismo conjunto de respondentes. No se trunca ni se rellena. " + "null ≠ unsure." + ), + "note": ( + "Fleiss' kappa y mayoría (sobre el panel kappa) son el objetivo primario. " + "posthoc_agreement_with_rule_reference excluye unspecified y es solo post-hoc." + ), + } + + out = ROOT / "experiments" / "results" / "independent_eval_scores.json" + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, ensure_ascii=False, indent=2)) + print(f"Escrito: {out}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/self_bootstrap.py b/scripts/self_bootstrap.py new file mode 100644 index 0000000000000000000000000000000000000000..16e8c0401f70c4d1c2602089780b03f37b526d3f --- /dev/null +++ b/scripts/self_bootstrap.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Punto fijo del repositorio: auto-creación estable bajo iteración. + + python scripts/self_bootstrap.py --passes 2 + python scripts/self_bootstrap.py --with-manifest --passes 2 + +Con --with-manifest: + 1. Regenera CSV + MANIFEST.sha256 + 2. Exige identidad con HEAD (git diff vacío) + 3. Cobertura dura de archivos críticos + 4. Sello datasets/GENERATED_FROM.json == spec_version del iom_spec.json +""" +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +DERIVED_CSV = [ + "datasets/triad_nodes.csv", + "datasets/vector_steps.csv", + "datasets/relation_candidates.csv", + "datasets/GENERATED_FROM.json", +] + +CRITICAL_IF_PRESENT = [ + "scripts/self_bootstrap.py", + "scripts/measure_invariance.py", + "scripts/create_manifest.py", + "scripts/generate_ontology.py", + "IOM/SelfGenesis.lean", + "IOM/FormalRules.lean", + "MANIFIESTO.md", + "docs/DEL_ORDEN_UNIVERSAL_A_LA_CREACION_DE_UNO_MISMO.md", + "datasets/independent_eval/instrument/INSTRUCTIONS.md", + "datasets/independent_eval/instrument/pairs.csv", + "datasets/independent_eval/instrument/ACCESS_LOG.template.json", + "datasets/GENERATED_FROM.json", +] + + +def check_spec_version_stamp() -> list[str]: + """Falla si los derivados no declaran la misma spec_version que iom_spec.json.""" + spec = json.loads((ROOT / "data" / "iom_spec.json").read_text(encoding="utf-8")) + expected = spec["spec_version"] + stamp_path = ROOT / "datasets" / "GENERATED_FROM.json" + if not stamp_path.is_file(): + return [f"falta {stamp_path.as_posix()} (regenera con generate_ontology.py)"] + stamp = json.loads(stamp_path.read_text(encoding="utf-8")) + if stamp.get("spec_version") != expected: + return [ + f"GENERATED_FROM.json spec_version={stamp.get('spec_version')!r} " + f"≠ iom_spec.json {expected!r}" + ] + return [] + + +def run(cmd: list[str]) -> subprocess.CompletedProcess: + return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True) + + +def git_diff_paths(paths: list[str]) -> subprocess.CompletedProcess: + return run(["git", "diff", "--ignore-space-at-eol", "--exit-code", "--", *paths]) + + +def porcelain(paths: list[str]) -> str: + return run(["git", "status", "--porcelain", "--", *paths]).stdout + + +def manifest_paths(manifest_file: Path) -> set[str]: + out: set[str] = set() + for line in manifest_file.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line: + continue + parts = line.split(" ", 1) + if len(parts) == 2: + out.add(parts[1]) + return out + + +def check_manifest_coverage() -> list[str]: + mf = ROOT / "MANIFEST.sha256" + if not mf.is_file(): + return ["MANIFEST.sha256 (archivo inexistente)"] + listed = manifest_paths(mf) + missing = [] + for rel in CRITICAL_IF_PRESENT: + p = ROOT / rel + if p.is_file() and rel not in listed: + missing.append(rel) + return missing + + +def main() -> int: + parser = argparse.ArgumentParser(description="Punto fijo idempotente") + parser.add_argument("--with-manifest", action="store_true") + parser.add_argument("--passes", type=int, default=2) + args = parser.parse_args() + + paths = list(DERIVED_CSV) + if args.with_manifest: + paths.append("MANIFEST.sha256") + + print("=== self_bootstrap: punto fijo idempotente ===") + print(f"Pasadas: {args.passes} | manifiesto: {args.with_manifest}") + print() + + for i in range(1, args.passes + 1): + print(f"--- pasada {i}/{args.passes} ---") + r = run([sys.executable, "scripts/generate_ontology.py"]) + print(r.stdout, end="") + if r.returncode != 0: + print(r.stderr, file=sys.stderr) + return 1 + + stamp_errs = check_spec_version_stamp() + if stamp_errs: + print("FALLO: sello de spec_version inconsistente:", file=sys.stderr) + for e in stamp_errs: + print(f" - {e}", file=sys.stderr) + return 1 + + if args.with_manifest: + r = run([sys.executable, "scripts/create_manifest.py"]) + print(r.stdout, end="") + if r.returncode != 0: + print(r.stderr, file=sys.stderr) + return 1 + + missing = check_manifest_coverage() + if missing: + print( + "FALLO de cobertura del manifiesto — archivos críticos en disco " + "pero ausentes de MANIFEST.sha256:", + file=sys.stderr, + ) + for m in missing: + print(f" - {m}", file=sys.stderr) + return 1 + + r = git_diff_paths(paths) + if r.returncode != 0: + print( + f"FALLO en pasada {i}: regenerado ≠ HEAD en {paths}", + file=sys.stderr, + ) + print(r.stdout or r.stderr, file=sys.stderr) + if args.with_manifest: + print( + "\nVersiona el manifiesto:\n" + " python scripts/create_manifest.py\n" + " git add MANIFEST.sha256 && git commit -m 'chore: refresh MANIFEST'\n" + " python scripts/self_bootstrap.py --with-manifest --passes 2", + file=sys.stderr, + ) + return 1 + + dirty = porcelain(paths).strip() + if dirty: + print(f"FALLO: porcelain no limpio:\n{dirty}", file=sys.stderr) + return 1 + print( + f"OK pasada {i}: diff vacío, porcelain limpio" + + (", cobertura crítica OK" if args.with_manifest else "") + + f", stamp={json.loads((ROOT / 'datasets' / 'GENERATED_FROM.json').read_text())['spec_version']}" + ) + + print() + print("OK: punto fijo estable (S_{n+1} = S_n).") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/sync_spec_artifacts.py b/scripts/sync_spec_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..d64859c1279ca4c7b87700ad8d0095302c2659c7 --- /dev/null +++ b/scripts/sync_spec_artifacts.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Sincronización y verificación bidireccional entre especificación y artefactos. + +Garantiza que data/iom_spec.json, los CSV generados, la ontología y los conteos +de pruebas permanecen coherentes. Con --check solo verifica; con --fix regenera +vía generate_ontology.py y vuelve a verificar. + +Uso: + python scripts/sync_spec_artifacts.py --check + python scripts/sync_spec_artifacts.py --fix +""" +from __future__ import annotations + +import argparse +import csv +import json +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SPEC_PATH = ROOT / "data" / "iom_spec.json" + + +def load_spec() -> dict: + return json.loads(SPEC_PATH.read_text(encoding="utf-8")) + + +def count_csv(name: str) -> int: + path = ROOT / "datasets" / name + if not path.is_file(): + return -1 + with path.open(encoding="utf-8", newline="") as fh: + return len(list(csv.DictReader(fh))) + + +def expected_counts(spec: dict) -> dict: + n_triads = len(spec["triads"]["adv"]) + n_positions = len(spec["positions"]["indices"]) + n_vectors = len(spec["vectors"]) + steps_per_vector = len(spec["vectors"][0]["labels"]) if spec["vectors"] else 5 + # 6 nodos por tríada (2 fases × 3 pos), 5 destinos no reflexivos → 6*5=30 pares/tríada + pairs_per_triad = (2 * n_positions) * (2 * n_positions - 1) + # creates: 4 rules × product of position lists × n_triads + creates = 0 + for rule in spec["creation_rules"]: + creates += len(rule["source_positions"]) * len(rule["target_positions"]) * n_triads + # mirrorOf: 3 posiciones × 2 direcciones × n_triads = 6 * n_triads + mirrors = n_positions * 2 * n_triads + nodes = n_triads * 2 * n_positions + pairs = n_triads * pairs_per_triad + none = pairs - mirrors - creates + return { + "n_triads": n_triads, + "nodes": nodes, + "vector_steps": n_vectors * steps_per_vector, + "relation_candidates": pairs, + "mirrorOf": mirrors, + "creates": creates, + "none": none, + } + + +def check(spec: dict) -> list[str]: + errors = [] + exp = expected_counts(spec) + + # Versión + if not spec.get("spec_version"): + errors.append("Falta spec_version") + migrations = spec.get("migrations") or [] + if migrations and migrations[-1].get("to_version") != spec.get("spec_version"): + errors.append( + f"spec_version={spec.get('spec_version')} != último to_version={migrations[-1].get('to_version')}" + ) + + # Conteos CSV + actual_nodes = count_csv("triad_nodes.csv") + actual_vecs = count_csv("vector_steps.csv") + actual_rels = count_csv("relation_candidates.csv") + + if actual_nodes != exp["nodes"]: + errors.append(f"triad_nodes.csv: {actual_nodes} filas, esperado {exp['nodes']}") + if actual_vecs != exp["vector_steps"]: + errors.append(f"vector_steps.csv: {actual_vecs} filas, esperado {exp['vector_steps']}") + if actual_rels != exp["relation_candidates"]: + errors.append( + f"relation_candidates.csv: {actual_rels} filas, esperado {exp['relation_candidates']}" + ) + + # Conteos de relaciones + if actual_rels > 0: + with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as fh: + from collections import Counter + c = Counter(r["relation"] for r in csv.DictReader(fh)) + for key in ("mirrorOf", "creates", "none"): + if c.get(key, 0) != exp[key]: + errors.append(f"relación {key}: {c.get(key, 0)}, esperado {exp[key]}") + + # Ontología existe y menciona version-ish content + ttl = ROOT / "ontology" / "io_ontology.ttl" + if not ttl.is_file(): + errors.append("Falta ontology/io_ontology.ttl") + else: + text = ttl.read_text(encoding="utf-8") + if "mirrorOf" not in text or "creates" not in text: + errors.append("io_ontology.ttl no contiene mirrorOf/creates") + + # Schema + schema = ROOT / "data" / "iom_spec.schema.json" + if not schema.is_file(): + errors.append("Falta data/iom_spec.schema.json") + + return errors + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true", help="Solo verificar sincronización") + parser.add_argument("--fix", action="store_true", help="Regenerar artefactos y verificar") + args = parser.parse_args() + + if not args.check and not args.fix: + args.check = True + + if args.fix: + print("Regenerando ontología y datasets…") + r = subprocess.run( + [sys.executable, "scripts/generate_ontology.py"], + cwd=ROOT, + capture_output=True, + text=True, + ) + if r.returncode != 0: + print(r.stdout) + print(r.stderr, file=sys.stderr) + return 1 + print(r.stdout.strip()) + + spec = load_spec() + errors = check(spec) + exp = expected_counts(spec) + + print(f"spec_version={spec.get('spec_version')} schema_version={spec.get('schema_version')}") + print(f"Esperado: nodos={exp['nodes']} vectores={exp['vector_steps']} " + f"pares={exp['relation_candidates']} " + f"(mirror={exp['mirrorOf']} creates={exp['creates']} none={exp['none']})") + + if errors: + print("INCONSISTENCIAS:") + for e in errors: + print(f" - {e}") + return 1 + print("OK: especificación, CSV y ontología sincronizados") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validate_shacl.py b/scripts/validate_shacl.py new file mode 100644 index 0000000000000000000000000000000000000000..033c94da2e08f0d9cea3e95dce0d09fdf45b0dae --- /dev/null +++ b/scripts/validate_shacl.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Comprueba declaraciones OWL, inferencias de dominio/rango y restricciones SHACL.""" +from pathlib import Path +import sys + +from owlrl import DeductiveClosure, OWLRL_Semantics +from pyshacl import validate +from rdflib import Graph, Namespace +from rdflib.namespace import OWL, RDF, RDFS + +ROOT = Path(__file__).resolve().parents[1] +DATA_GRAPH = ROOT / "ontology" / "io_ontology.ttl" +SHAPES_GRAPH = ROOT / "ontology" / "io_shapes.ttl" +IO = Namespace("http://example.org/iom#") +REQUIRED_CLASSES = (IO.OntoNode, IO.VectorStep, IO.Perspective, IO.ExpandedCategory, IO.Position, IO.Direction, IO.SourceModel) +REQUIRED_PROPERTIES = (IO.hasPerspective, IO.hasPosition, IO.hasDirection, IO.hasVector, IO.mirrorOf, IO.creates) + + +def main() -> int: + data = Graph().parse(DATA_GRAPH, format="turtle") + for cls in REQUIRED_CLASSES: + if (cls, RDF.type, OWL.Class) not in data: + print(f"Falta declaración OWL de clase {cls}", file=sys.stderr) + return 1 + for prop in REQUIRED_PROPERTIES: + if (prop, RDF.type, OWL.ObjectProperty) not in data or (prop, RDFS.domain, None) not in data or (prop, RDFS.range, None) not in data: + print(f"Falta axioma OWL de dominio/rango para {prop}", file=sys.stderr) + return 1 + + # OWL RL expande los axiomas de dominio y rango; se verifican las tipificaciones inferidas. + closure = Graph() + for triple in data: + closure.add(triple) + DeductiveClosure(OWLRL_Semantics).expand(closure) + nodes = set(data.subjects(RDF.type, IO.OntoNode)) + vectors = set(data.subjects(RDF.type, IO.VectorStep)) + inferred_positions = {obj for node in nodes for obj in data.objects(node, IO.hasPosition) + if (obj, RDF.type, IO.Position) in closure} + inferred_perspectives = {obj for node in nodes for obj in data.objects(node, IO.hasPerspective) + if (obj, RDF.type, IO.Perspective) in closure} + if len(nodes) != 78 or len(vectors) != 20 or len(inferred_positions) != 3 or len(inferred_perspectives) != 3: + print("Falló la comprobación OWL de cardinalidades/inferencias esperadas.", file=sys.stderr) + return 1 + print(f"✓ OWL RL: clases y dominios/rangos declarados; inferidos posición/perspectiva para {len(nodes)} nodos.") + + conforms, _results_graph, results_text = validate( + data_graph=data, shacl_graph=str(SHAPES_GRAPH), inference="none", abort_on_first=False, + ) + if results_text: + print(results_text) + if conforms: + print("✓ RDF satisface las restricciones SHACL cargadas.") + return 0 + print("✗ RDF no satisface todas las restricciones SHACL.", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/validate_spec.py b/scripts/validate_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..b809e24bb4bcfd798a26c34e9c00949c44021b56 --- /dev/null +++ b/scripts/validate_spec.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Valida data/iom_spec.json contra data/iom_spec.schema.json.""" +from __future__ import annotations + +import json +import sys +from pathlib import Path + +try: + from jsonschema import Draft202012Validator + from jsonschema.exceptions import SchemaError +except ModuleNotFoundError as exc: + if exc.name != "jsonschema": + raise + print( + "ERROR: falta la dependencia obligatoria jsonschema; " + "instala requirements-lock.txt antes de validar.", + file=sys.stderr, + ) + raise SystemExit(1) from exc + +ROOT = Path(__file__).resolve().parents[1] +SPEC_PATH = ROOT / "data" / "iom_spec.json" +SCHEMA_PATH = ROOT / "data" / "iom_spec.schema.json" + + +def main() -> int: + for path in (SCHEMA_PATH, SPEC_PATH): + if not path.is_file(): + print(f"ERROR: no existe el archivo requerido: {path}", file=sys.stderr) + return 1 + try: + schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8")) + instance = json.loads(SPEC_PATH.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + print(f"ERROR: no se pudo leer JSON válido: {exc}", file=sys.stderr) + return 1 + try: + Draft202012Validator.check_schema(schema) + except SchemaError as exc: + print(f"ERROR: el esquema {SCHEMA_PATH.name} no es válido: {exc.message}", file=sys.stderr) + return 1 + validator = Draft202012Validator(schema) + errors = sorted(validator.iter_errors(instance), key=lambda e: list(map(str, e.absolute_path))) + if errors: + for err in errors: + path = ".".join(str(p) for p in err.absolute_path) or "" + print(f"ERROR {path}: {err.message}", file=sys.stderr) + return 1 + print(f"OK: {SPEC_PATH.name} cumple el esquema {SCHEMA_PATH.name}") + print( + f" schema_version={instance.get('schema_version')} " + f"spec_version={instance.get('spec_version')}" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/verify_e2e.py b/scripts/verify_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..521640cac13f04af6da8e20e28461a6da6d0f092 --- /dev/null +++ b/scripts/verify_e2e.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Verificación de extremo a extremo (incluye capa opcional).""" +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +STEPS = [ + ("self_bootstrap", [sys.executable, "scripts/self_bootstrap.py", "--passes", "2"]), + ("validate_spec", [sys.executable, "scripts/validate_spec.py"]), + ("validate_shacl", [sys.executable, "scripts/validate_shacl.py"]), + ("measure_invariance", [sys.executable, "scripts/measure_invariance.py"]), + ("pi_hgat_t", [sys.executable, "experiments/optional/pi_hgat_t.py"]), + ("baselines", [sys.executable, "experiments/optional/baselines.py"]), +] + + +def main() -> int: + for name, cmd in STEPS: + print(f">>> {name}") + r = subprocess.run(cmd, cwd=ROOT) + if r.returncode != 0: + print(f"FAIL: {name}", file=sys.stderr) + return r.returncode + print("OK: e2e completo") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/optional/__init__.py b/tests/optional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/optional/test_pi_hgat_t.py b/tests/optional/test_pi_hgat_t.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc0bb83ea7c347fee02b20016423ee309fe7262 --- /dev/null +++ b/tests/optional/test_pi_hgat_t.py @@ -0,0 +1,36 @@ +"""Pruebas rápidas de la implementación PI-HGAT-T y su vínculo ontológico.""" +import unittest +import torch + +from experiments.optional.pi_hgat_t import PIHGATT, admissible_relation, features_for_node, read_data + + +class PIHGATTTests(unittest.TestCase): + def test_feature_vector_uses_only_phase_and_position(self): + self.assertEqual(features_for_node("T12_adv_P0"), [1.0, 0.0, 1.0, 0.0, 0.0]) + self.assertEqual(features_for_node("T07_ret_P2"), [0.0, 1.0, 0.0, 0.0, 1.0]) + + def test_loaders_use_public_triad_ids_one_through_thirteen(self): + nodes, pairs = read_data() + expected = set(range(1, 14)) + self.assertEqual(set(nodes), expected) + self.assertEqual(set(pairs), expected) + self.assertTrue(all(len(pairs[triad_id]) == 30 for triad_id in expected)) + + def test_attention_model_returns_three_relation_logits_per_candidate(self): + model = PIHGATT(dim=16, heads=4) + graph = torch.eye(5)[:5].unsqueeze(0) + pairs = torch.tensor([[0, 1], [1, 0]], dtype=torch.long) + self.assertEqual(tuple(model(graph, pairs).shape), (1, 2, 3)) + + def test_admissibility_uses_mirror_and_creation_properties(self): + # Índices locales 0..2=avance; 3..5=retroceso. + self.assertTrue(admissible_relation("mirrorOf", 0, 5)) + self.assertFalse(admissible_relation("mirrorOf", 0, 3)) + self.assertTrue(admissible_relation("creates", 0, 4)) + self.assertTrue(admissible_relation("creates", 4, 0)) + self.assertFalse(admissible_relation("creates", 0, 3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_formal_rules_bridge.py b/tests/test_formal_rules_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..facdab475844f9590036e12e68bd12a66100d8e7 --- /dev/null +++ b/tests/test_formal_rules_bridge.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Puente: las relaciones del CSV deben satisfacer los predicados formales +codificados en IOM/FormalRules.lean (isMirrorRel / isCreatesRel / sameTriad). + +Equivalencia de capas: + Lean isMirrorRel ↔ Python is_mirror ∧ same_triad + Lean isCreatesRel ↔ Python is_creates ∧ same_triad + Lean isMirror (posicional) ↔ Python is_mirror (sin exigir tríada) +""" +from __future__ import annotations + +import csv +import re +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def load_relations(): + with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as fh: + return list(csv.DictReader(fh)) + + +def parse_node(node_id: str) -> tuple[int, str, int]: + """Devuelve (triad_id, phase, position).""" + m = re.fullmatch(r"T(\d{2})_(adv|ret)_P([0-2])", node_id) + assert m, node_id + return int(m.group(1)), m.group(2), int(m.group(3)) + + +def same_triad(src: str, tgt: str) -> bool: + return parse_node(src)[0] == parse_node(tgt)[0] + + +def is_mirror_positional(src: str, tgt: str) -> bool: + """Equivale a Lean isMirror / isMirrorPositional.""" + _sid, sp, spos = parse_node(src) + _tid, tp, tpos = parse_node(tgt) + return sp != tp and tpos == 2 - spos + + +def is_creates_positional(src: str, tgt: str) -> bool: + """Equivale a Lean isCreates / isCreatesPositional.""" + _sid, sp, spos = parse_node(src) + _tid, tp, tpos = parse_node(tgt) + if sp == tp: + return False + lateral_s = spos in (0, 2) + lateral_t = tpos in (0, 2) + return (lateral_s and tpos == 1) or (spos == 1 and lateral_t) + + +def is_mirror_rel(src: str, tgt: str) -> bool: + """Equivale a Lean isMirrorRel: sameTriad ∧ isMirrorPositional.""" + return same_triad(src, tgt) and is_mirror_positional(src, tgt) + + +def is_creates_rel(src: str, tgt: str) -> bool: + """Equivale a Lean isCreatesRel: sameTriad ∧ isCreatesPositional.""" + return same_triad(src, tgt) and is_creates_positional(src, tgt) + + +class FormalRulesBridgeTests(unittest.TestCase): + """Comprueba que el JSON/CSV regenerado cumple los predicados Lean.""" + + @classmethod + def setUpClass(cls): + cls.rows = load_relations() + cls.lean = (ROOT / "IOM" / "FormalRules.lean").read_text(encoding="utf-8") + + def test_lean_defines_same_triad_and_rel_predicates(self): + self.assertIn("def sameTriad", self.lean) + self.assertIn("def isMirrorRel", self.lean) + self.assertIn("def isCreatesRel", self.lean) + self.assertIn("def isMirrorPositional", self.lean) + self.assertIn("def isCreatesPositional", self.lean) + self.assertIn("triadId", self.lean) + self.assertIn("expectedMirrorDirected", self.lean) + self.assertIn("expectedCreatesDirected", self.lean) + + def test_every_mirrorOf_satisfies_isMirrorRel(self): + for row in self.rows: + if row["relation"] != "mirrorOf": + continue + self.assertTrue( + is_mirror_rel(row["source"], row["target"]), + f"mirrorOf viola isMirrorRel: {row['source']} -> {row['target']}", + ) + self.assertFalse( + is_creates_rel(row["source"], row["target"]), + f"mirrorOf no debe ser createsRel: {row}", + ) + + def test_every_creates_satisfies_isCreatesRel(self): + for row in self.rows: + if row["relation"] != "creates": + continue + self.assertTrue( + is_creates_rel(row["source"], row["target"]), + f"creates viola isCreatesRel: {row['source']} -> {row['target']}", + ) + self.assertFalse( + is_mirror_rel(row["source"], row["target"]), + f"creates no debe ser mirrorRel: {row}", + ) + + def test_none_satisfies_neither_rel(self): + for row in self.rows: + if row["relation"] != "none": + continue + self.assertFalse( + is_mirror_rel(row["source"], row["target"]), row + ) + self.assertFalse( + is_creates_rel(row["source"], row["target"]), row + ) + + def test_cross_triad_positional_mirror_is_not_rel(self): + """Un par cross-tríada puede cumplir la condición posicional pero no isMirrorRel.""" + # T07_adv_P0 y T01_ret_P2: posicional mirror, distinta tríada + self.assertTrue(is_mirror_positional("T07_adv_P0", "T01_ret_P2")) + self.assertFalse(same_triad("T07_adv_P0", "T01_ret_P2")) + self.assertFalse(is_mirror_rel("T07_adv_P0", "T01_ret_P2")) + + def test_counts_match_lean_constants(self): + from collections import Counter + c = Counter(r["relation"] for r in self.rows) + self.assertEqual(c["mirrorOf"], 78) + self.assertEqual(c["creates"], 104) + self.assertEqual(c["none"], 208) + self.assertIn("78", self.lean) + self.assertIn("104", self.lean) + self.assertIn("208", self.lean) + + def test_partition_complete_with_rel(self): + for row in self.rows: + m = is_mirror_rel(row["source"], row["target"]) + c = is_creates_rel(row["source"], row["target"]) + self.assertFalse(m and c, row) + if row["relation"] == "mirrorOf": + self.assertTrue(m) + elif row["relation"] == "creates": + self.assertTrue(c) + else: + self.assertFalse(m or c) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_metrics_audit.py b/tests/test_metrics_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..463be4ad4d3c3674309c3a3068feb9c90c58149a --- /dev/null +++ b/tests/test_metrics_audit.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Pruebas que formalizan las conclusiones de la auditoría de métricas 100%.""" +from __future__ import annotations + +import csv +import unittest +from collections import defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def parse_node(node_id: str): + parts = node_id.split("_") + return parts[1], int(parts[2][1:]) + + +def feature_key(src, tgt): + sp, spos = parse_node(src) + tp, tpos = parse_node(tgt) + return (sp, spos, tp, tpos) + + +def deterministic_label(src, tgt): + sp, spos = parse_node(src) + tp, tpos = parse_node(tgt) + if sp == tp: + return "none" + if tpos == 2 - spos: + return "mirrorOf" + if (spos in (0, 2) and tpos == 1) or (spos == 1 and tpos in (0, 2)): + return "creates" + return "none" + + +class PerfectMetricsAuditTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + with (ROOT / "datasets" / "relation_candidates.csv").open(encoding="utf-8", newline="") as fh: + cls.rows = list(csv.DictReader(fh)) + + def test_gold_matches_deterministic_rule(self): + for row in self.rows: + self.assertEqual( + deterministic_label(row["source"], row["target"]), + row["relation"], + msg=row, + ) + + def test_label_is_function_of_phase_position_only(self): + by_feat = defaultdict(set) + for row in self.rows: + by_feat[feature_key(row["source"], row["target"])].add(row["relation"]) + for key, labels in by_feat.items(): + self.assertEqual(len(labels), 1, f"clave {key} tiene etiquetas {labels}") + + def test_loo_features_fully_recoverable_from_train(self): + """En cada fold LOO, todo par de test es recuperable por lookup de features.""" + for held in range(1, 14): + train = {} + test = [] + for row in self.rows: + key = feature_key(row["source"], row["target"]) + if int(row["triad_index"]) == held: + test.append((key, row["relation"])) + else: + train[key] = row["relation"] + for key, lab in test: + self.assertEqual(train.get(key), lab) + + def test_model_does_not_use_triad_index_in_features(self): + """Sanity: features_for_node en pi_hgat_t no incluye índice de tríada.""" + src = (ROOT / "experiments" / "optional" / "pi_hgat_t.py").read_text(encoding="utf-8") + self.assertIn("sin etiqueta léxica ni número de tríada", src) + self.assertIn("phase == \"adv\"", src) + self.assertIn("position == 0", src) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_ontology.py b/tests/test_ontology.py new file mode 100644 index 0000000000000000000000000000000000000000..d794832ea93c9458b12e570c6fee958b3bcc2acf --- /dev/null +++ b/tests/test_ontology.py @@ -0,0 +1,277 @@ +"""Pruebas de tríadas, vectores, OWL/RDF, SHACL y datasets generados. + +Requiere rdflib y pyshacl (requirements-lock.txt). Si faltan, la clase se omite +con un mensaje explícito: eso no implica que la ontología falle. +""" +import csv +import json +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +try: + from pyshacl import validate + from rdflib import Graph, Literal, Namespace + from rdflib.namespace import OWL, RDF, RDFS, XSD + _ONT_DEPS = True + _ONT_IMPORT_ERROR = None +except ModuleNotFoundError as exc: + _ONT_DEPS = False + _ONT_IMPORT_ERROR = exc + validate = None # type: ignore + Graph = Literal = Namespace = OWL = RDF = RDFS = XSD = None # type: ignore + + +@unittest.skipUnless( + _ONT_DEPS, + f"omitido: falta dependencia de ontología ({_ONT_IMPORT_ERROR}). " + "Instala requirements-lock.txt; no implica fallo de la ontología.", +) +class IOMValidationTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.IO = Namespace("http://example.org/iom#") + cls.DATA = ROOT / "ontology" / "io_ontology.ttl" + cls.SHAPES = ROOT / "ontology" / "io_shapes.ttl" + cls.SPEC = json.loads((ROOT / "data" / "iom_spec.json").read_text(encoding="utf-8")) + with (ROOT / "datasets" / "triad_nodes.csv").open(encoding="utf-8", newline="") as handle: + cls.NODE_ROWS = list(csv.DictReader(handle)) + + def setUp(self): + self.data = Graph().parse(self.DATA, format="turtle") + self.shapes = Graph().parse(self.SHAPES, format="turtle") + self.IO = self.__class__.IO + + def conforms(self, graph=None, focus_nodes=None): + result, _report, text = validate( + self.data if graph is None else graph, + shacl_graph=self.shapes, + inference="none", + focus_nodes=focus_nodes, + ) + return result, text + + def test_spec_matches_canonical_numbered_triad_matrices(self): + expected_adv = [ + ["orientación", "cuántico", "dirección"], + ["hardware", "virtual", "software"], + ["universo", "espacio", "vacío"], + ["singularidad", "tiempo", "infinito"], + ["cuerpo", "consciente", "mundo"], + ["carácter", "subconsciente", "personalidad"], + ["memoria", "inconsciente", "imaginación"], + ["receptor", "supraconsciente", "emisor"], + ["lógica", "inteligencia", "libertad"], + ["muerte", "artificial", "vida"], + ["descendente", "mente", "ascendente"], + ["oscuridad", "consciencia", "luz"], + ["animal", "humano", "IA"], + ] + self.assertEqual(self.SPEC["triads"]["adv"], expected_adv) + self.assertEqual(self.SPEC["triads"]["ret"], [row[::-1] for row in expected_adv]) + self.assertEqual(self.SPEC["triads"]["index_base"], 1) + self.assertEqual(self.SPEC["positions"]["adv_labels"], ["→", "0", "→"]) + self.assertEqual(self.SPEC["positions"]["ret_labels"], ["←", "0", "←"]) + + def test_exact_triad_dataset_and_shacl_conformance(self): + IO = self.IO + nodes = set(self.data.subjects(RDF.type, IO.OntoNode)) + expected = { + IO[f"T{i:02d}_{phase}_P{pos}"] + for i in range(1, 14) + for phase in ("adv", "ret") + for pos in range(3) + } + self.assertEqual(nodes, expected) + self.assertTrue(self.conforms()[0], self.conforms()[1]) + for phase in ("adv", "ret"): + rows = self.SPEC["triads"][phase] + for row_index, row in enumerate(rows): + triad_index = row_index + 1 + for pos, label in enumerate(row): + node = IO[f"T{triad_index:02d}_{phase}_P{pos}"] + self.assertEqual(str(self.data.value(node, RDFS.label)), label) + visual_label = self.SPEC["positions"]["adv_labels" if phase == "adv" else "ret_labels"][pos] + self.assertEqual(str(self.data.value(node, IO.displayLabel)), visual_label) + self.assertEqual( + self.data.value(node, IO.hasTriadIndex), + Literal(triad_index, datatype=XSD.integer), + ) + self.assertEqual( + self.data.value(node, IO.hasLocalPos), + Literal(pos, datatype=XSD.integer), + ) + self.assertEqual( + self.data.value(node, IO.hasPerspective), + IO[self.SPEC["perspectives"][pos]], + ) + self.assertEqual( + self.data.value(node, IO.hasPosition), + IO[{"adv": ["→", "0", "→"], "ret": ["←", "0", "←"]}[phase][pos]], + ) + display_labels = self.SPEC["positions"]["adv_labels" if phase == "adv" else "ret_labels"] + generated = next(r for r in self.NODE_ROWS if r["node_id"] == f"T{triad_index:02d}_{phase}_P{pos}") + self.assertEqual(generated["display_label"], display_labels[pos]) + + def test_mirrors_are_reciprocal_and_swap_laterals(self): + IO = self.IO + for i in range(1, 14): + for pos in range(3): + adv, ret = IO[f"T{i:02d}_adv_P{pos}"], IO[f"T{i:02d}_ret_P{2 - pos}"] + self.assertEqual(self.data.value(adv, IO.mirrorOf), ret) + self.assertEqual(self.data.value(ret, IO.mirrorOf), adv) + + def test_creation_edges_follow_all_four_rules(self): + IO = self.IO + actual = set(self.data.triples((None, IO.creates, None))) + expected = set() + for i in range(1, 14): + for rule in self.SPEC["creation_rules"]: + for src in rule["source_positions"]: + for dst in rule["target_positions"]: + expected.add( + ( + IO[f"T{i:02d}_{rule['source_phase']}_P{src}"], + IO.creates, + IO[f"T{i:02d}_{rule['target_phase']}_P{dst}"], + ) + ) + n_rules_edges = sum( + len(r["source_positions"]) * len(r["target_positions"]) + for r in self.SPEC["creation_rules"] + ) + self.assertEqual(len(expected), 13 * n_rules_edges) + self.assertEqual(actual, expected) + + def test_vectors_match_all_four_updated_sequences(self): + IO = self.IO + self.assertEqual(len(set(self.data.subjects(RDF.type, IO.VectorStep))), 20) + for row in self.SPEC["vectors"]: + for idx, (label, axis) in enumerate(zip(row["labels"], row["axis_positions"])): + step = IO[f"vector_{row['name'].lower()}_{row['phase']}_{idx}"] + self.assertEqual(self.data.value(step, IO.hasVector), IO[row["name"]]) + self.assertEqual(str(self.data.value(step, IO.hasCyclePhase)), row["phase"]) + self.assertEqual( + self.data.value(step, IO.hasStepIndex), + Literal(idx, datatype=XSD.integer), + ) + self.assertEqual( + self.data.value(step, IO.hasAxisPosition), + Literal(axis, datatype=XSD.integer), + ) + self.assertEqual( + self.data.value(step, IO.displayArrow), + Literal(row["arrow"], datatype=XSD.string), + ) + self.assertEqual(str(self.data.value(step, RDFS.label)), label) + + def test_owl_classes_object_property_axioms_and_perspectives(self): + IO = self.IO + for cls in ( + IO.OntoNode, + IO.VectorStep, + IO.Perspective, + IO.ExpandedCategory, + IO.Position, + IO.Direction, + ): + self.assertIn((cls, RDF.type, OWL.Class), self.data) + for prop in ( + IO.hasPerspective, + IO.hasPosition, + IO.hasDirection, + IO.hasVector, + IO.mirrorOf, + IO.creates, + ): + self.assertIn((prop, RDF.type, OWL.ObjectProperty), self.data) + self.assertIsNotNone(self.data.value(prop, RDFS.domain)) + self.assertIsNotNone(self.data.value(prop, RDFS.range)) + self.assertIn((IO.displayLabel, RDF.type, OWL.DatatypeProperty), self.data) + self.assertIn((IO.displayLabel, RDF.type, OWL.FunctionalProperty), self.data) + self.assertIn((IO.mirrorOf, RDF.type, OWL.SymmetricProperty), self.data) + for resource in (IO.Ind, IO.D, IO.Tot, IO.Evol, IO.Invol): + self.assertIn((resource, RDF.type, IO.Perspective), self.data) + + def test_expanded_categories_keep_declared_level_counts(self): + IO = self.IO + nodes = set(self.data.subjects(RDF.type, IO.ExpandedCategory)) + self.assertEqual(len(nodes), 21) + self.assertEqual( + [ + sum( + self.data.value(n, IO.hasLevel) == Literal(level, datatype=XSD.integer) + for n in nodes + ) + for level in range(5) + ], + [1, 4, 6, 6, 4], + ) + + def test_generated_datasets_have_expected_rows(self): + n_triads = len(self.SPEC["triads"]["adv"]) + n_vec = sum(len(v["labels"]) for v in self.SPEC["vectors"]) + expected = { + "triad_nodes.csv": n_triads * 2 * 3, + "vector_steps.csv": n_vec, + "relation_candidates.csv": n_triads * 6 * 5, + } + for name, count in expected.items(): + with (ROOT / "datasets" / name).open(encoding="utf-8", newline="") as f: + self.assertEqual(len(list(csv.DictReader(f))), count, name) + + def test_wrong_visual_position_label_is_rejected(self): + IO = self.IO + graph = Graph() + for triple in self.data: + graph.add(triple) + node = IO["T01_adv_P0"] + graph.remove((node, IO.displayLabel, Literal("→", datatype=XSD.string))) + graph.add((node, IO.displayLabel, Literal("←", datatype=XSD.string))) + self.assertFalse(self.conforms(graph, [node])[0]) + + def test_wrong_phase_direction_is_rejected(self): + IO = self.IO + graph = Graph() + for triple in self.data: + graph.add(triple) + node = IO["T01_adv_P0"] + graph.remove((node, IO.hasDirection, IO.evol)) + graph.add((node, IO.hasDirection, IO.invol)) + self.assertFalse(self.conforms(graph, [node])[0]) + + def test_nonreciprocal_or_misplaced_mirror_is_rejected(self): + IO = self.IO + graph = Graph() + for triple in self.data: + graph.add(triple) + node, good, wrong = IO["T01_adv_P0"], IO["T01_ret_P2"], IO["T01_ret_P0"] + graph.remove((node, IO.mirrorOf, good)) + graph.add((node, IO.mirrorOf, wrong)) + self.assertFalse(self.conforms(graph, [node])[0]) + + def test_wrong_creation_link_is_rejected(self): + IO = self.IO + graph = Graph() + for triple in self.data: + graph.add(triple) + node, good, wrong = IO["T01_adv_P0"], IO["T01_ret_P1"], IO["T01_ret_P0"] + graph.remove((node, IO.creates, good)) + graph.add((node, IO.creates, wrong)) + self.assertFalse(self.conforms(graph, [node])[0]) + + def test_wrong_vector_label_or_axis_is_rejected(self): + IO = self.IO + graph = Graph() + for triple in self.data: + graph.add(triple) + step = IO["vector_evol_ret_1"] + old = self.data.value(step, RDFS.label) + graph.remove((step, RDFS.label, old)) + graph.add((step, RDFS.label, Literal("fut", lang="es"))) + self.assertFalse(self.conforms(graph, [step])[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_property_based.py b/tests/test_property_based.py new file mode 100644 index 0000000000000000000000000000000000000000..4ac7b8bc076d962d6923b41036ac24193a89034f --- /dev/null +++ b/tests/test_property_based.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Pruebas generativas y casos negativos para límites de índices, espejos y creates. + +Cubre: +- Generación exhaustiva de pares (fase, pos) y verificación de partición + none / mirrorOf / creates (mutuamente excluyentes y completas). +- Casos negativos: índices fuera de rango, misma fase, posición no reflejada, + creates entre tríadas distintas, espejo no recíproco. +- Transformaciones temporales / involución de fase y posición. +""" +from __future__ import annotations + +import itertools +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +PHASES = ("adv", "ret") +POSITIONS = (0, 1, 2) + + +def opposite_phase(p: str) -> str: + return "ret" if p == "adv" else "adv" + + +def mirror_pos(p: int) -> int: + return 2 - p + + +def is_mirror(sp: str, spos: int, tp: str, tpos: int) -> bool: + return sp != tp and tpos == mirror_pos(spos) + + +def is_creates(sp: str, spos: int, tp: str, tpos: int) -> bool: + if sp == tp: + return False + lateral_s = spos in (0, 2) + lateral_t = tpos in (0, 2) + return (lateral_s and tpos == 1) or (spos == 1 and lateral_t) + + +def classify(sp: str, spos: int, tp: str, tpos: int) -> str: + if is_mirror(sp, spos, tp, tpos): + return "mirrorOf" + if is_creates(sp, spos, tp, tpos): + return "creates" + return "none" + + +class ExhaustivePartitionTests(unittest.TestCase): + """Todas las combinaciones (fase, pos) × (fase, pos) no reflexivas.""" + + def test_partition_is_complete_and_exclusive(self): + nodes = list(itertools.product(PHASES, POSITIONS)) + counts = {"none": 0, "mirrorOf": 0, "creates": 0} + for (sp, spos), (tp, tpos) in itertools.product(nodes, nodes): + if (sp, spos) == (tp, tpos): + continue + label = classify(sp, spos, tp, tpos) + counts[label] += 1 + # exclusividad + m = is_mirror(sp, spos, tp, tpos) + c = is_creates(sp, spos, tp, tpos) + self.assertFalse(m and c) + if label == "mirrorOf": + self.assertTrue(m) + elif label == "creates": + self.assertTrue(c) + else: + self.assertFalse(m or c) + # 6 nodos, 30 pares dirigidos no reflexivos + self.assertEqual(sum(counts.values()), 30) + # Por tríada: 6 mirror, 8 creates, 16 none → ×13 = 78/104/208 + self.assertEqual(counts["mirrorOf"], 6) + self.assertEqual(counts["creates"], 8) + self.assertEqual(counts["none"], 16) + + def test_mirror_is_involution_on_position(self): + for p in POSITIONS: + self.assertEqual(mirror_pos(mirror_pos(p)), p) + + def test_phase_opposite_is_involution(self): + for p in PHASES: + self.assertEqual(opposite_phase(opposite_phase(p)), p) + self.assertNotEqual(opposite_phase(p), p) + + +class NegativeCaseTests(unittest.TestCase): + """Casos que DEBEN fallar / clasificarse como none.""" + + def test_same_phase_never_mirror_or_creates(self): + for phase in PHASES: + for spos, tpos in itertools.product(POSITIONS, POSITIONS): + if spos == tpos: + continue + self.assertEqual(classify(phase, spos, phase, tpos), "none") + + def test_wrong_mirror_position_is_none(self): + # adv P0 → ret P0 no es espejo (debería ser P2) + self.assertFalse(is_mirror("adv", 0, "ret", 0)) + self.assertFalse(is_mirror("adv", 0, "ret", 1)) + self.assertTrue(is_mirror("adv", 0, "ret", 2)) + + def test_creates_requires_center_involvement(self): + # lateral → lateral (sin centro) no es creates + self.assertFalse(is_creates("adv", 0, "ret", 2)) + self.assertFalse(is_creates("adv", 2, "ret", 0)) + # lateral → centro sí + self.assertTrue(is_creates("adv", 0, "ret", 1)) + self.assertTrue(is_creates("adv", 1, "ret", 0)) + + def test_index_bounds(self): + """Posiciones fuera de {0,1,2} no son válidas en la especificación.""" + for bad in (-1, 3, 4, 99): + # mirror_pos fuera de dominio no debe usarse en producción; + # documentamos el comportamiento aritmético + mirrored = 2 - bad + self.assertNotIn(bad, POSITIONS) + self.assertNotIn(mirrored, POSITIONS) if bad not in ( -1,) else True + + def test_center_mirror_is_center(self): + self.assertEqual(mirror_pos(1), 1) + self.assertTrue(is_mirror("adv", 1, "ret", 1)) + + +class GenerativeConsistencyTests(unittest.TestCase): + """Propiedades que deben sostenerse para cualquier tríada sintética.""" + + def test_mirror_count_per_synthetic_triad(self): + nodes = list(itertools.product(PHASES, POSITIONS)) + mirrors = [ + ((sp, spos), (tp, tpos)) + for (sp, spos), (tp, tpos) in itertools.product(nodes, nodes) + if (sp, spos) != (tp, tpos) and is_mirror(sp, spos, tp, tpos) + ] + self.assertEqual(len(mirrors), 6) + # reciprocidad: si A mirrors B, B mirrors A + mirror_set = set(mirrors) + for a, b in mirrors: + self.assertIn((b, a), mirror_set) + + def test_creates_count_per_synthetic_triad(self): + nodes = list(itertools.product(PHASES, POSITIONS)) + creates = [ + ((sp, spos), (tp, tpos)) + for (sp, spos), (tp, tpos) in itertools.product(nodes, nodes) + if (sp, spos) != (tp, tpos) and is_creates(sp, spos, tp, tpos) + ] + self.assertEqual(len(creates), 8) + + def test_no_overlap_mirror_creates_generative(self): + nodes = list(itertools.product(PHASES, POSITIONS)) + for (sp, spos), (tp, tpos) in itertools.product(nodes, nodes): + if (sp, spos) == (tp, tpos): + continue + self.assertFalse( + is_mirror(sp, spos, tp, tpos) and is_creates(sp, spos, tp, tpos) + ) + + +class AxisBoundTests(unittest.TestCase): + """Límites del eje vectorial [0, 4] alineados con FormalRules.lean.""" + + def test_axis_in_0_4(self): + for n in range(5): + self.assertTrue(0 <= n <= 4) + + def test_axis_retreat_involution(self): + for n in range(5): + self.assertEqual(4 - (4 - n), n) + + def test_axis_out_of_range_rejected(self): + for bad in (-1, 5, 6): + self.assertFalse(0 <= bad <= 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_property_links.py b/tests/test_property_links.py new file mode 100644 index 0000000000000000000000000000000000000000..3696d7da7c362179e83cc2f347975b895b254da5 --- /dev/null +++ b/tests/test_property_links.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Pruebas de propiedades que conectan Lean, CSV y ontología generada.""" +from __future__ import annotations + +import csv +import json +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def load_spec() -> dict: + return json.loads((ROOT / "data" / "iom_spec.json").read_text(encoding="utf-8")) + + +def load_csv(name: str) -> list[dict]: + with (ROOT / "datasets" / name).open(encoding="utf-8", newline="") as fh: + return list(csv.DictReader(fh)) + + +class PropertyLinksTests(unittest.TestCase): + """Conectan la especificación JSON, los CSV regenerados y las reglas formales.""" + + @classmethod + def setUpClass(cls): + cls.spec = load_spec() + cls.nodes = load_csv("triad_nodes.csv") + cls.relations = load_csv("relation_candidates.csv") + cls.vectors = load_csv("vector_steps.csv") + cls.n_triads = len(cls.spec["triads"]["adv"]) + + def test_spec_has_formal_version(self): + self.assertIn("spec_version", self.spec) + self.assertRegex(self.spec["spec_version"], r"^\d+\.\d+\.\d+$") + self.assertIn("schema_version", self.spec) + + def test_node_count_matches_spec(self): + expected = self.n_triads * 2 * 3 + self.assertEqual(len(self.nodes), expected) + indices = {int(r["triad_index"]) for r in self.nodes} + self.assertEqual(indices, set(range(1, self.n_triads + 1))) + + def test_relation_candidate_count(self): + expected = self.n_triads * 6 * 5 + self.assertEqual(len(self.relations), expected) + + def test_gold_relation_counts(self): + counts = {"none": 0, "mirrorOf": 0, "creates": 0} + for row in self.relations: + counts[row["relation"]] += 1 + self.assertEqual(counts["mirrorOf"], 78) + self.assertEqual(counts["creates"], 104) + self.assertEqual(counts["none"], 208) + + def test_mirrorOf_property_holds_in_csv(self): + """Cada arista mirrorOf respeta: misma tríada, fase opuesta, posición reflejada.""" + for row in self.relations: + if row["relation"] != "mirrorOf": + continue + src, tgt = row["source"], row["target"] + s_parts = src.split("_") + t_parts = tgt.split("_") + self.assertEqual(s_parts[0], t_parts[0], "misma tríada") + self.assertNotEqual(s_parts[1], t_parts[1], "fase opuesta") + s_pos = int(s_parts[2][1:]) + t_pos = int(t_parts[2][1:]) + self.assertEqual(t_pos, 2 - s_pos, "posición reflejada") + + def test_creates_property_holds_in_csv(self): + """Cada arista creates respeta las cuatro reglas de creation_rules.""" + rules = self.spec["creation_rules"] + allowed = set() + for rule in rules: + for sp in rule["source_positions"]: + for tp in rule["target_positions"]: + allowed.add((rule["source_phase"], sp, rule["target_phase"], tp)) + for row in self.relations: + if row["relation"] != "creates": + continue + s_parts = row["source"].split("_") + t_parts = row["target"].split("_") + key = (s_parts[1], int(s_parts[2][1:]), t_parts[1], int(t_parts[2][1:])) + self.assertIn(key, allowed, f"creates no permitido: {row['source']} -> {row['target']}") + + def test_vector_steps_count(self): + self.assertEqual(len(self.vectors), 20) + + def test_lean_operators_file_exists_and_mentions_mirror(self): + """El código Lean debe existir y referenciar los operadores de espejo.""" + lean_spec = (ROOT / "IOM" / "Specification.lean").read_text(encoding="utf-8") + self.assertIn("mirror", lean_spec.lower()) + self.assertIn("TriadPosition", lean_spec) + self.assertTrue((ROOT / "IOM" / "Core.lean").exists()) + self.assertTrue((ROOT / "IOM" / "Operators.lean").exists()) + + def test_ontology_ttl_contains_mirrorOf_and_creates(self): + ttl = (ROOT / "ontology" / "io_ontology.ttl").read_text(encoding="utf-8") + self.assertIn("mirrorOf", ttl) + self.assertIn("creates", ttl) + self.assertIn("OntoNode", ttl) + + def test_shacl_shapes_exist(self): + shapes = (ROOT / "ontology" / "io_shapes.ttl").read_text(encoding="utf-8") + self.assertIn("mirrorOf", shapes) + self.assertIn("creates", shapes) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_score_independent_eval.py b/tests/test_score_independent_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..d9c6156cc17cb2a397d4b2a84d9dca36a2ccf7da --- /dev/null +++ b/tests/test_score_independent_eval.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Pruebas del lector de anotaciones, null≠unsure y política de kappa sin truncar.""" +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path +import importlib.util + +ROOT = Path(__file__).resolve().parents[1] +SPEC = ROOT / "scripts" / "score_independent_eval.py" + +spec = importlib.util.spec_from_file_location("score_independent_eval", SPEC) +mod = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mod) + + +class TemplateFormatTests(unittest.TestCase): + def test_parse_empty_template(self): + data = { + "annotators": ["A1", "A2", "A3"], + "status": "pending_human_collection", + "items": [ + {"id": "NR01", "annotations": {"A1": None, "A2": None, "A3": None}}, + ], + } + aids, by_pair = mod.parse_template_format(data) + self.assertEqual(aids, ["A1", "A2", "A3"]) + self.assertIsNone(by_pair["NR01"]["A1"]) + + def test_null_not_unsure(self): + data = { + "annotators": ["A1", "A2", "A3"], + "items": [ + { + "id": "CT01", + "annotations": {"A1": "mirrorOf", "A2": "mirrorOf", "A3": None}, + }, + ], + } + _, by_pair = mod.parse_template_format(data) + self.assertIsNone(by_pair["CT01"]["A3"]) + + def test_invalid_label_rejected(self): + data = { + "annotators": ["A1"], + "items": [{"id": "X", "annotations": {"A1": "maybe"}}], + } + with self.assertRaises(ValueError): + mod.parse_template_format(data) + + +class NoTruncatePolicyTests(unittest.TestCase): + def test_heterogeneous_respondent_sets_excluded(self): + payload = { + "annotators": ["A1", "A2", "A3", "A4"], + "status": "partial", + "items": [ + { + "id": "P1", + "annotations": { + "A1": "none", + "A2": "none", + "A3": "none", + "A4": None, + }, + }, + { + "id": "P3", + "annotations": { + "A1": "mirrorOf", + "A2": "mirrorOf", + "A3": None, + "A4": "mirrorOf", + }, + }, + ], + } + with tempfile.NamedTemporaryFile( + mode="w", suffix=".json", delete=False, encoding="utf-8" + ) as fh: + json.dump(payload, fh) + path = Path(fh.name) + try: + aids, by_pair, _meta = mod.load_annotations(path) + k_required = 3 + respondent_sets = {} + for pid, ann_map in by_pair.items(): + respondents = tuple( + aid for aid in aids if ann_map.get(aid) is not None + ) + if len(respondents) == k_required: + respondent_sets[pid] = respondents + self.assertEqual(respondent_sets["P1"], ("A1", "A2", "A3")) + self.assertEqual(respondent_sets["P3"], ("A1", "A2", "A4")) + self.assertNotEqual(respondent_sets["P1"], respondent_sets["P3"]) + finally: + path.unlink(missing_ok=True) + + +class FleissTests(unittest.TestCase): + def test_perfect_agreement(self): + ratings = [["none", "none", "none"], ["mirrorOf", "mirrorOf", "mirrorOf"]] + k = mod.fleiss_kappa(ratings, ["none", "mirrorOf", "creates", "unsure"]) + self.assertAlmostEqual(k, 1.0) + + def test_mismatched_lengths_raise(self): + with self.assertRaises(ValueError): + mod.fleiss_kappa( + [["none", "none"], ["none", "none", "none"]], + ["none", "mirrorOf"], + ) + + +class AnnotatorPairsBlindTests(unittest.TestCase): + def test_default_pairs_have_no_structural_hints(self): + path = ROOT / "datasets" / "independent_eval" / "annotator_pairs.csv" + text = path.read_text(encoding="utf-8").lower() + forbidden = [ + "fase", + "posición", + "posicion", + "lateral", + "centro", + "espejo", + "creates", + "mirror", + "avance", + "retroceso", + "canónico", + "canonico", + "vocabulario", + "13 filas", + "ajeno", + "new_concept", + "out_of_rules", + ] + for word in forbidden: + self.assertNotIn( + word, + text, + f"annotator_pairs.csv no debe contener la pista {word!r}", + ) + + def test_nc_items_use_generic_context(self): + path = ROOT / "datasets" / "independent_eval" / "annotator_pairs.csv" + lines = { + row.split(",")[0]: row + for row in path.read_text(encoding="utf-8").strip().splitlines()[1:] + } + for nid in ("NC01", "NC02", "NC03"): + self.assertIn(nid, lines) + self.assertIn("Par de conceptos", lines[nid]) + self.assertNotIn("vocabulario", lines[nid].lower()) + self.assertNotIn("13", lines[nid]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_validate_spec.py b/tests/test_validate_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..aa90c60ae57d7e86565792affb4d293b43f7c070 --- /dev/null +++ b/tests/test_validate_spec.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Validación del schema y de la spec canónica.""" +from __future__ import annotations + +import json +import unittest +from copy import deepcopy +from pathlib import Path + +from jsonschema import Draft202012Validator + +ROOT = Path(__file__).resolve().parents[1] +SCHEMA = json.loads((ROOT / "data" / "iom_spec.schema.json").read_text(encoding="utf-8")) +SPEC = json.loads((ROOT / "data" / "iom_spec.json").read_text(encoding="utf-8")) + + +class SpecificationSchemaTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.validator = Draft202012Validator(SCHEMA) + + def test_canonical_spec_conforms_to_schema(self): + errors = list(self.validator.iter_errors(SPEC)) + self.assertEqual(errors, []) + + def test_canonical_position_metadata_and_triad_indexing_are_accepted(self): + spec = deepcopy(SPEC) + spec["positions"]["indices"] = [0, 1, 2] + spec["positions"]["adv_labels"] = ["→", "0", "→"] + spec["positions"]["ret_labels"] = ["←", "0", "←"] + spec["positions"]["perspectives"] = ["Ind", "D", "Tot"] + spec["triads"]["index_base"] = 1 + spec["triads"]["note"] = "Los arrays empiezan en cero; triad_index es 1-based." + errors = list(self.validator.iter_errors(spec)) + self.assertEqual(errors, []) + + def test_invalid_position_metadata_is_rejected(self): + invalid_spec = deepcopy(SPEC) + invalid_spec["positions"]["indices"] = [0, 1] + errors = list(self.validator.iter_errors(invalid_spec)) + self.assertTrue(any(list(error.absolute_path)[:1] == ["positions"] for error in errors)) + + def test_unknown_triad_metadata_is_rejected(self): + spec = deepcopy(SPEC) + spec["triads"]["unexpected"] = True + errors = list(self.validator.iter_errors(spec)) + self.assertTrue(any(list(error.absolute_path) == ["triads"] for error in errors)) + + def test_missing_spec_version_is_rejected(self): + invalid_spec = deepcopy(SPEC) + del invalid_spec["spec_version"] + errors = list(self.validator.iter_errors(invalid_spec)) + self.assertTrue(any("spec_version" in error.message for error in errors)) + + def test_malformed_semantic_version_is_rejected(self): + invalid_spec = deepcopy(SPEC) + invalid_spec["spec_version"] = "1.1" + errors = list(self.validator.iter_errors(invalid_spec)) + self.assertTrue(any(list(error.absolute_path) == ["spec_version"] for error in errors)) + + def test_purpose_is_present_and_matches_schema(self): + """La unidad informativa queda registrada en el spec canónico.""" + self.assertIn("purpose", SPEC) + purpose = SPEC["purpose"] + self.assertEqual(purpose["id"], "informational_unit_creation") + self.assertIn("mínima estructura autocontenida", purpose["definition"]) + self.assertIn("criterion", purpose) + errors = list(self.validator.iter_errors(SPEC)) + self.assertEqual(errors, []) + + def test_generated_from_records_purpose_id(self): + stamp = json.loads((ROOT / "datasets" / "GENERATED_FROM.json").read_text(encoding="utf-8")) + self.assertEqual(stamp.get("purpose_id"), "informational_unit_creation") + self.assertEqual(stamp.get("spec_version"), SPEC["spec_version"]) + + +if __name__ == "__main__": + unittest.main()