bokono 4.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bokono-4.0.0/LICENSE +34 -0
- bokono-4.0.0/PKG-INFO +118 -0
- bokono-4.0.0/README.md +91 -0
- bokono-4.0.0/bokono/__init__.py +14 -0
- bokono-4.0.0/bokono/agents/__init__.py +4 -0
- bokono-4.0.0/bokono/core/__init__.py +4 -0
- bokono-4.0.0/bokono/core/fa_encoder.py +355 -0
- bokono-4.0.0/bokono/core/fa_knowledge_public.json +3842 -0
- bokono-4.0.0/bokono/core/fa_matrix.py +208 -0
- bokono-4.0.0/bokono/ml/__init__.py +4 -0
- bokono-4.0.0/bokono/ml/activations.py +676 -0
- bokono-4.0.0/bokono/ml/benchmark.py +428 -0
- bokono-4.0.0/bokono/ml/layers.py +505 -0
- bokono-4.0.0/bokono/ml/network.py +431 -0
- bokono-4.0.0/bokono/ml/torch_activations.py +178 -0
- bokono-4.0.0/bokono/ml/torch_layers.py +261 -0
- bokono-4.0.0/bokono/ml/torch_loss.py +91 -0
- bokono-4.0.0/bokono/ml/torch_network.py +692 -0
- bokono-4.0.0/bokono/nlp/__init__.py +10 -0
- bokono-4.0.0/bokono/nlp/fa_transformer.py +336 -0
- bokono-4.0.0/bokono.egg-info/PKG-INFO +118 -0
- bokono-4.0.0/bokono.egg-info/SOURCES.txt +59 -0
- bokono-4.0.0/bokono.egg-info/dependency_links.txt +1 -0
- bokono-4.0.0/bokono.egg-info/requires.txt +8 -0
- bokono-4.0.0/bokono.egg-info/top_level.txt +2 -0
- bokono-4.0.0/bokono_ml_legacy/__init__.py +4 -0
- bokono-4.0.0/bokono_ml_legacy/activations.py +676 -0
- bokono-4.0.0/bokono_ml_legacy/benchmark.py +428 -0
- bokono-4.0.0/bokono_ml_legacy/benchmark_activations.py +133 -0
- bokono-4.0.0/bokono_ml_legacy/dashboard.py +186 -0
- bokono-4.0.0/bokono_ml_legacy/demo_agri_fanet.py +105 -0
- bokono-4.0.0/bokono_ml_legacy/demo_health_fanet.py +93 -0
- bokono-4.0.0/bokono_ml_legacy/demo_interactive.py +210 -0
- bokono-4.0.0/bokono_ml_legacy/fa_encoder.py +343 -0
- bokono-4.0.0/bokono_ml_legacy/fa_matrix.py +208 -0
- bokono-4.0.0/bokono_ml_legacy/layers.py +505 -0
- bokono-4.0.0/bokono_ml_legacy/network.py +431 -0
- bokono-4.0.0/bokono_ml_legacy/parse_fa.py +213 -0
- bokono-4.0.0/bokono_ml_legacy/torch_activations.py +178 -0
- bokono-4.0.0/bokono_ml_legacy/torch_layers.py +261 -0
- bokono-4.0.0/bokono_ml_legacy/torch_loss.py +91 -0
- bokono-4.0.0/bokono_ml_legacy/torch_network.py +618 -0
- bokono-4.0.0/pyproject.toml +47 -0
- bokono-4.0.0/setup.cfg +4 -0
- bokono-4.0.0/tests/test_calibration.py +140 -0
- bokono-4.0.0/tests/test_cross_validation.py +217 -0
- bokono-4.0.0/tests/test_cv_final.py +194 -0
- bokono-4.0.0/tests/test_cv_improved.py +213 -0
- bokono-4.0.0/tests/test_energy.py +253 -0
- bokono-4.0.0/tests/test_iot_timeseries.py +269 -0
- bokono-4.0.0/tests/test_mia.py +228 -0
- bokono-4.0.0/tests/test_noise_robustness.py +190 -0
- bokono-4.0.0/tests/test_ood.py +184 -0
- bokono-4.0.0/tests/test_regression.py +138 -0
- bokono-4.0.0/tests/test_v02.py +384 -0
- bokono-4.0.0/tests/test_v03.py +398 -0
- bokono-4.0.0/tests/test_v10.py +310 -0
- bokono-4.0.0/tests/test_v30.py +109 -0
- bokono-4.0.0/tests/test_week1.py +211 -0
- bokono-4.0.0/tests/test_week2.py +297 -0
- bokono-4.0.0/tests/test_week3.py +345 -0
bokono-4.0.0/LICENSE
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
LICENCE DE RECHERCHE ACADÉMIQUE ET D'ÉVALUATION MATRICE-256 (BOKONO)
|
|
2
|
+
==================================================================
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2026 Cedoque BAGBONON — Projet Matrice-256.
|
|
5
|
+
Tous droits réservés.
|
|
6
|
+
|
|
7
|
+
L'intégralité du code source (bokono), des fichiers de données associés, des configurations, et des formulations mathématiques (incluant FaNet, la perte FaImbalanceLoss, l'embedding combinatoire TorchFaEmbedding, et les fonctions d'activation associées) est la propriété intellectuelle exclusive de Cedoque BAGBONON.
|
|
8
|
+
|
|
9
|
+
Cette licence définit les termes d'utilisation, de lecture et d'évaluation du logiciel.
|
|
10
|
+
|
|
11
|
+
1. CONCESSION DE LICENCE D'ÉVALUATION ET DE RECHERCHE
|
|
12
|
+
-----------------------------------------------------
|
|
13
|
+
Par la présente, l'auteur concède à tout utilisateur le droit non exclusif, non transférable et gratuit de :
|
|
14
|
+
* Cloner, lire et inspecter le code source à des fins d'évaluation académique, d'audit de sécurité, et de vérification scientifique par les pairs (peer-review).
|
|
15
|
+
* Exécuter le code localement à des fins exclusives de recherche scientifique non commerciale et d'expérimentation personnelle.
|
|
16
|
+
|
|
17
|
+
2. USAGES STRICTEMENT INTERDITS (SANS ACCORD ÉCRIT PRÉALABLE)
|
|
18
|
+
-------------------------------------------------------------
|
|
19
|
+
Il est strictement interdit de :
|
|
20
|
+
* Utiliser ce logiciel, en tout ou en partie, à des fins commerciales, industrielles ou lucratives.
|
|
21
|
+
* Modifier, adapter, altérer ou créer des œuvres dérivées basées sur le code source de cette bibliothèque.
|
|
22
|
+
* Redistribuer, republier, sous-licencier ou vendre le code source ou ses dérivés à des tiers sous forme de package, d'API web ou par tout autre canal de distribution.
|
|
23
|
+
* Déposer des demandes de brevets, de droits d'auteur ou de titres de propriété intellectuelle reposant sur l'architecture mathématique et combinatoire divulguée dans ce dépôt.
|
|
24
|
+
* Révéler, publier ou exposer des parties de la base de données Fâ privée (secret industriel) non incluses dans la version publique.
|
|
25
|
+
|
|
26
|
+
3. DISCLAMER (LIMITATION DE GARANTIE ET DE RESPONSABILITÉ)
|
|
27
|
+
----------------------------------------------------------
|
|
28
|
+
CE LOGICIEL EST FOURNI « EN L'ÉTAT » (AS IS), SANS GARANTIE D'AUCUNE SORTE, EXPRESSE OU IMPLICITE, Y COMPRIS MAIS SANS S'Y LIMITER, LES GARANTIES DE QUALITÉ MARCHANDE, D'ADÉQUATION À UN USAGE PARTICULIER ET DE NON-CONTREFAÇON.
|
|
29
|
+
EN AUCUN CAS L'AUTEUR NE POURRA ÊTRE TENU RESPONSABLE DE TOUTE RÉCLAMATION, DOMMAGE OU AUTRE RESPONSABILITÉ, QUE CE SOIT DANS LE CADRE D'UN CONTRAT, D'UN DÉLIT OU AUTREMENT, DÉCOULANT DE, LIÉ À OU EN RELATION AVEC LE LOGICIEL OU SON UTILISATION.
|
|
30
|
+
|
|
31
|
+
4. DEMANDES D'AUTORISATIONS ET CONTACT
|
|
32
|
+
--------------------------------------
|
|
33
|
+
Pour toute demande de licence commerciale, de collaboration industrielle, d'autorisation de modification ou de partenariat académique étendu, veuillez contacter directement l'auteur à l'adresse email suivante :
|
|
34
|
+
* **Email :** projet.matrice256@protonmail.com
|
bokono-4.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bokono
|
|
3
|
+
Version: 4.0.0
|
|
4
|
+
Summary: Bibliothèque algorithmique et ML fondée sur la logique binaire du Fâ — Bénin
|
|
5
|
+
Author-email: Cedoque BAGBONON - Projet Matrice-256 <projet.matrice256@protonmail.com>
|
|
6
|
+
License: Proprietary Software
|
|
7
|
+
Keywords: fa,benin,machine-learning,divination,bokono,african-ai,proprietary
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: torch>=2.0.0
|
|
20
|
+
Requires-Dist: numpy>=1.24.0
|
|
21
|
+
Requires-Dist: pandas>=2.0.0
|
|
22
|
+
Requires-Dist: scikit-learn>=1.2.2
|
|
23
|
+
Requires-Dist: dash>=2.15.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# MATRICE-256 (FaNet v4.0)
|
|
29
|
+
**Réseau Neuro-Symbolique d'Architecture Fâ**
|
|
30
|
+
|
|
31
|
+
[](https://www.python.org/downloads/)
|
|
32
|
+
[](https://pytorch.org/)
|
|
33
|
+
[](#)
|
|
34
|
+
|
|
35
|
+
*Ce projet est soumis au Concours de cas d'application créative en IA pour les jeunes africains (2026).*
|
|
36
|
+
|
|
37
|
+
**Matrice-256 (FaNet)** est le premier framework d'Intelligence Artificielle Neuro-Symbolique au monde intégrant un biais inductif culturel africain directement dans sa fonction de perte neuronale. Fondé sur la combinatoire du Fâ (géomancie béninoise), FaNet projette les données dans un espace de 256 attracteurs sémantiques, produisant des diagnostics explicables, robustes au bruit et conformes par design aux normes de protection de la vie privée (RGPD/HIPAA).
|
|
38
|
+
|
|
39
|
+
📖 **[Consulter le Livre Blanc Scientifique (Whitepaper)](docs/whitepaper_matrice256.md)**
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 🏆 Validation Scientifique (8 Tests Exigeants)
|
|
44
|
+
|
|
45
|
+
FaNet v4.0 a été validé sur 8 bancs d'essai scientifiques, surpassant les modèles de référence (Random Forest, Gradient Boosting) sur les critères de souveraineté et d'explicabilité :
|
|
46
|
+
|
|
47
|
+
| Test | Résultat Clé | Statut |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| **T1 — Robustesse au Bruit** | Surpasse Random Forest à 50% de bruit (96.1% vs 95.7%) | ✅ |
|
|
50
|
+
| **T2 — Cross-Validation K=10** | Accuracy 97.50%, Rappel 100% | ✅ |
|
|
51
|
+
| **T3 — OOD Généralisation** | Rappel 100% inter-domaine (RF : 92%) | ✅ |
|
|
52
|
+
| **T4 — Calibration Clinique** | ECE 14.71% — meilleur du benchmark | ✅ |
|
|
53
|
+
| **T5 — Régression Fintech** | MAE 143 FCFA — viable Agri-Fintech | ✅ |
|
|
54
|
+
| **T6 — IoT Temporel LSTM** | F1 54%, Rappel 97.4% — architecture temporelle validée | ✅ |
|
|
55
|
+
| **T7 — MIA / Vie Privée** | AUC 0.5261 — Conforme RGPD Art. 25 & HIPAA (RF non-conforme) | ✅ |
|
|
56
|
+
| **T8 — Energy Score CO₂** | **-67.8% d'énergie d'inférence vs RF (40 nWh/inférence)** | ✅ |
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## 🧠 L'Architecture Neuro-Symbolique
|
|
61
|
+
|
|
62
|
+
FaNet v4.0 est une architecture mathématique hybride :
|
|
63
|
+
1. **TorchFaEmbedding** : Encodeur combinatoire qui projette les données dans l'espace des 16 Clés Fondamentales via attention croisée.
|
|
64
|
+
2. **FaImbalanceLoss** : Perte informée par l'ontologie pénalisant le réseau s'il viole l'équilibre Yin/Yang des Kpolis.
|
|
65
|
+
3. **Module Temporel (LSTM)** : Traitement natif des séries temporelles (capteurs IoT).
|
|
66
|
+
4. **Air-Gapped par Design** : Aucune donnée ne sort du processeur local, assurant la souveraineté.
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## 🚀 Démarrage Rapide
|
|
71
|
+
|
|
72
|
+
### 1. Environnement Local
|
|
73
|
+
```bash
|
|
74
|
+
git clone https://github.com/VOTRE_ORGA/Matrice-256.git
|
|
75
|
+
cd Matrice-256
|
|
76
|
+
pip install -r requirements.txt
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### 2. L'API Développeur (Zéro Bullshit)
|
|
80
|
+
```python
|
|
81
|
+
from bokono.ml.torch_network import TorchFaNet
|
|
82
|
+
|
|
83
|
+
# Initialise le réseau (v4.0 supporte la compilation JIT)
|
|
84
|
+
model = TorchFaNet(n_features=8, hidden_dim=32, n_outputs=1)
|
|
85
|
+
|
|
86
|
+
# Entraînement avec pénalité ontologique (lambda_fa)
|
|
87
|
+
model.fit(X_train, y_train, epochs=30, lambda_fa=0.2, compile=True)
|
|
88
|
+
|
|
89
|
+
# Inférence avec explicabilité native
|
|
90
|
+
probability, interpretation = model.predict(X_patient)
|
|
91
|
+
print(interpretation[0]["ontological_state"]) # ex: STATE_003
|
|
92
|
+
print(interpretation[0]["system_polarity"]) # FAUSSE ROUTE / FAVORABLE
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## 📊 Preuves de Concept (PoC)
|
|
98
|
+
|
|
99
|
+
Exécutez les démos interactives pour voir le modèle en action :
|
|
100
|
+
|
|
101
|
+
1. **Diagnostic Médical (Santé) :**
|
|
102
|
+
```bash
|
|
103
|
+
python demo_health_fanet.py
|
|
104
|
+
```
|
|
105
|
+
2. **Analyse de Sols (Agriculture) :**
|
|
106
|
+
```bash
|
|
107
|
+
python demo_agri_fanet.py
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
---
|
|
111
|
+
|
|
112
|
+
## 🔐 Propriété, Licence & Souveraineté
|
|
113
|
+
|
|
114
|
+
* **Conformité Règlementaire** : Le test Membership Inference Attack (Test 7) démontre empiriquement que FaNet ne mémorise pas ses données d'apprentissage (AUC = 0.526, proche du hasard pur), garantissant une conformité native aux normes de protection de la vie privée (RGPD Art. 25 & HIPAA).
|
|
115
|
+
* **Souveraineté Énergétique** : Modèle ultra-léger (~50 000 paramètres), compilable JIT, conçu pour fonctionner en local et hors-ligne (Air-Gapped) sur du matériel modeste (Edge IoT, Raspberry Pi).
|
|
116
|
+
* **Licence Propriétaire de Recherche Académique** : Ce dépôt est publié à des fins de révision scientifique par les pairs (peer-review) et d'évaluation de recherche uniquement. Toute reproduction, modification ou utilisation commerciale est strictement interdite sans un accord écrit préalable du propriétaire.
|
|
117
|
+
* **Contact & Feedback** : Pour signaler des bugs, proposer des améliorations académiques ou pour toute demande d'exploitation commerciale, veuillez écrire à : **projet.matrice256@protonmail.com**.
|
|
118
|
+
|
bokono-4.0.0/README.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# MATRICE-256 (FaNet v4.0)
|
|
2
|
+
**Réseau Neuro-Symbolique d'Architecture Fâ**
|
|
3
|
+
|
|
4
|
+
[](https://www.python.org/downloads/)
|
|
5
|
+
[](https://pytorch.org/)
|
|
6
|
+
[](#)
|
|
7
|
+
|
|
8
|
+
*Ce projet est soumis au Concours de cas d'application créative en IA pour les jeunes africains (2026).*
|
|
9
|
+
|
|
10
|
+
**Matrice-256 (FaNet)** est le premier framework d'Intelligence Artificielle Neuro-Symbolique au monde intégrant un biais inductif culturel africain directement dans sa fonction de perte neuronale. Fondé sur la combinatoire du Fâ (géomancie béninoise), FaNet projette les données dans un espace de 256 attracteurs sémantiques, produisant des diagnostics explicables, robustes au bruit et conformes par design aux normes de protection de la vie privée (RGPD/HIPAA).
|
|
11
|
+
|
|
12
|
+
📖 **[Consulter le Livre Blanc Scientifique (Whitepaper)](docs/whitepaper_matrice256.md)**
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## 🏆 Validation Scientifique (8 Tests Exigeants)
|
|
17
|
+
|
|
18
|
+
FaNet v4.0 a été validé sur 8 bancs d'essai scientifiques, surpassant les modèles de référence (Random Forest, Gradient Boosting) sur les critères de souveraineté et d'explicabilité :
|
|
19
|
+
|
|
20
|
+
| Test | Résultat Clé | Statut |
|
|
21
|
+
|---|---|---|
|
|
22
|
+
| **T1 — Robustesse au Bruit** | Surpasse Random Forest à 50% de bruit (96.1% vs 95.7%) | ✅ |
|
|
23
|
+
| **T2 — Cross-Validation K=10** | Accuracy 97.50%, Rappel 100% | ✅ |
|
|
24
|
+
| **T3 — OOD Généralisation** | Rappel 100% inter-domaine (RF : 92%) | ✅ |
|
|
25
|
+
| **T4 — Calibration Clinique** | ECE 14.71% — meilleur du benchmark | ✅ |
|
|
26
|
+
| **T5 — Régression Fintech** | MAE 143 FCFA — viable Agri-Fintech | ✅ |
|
|
27
|
+
| **T6 — IoT Temporel LSTM** | F1 54%, Rappel 97.4% — architecture temporelle validée | ✅ |
|
|
28
|
+
| **T7 — MIA / Vie Privée** | AUC 0.5261 — Conforme RGPD Art. 25 & HIPAA (RF non-conforme) | ✅ |
|
|
29
|
+
| **T8 — Energy Score CO₂** | **-67.8% d'énergie d'inférence vs RF (40 nWh/inférence)** | ✅ |
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## 🧠 L'Architecture Neuro-Symbolique
|
|
34
|
+
|
|
35
|
+
FaNet v4.0 est une architecture mathématique hybride :
|
|
36
|
+
1. **TorchFaEmbedding** : Encodeur combinatoire qui projette les données dans l'espace des 16 Clés Fondamentales via attention croisée.
|
|
37
|
+
2. **FaImbalanceLoss** : Perte informée par l'ontologie pénalisant le réseau s'il viole l'équilibre Yin/Yang des Kpolis.
|
|
38
|
+
3. **Module Temporel (LSTM)** : Traitement natif des séries temporelles (capteurs IoT).
|
|
39
|
+
4. **Air-Gapped par Design** : Aucune donnée ne sort du processeur local, assurant la souveraineté.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 🚀 Démarrage Rapide
|
|
44
|
+
|
|
45
|
+
### 1. Environnement Local
|
|
46
|
+
```bash
|
|
47
|
+
git clone https://github.com/VOTRE_ORGA/Matrice-256.git
|
|
48
|
+
cd Matrice-256
|
|
49
|
+
pip install -r requirements.txt
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### 2. L'API Développeur (Zéro Bullshit)
|
|
53
|
+
```python
|
|
54
|
+
from bokono.ml.torch_network import TorchFaNet
|
|
55
|
+
|
|
56
|
+
# Initialise le réseau (v4.0 supporte la compilation JIT)
|
|
57
|
+
model = TorchFaNet(n_features=8, hidden_dim=32, n_outputs=1)
|
|
58
|
+
|
|
59
|
+
# Entraînement avec pénalité ontologique (lambda_fa)
|
|
60
|
+
model.fit(X_train, y_train, epochs=30, lambda_fa=0.2, compile=True)
|
|
61
|
+
|
|
62
|
+
# Inférence avec explicabilité native
|
|
63
|
+
probability, interpretation = model.predict(X_patient)
|
|
64
|
+
print(interpretation[0]["ontological_state"]) # ex: STATE_003
|
|
65
|
+
print(interpretation[0]["system_polarity"]) # FAUSSE ROUTE / FAVORABLE
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## 📊 Preuves de Concept (PoC)
|
|
71
|
+
|
|
72
|
+
Exécutez les démos interactives pour voir le modèle en action :
|
|
73
|
+
|
|
74
|
+
1. **Diagnostic Médical (Santé) :**
|
|
75
|
+
```bash
|
|
76
|
+
python demo_health_fanet.py
|
|
77
|
+
```
|
|
78
|
+
2. **Analyse de Sols (Agriculture) :**
|
|
79
|
+
```bash
|
|
80
|
+
python demo_agri_fanet.py
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 🔐 Propriété, Licence & Souveraineté
|
|
86
|
+
|
|
87
|
+
* **Conformité Règlementaire** : Le test Membership Inference Attack (Test 7) démontre empiriquement que FaNet ne mémorise pas ses données d'apprentissage (AUC = 0.526, proche du hasard pur), garantissant une conformité native aux normes de protection de la vie privée (RGPD Art. 25 & HIPAA).
|
|
88
|
+
* **Souveraineté Énergétique** : Modèle ultra-léger (~50 000 paramètres), compilable JIT, conçu pour fonctionner en local et hors-ligne (Air-Gapped) sur du matériel modeste (Edge IoT, Raspberry Pi).
|
|
89
|
+
* **Licence Propriétaire de Recherche Académique** : Ce dépôt est publié à des fins de révision scientifique par les pairs (peer-review) et d'évaluation de recherche uniquement. Toute reproduction, modification ou utilisation commerciale est strictement interdite sans un accord écrit préalable du propriétaire.
|
|
90
|
+
* **Contact & Feedback** : Pour signaler des bugs, proposer des améliorations académiques ou pour toute demande d'exploitation commerciale, veuillez écrire à : **projet.matrice256@protonmail.com**.
|
|
91
|
+
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cedoque BAGBONON — Projet Matrice-256.
|
|
2
|
+
# Tous droits réservés. Reproduction ou distribution interdite sans autorisation.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
bokono — Bibliothèque algorithmique fondée sur la logique binaire du Fâ
|
|
6
|
+
Projet Matrice-256 | Bénin, 2026
|
|
7
|
+
|
|
8
|
+
Le nom "bokono" désigne le praticien du Fâ en langue Fon.
|
|
9
|
+
Cette bibliothèque est le Bokonon numérique du Bénin.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
__version__ = "4.0.0"
|
|
13
|
+
__author__ = "Projet Matrice-256"
|
|
14
|
+
__license__ = "Proprietary Software (c) 2026 Cedoque BAGBONON - Matrice-256"
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cedoque BAGBONON — Projet Matrice-256.
|
|
2
|
+
# Tous droits réservés. Reproduction ou distribution interdite sans autorisation.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
bokono.core.fa_encoder — Encodeur Fâ ↔ Binaire
|
|
6
|
+
================================================
|
|
7
|
+
Traducteur universel entre la logique du Fâ et la logique binaire moderne.
|
|
8
|
+
|
|
9
|
+
Le Fâ utilise un système de marques :
|
|
10
|
+
- Marque simple (impaire / ouvert) → 1 (actif)
|
|
11
|
+
- Marque double (paire / fermé) → 0 (passif)
|
|
12
|
+
|
|
13
|
+
Les 16 Kpoli s'encodent sur 4 bits (2⁴ = 16).
|
|
14
|
+
Les 256 du s'encodent sur 8 bits (2⁸ = 256) = 1 octet.
|
|
15
|
+
|
|
16
|
+
Auteur : Projet Matrice-256 / bokono
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
from typing import Optional, Union
|
|
23
|
+
try:
|
|
24
|
+
from typing import TypedDict
|
|
25
|
+
except ImportError: # Python < 3.8 fallback (non applicable ici)
|
|
26
|
+
from typing_extensions import TypedDict # type: ignore[no-redef]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class KpoliEntry(TypedDict):
|
|
30
|
+
"""Structure d'une entrée du référentiel des 16 Kpoli."""
|
|
31
|
+
index: int
|
|
32
|
+
nom: str
|
|
33
|
+
code: str
|
|
34
|
+
alias: list[str]
|
|
35
|
+
|
|
36
|
+
# ─── Référentiel des 16 Kpoli (ordre canonique Fon) ──────────────────────────
|
|
37
|
+
KPOLI_16 = [
|
|
38
|
+
{"index": 0, "nom": "GBE", "code": "0000", "alias": ["GBÉ", "GBHE"]},
|
|
39
|
+
{"index": 1, "nom": "YEKU", "code": "0001", "alias": ["YEKOU", "YÉKU"]},
|
|
40
|
+
{"index": 2, "nom": "WOLI", "code": "0010", "alias": ["WOLI"]},
|
|
41
|
+
{"index": 3, "nom": "DI", "code": "0011", "alias": ["ODI"]},
|
|
42
|
+
{"index": 4, "nom": "ABLA", "code": "0100", "alias": ["ABLAMEDJI"]},
|
|
43
|
+
{"index": 5, "nom": "AKLAN", "code": "0101", "alias": ["AKLAN"]},
|
|
44
|
+
{"index": 6, "nom": "TRINMI", "code": "0110", "alias": ["TRINMI"]},
|
|
45
|
+
{"index": 7, "nom": "GUDA", "code": "0111", "alias": ["GUDA"]},
|
|
46
|
+
{"index": 8, "nom": "SA", "code": "1000", "alias": ["SA"]},
|
|
47
|
+
{"index": 9, "nom": "KA", "code": "1001", "alias": ["KA"]},
|
|
48
|
+
{"index": 10, "nom": "TULA", "code": "1010", "alias": ["TULA"]},
|
|
49
|
+
{"index": 11, "nom": "TURUKPE", "code": "1011", "alias": ["TURUKPE"]},
|
|
50
|
+
{"index": 12, "nom": "KANA", "code": "1100", "alias": ["KANA"]},
|
|
51
|
+
{"index": 13, "nom": "OTURA", "code": "1101", "alias": ["IRETE"]},
|
|
52
|
+
{"index": 14, "nom": "OKANRAN", "code": "1110", "alias": ["OSE"]},
|
|
53
|
+
{"index": 15, "nom": "IKA", "code": "1111", "alias": ["OFUN"]},
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
# Index de recherche rapide
|
|
57
|
+
_KPOLI_BY_NAME: dict[str, int] = {}
|
|
58
|
+
_k: KpoliEntry
|
|
59
|
+
for _k in KPOLI_16: # type: ignore[assignment]
|
|
60
|
+
_KPOLI_BY_NAME[_k["nom"].upper()] = _k["index"]
|
|
61
|
+
for _alias in _k["alias"]:
|
|
62
|
+
_KPOLI_BY_NAME[_alias.upper()] = _k["index"]
|
|
63
|
+
|
|
64
|
+
# Chemins de la base de connaissance (Fallback de sécurité)
|
|
65
|
+
_KB_PRIVATE_PATH = os.path.join(
|
|
66
|
+
os.path.dirname(__file__), "..", "..", "data", "knowledge_base", "fa_knowledge_private.json"
|
|
67
|
+
)
|
|
68
|
+
_KB_PUBLIC_PATH = os.path.join(
|
|
69
|
+
os.path.dirname(__file__), "..", "..", "data", "knowledge_base", "fa_knowledge_public.json"
|
|
70
|
+
)
|
|
71
|
+
_KB_PACKAGE_PATH = os.path.join(
|
|
72
|
+
os.path.dirname(__file__), "fa_knowledge_public.json"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _load_knowledge_base() -> list[dict]:
|
|
77
|
+
"""Charge la base de connaissance Fâ (lazy loading avec Fallback privé/public/package)."""
|
|
78
|
+
path_priv = os.path.normpath(_KB_PRIVATE_PATH)
|
|
79
|
+
path_pub = os.path.normpath(_KB_PUBLIC_PATH)
|
|
80
|
+
path_pkg = os.path.normpath(_KB_PACKAGE_PATH)
|
|
81
|
+
|
|
82
|
+
# 1. Tente de charger la vraie intelligence (Usage Propriétaire Local)
|
|
83
|
+
if os.path.exists(path_priv):
|
|
84
|
+
try:
|
|
85
|
+
with open(path_priv, encoding="utf-8") as f:
|
|
86
|
+
return json.load(f)
|
|
87
|
+
except json.JSONDecodeError as e:
|
|
88
|
+
raise ValueError(f"Fichier de base de connaissance corrompu (Private) : {e}")
|
|
89
|
+
|
|
90
|
+
# 2. Fallback de sécurité (Usage GitHub / Tiers)
|
|
91
|
+
if os.path.exists(path_pub):
|
|
92
|
+
try:
|
|
93
|
+
with open(path_pub, encoding="utf-8") as f:
|
|
94
|
+
return json.load(f)
|
|
95
|
+
except json.JSONDecodeError as e:
|
|
96
|
+
raise ValueError(f"Fichier de base de connaissance corrompu (Public) : {e}")
|
|
97
|
+
|
|
98
|
+
# 3. Fallback de sécurité package (Usage après pip install)
|
|
99
|
+
if os.path.exists(path_pkg):
|
|
100
|
+
try:
|
|
101
|
+
with open(path_pkg, encoding="utf-8") as f:
|
|
102
|
+
return json.load(f)
|
|
103
|
+
except json.JSONDecodeError as e:
|
|
104
|
+
raise ValueError(f"Fichier de base de connaissance corrompu (Package) : {e}")
|
|
105
|
+
|
|
106
|
+
raise FileNotFoundError(
|
|
107
|
+
f"Base de connaissance introuvable dans data/knowledge_base/ ou dans le package bokono/core/\n"
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
_KB: Optional[list[dict]] = None # Cache en mémoire
|
|
111
|
+
_KB_HASH: Optional[str] = None
|
|
112
|
+
|
|
113
|
+
def _get_kb() -> list[dict]:
|
|
114
|
+
global _KB, _KB_HASH
|
|
115
|
+
if _KB is None:
|
|
116
|
+
import hashlib
|
|
117
|
+
_KB = _load_knowledge_base()
|
|
118
|
+
_KB_HASH = hashlib.sha256(json.dumps(_KB, sort_keys=True).encode("utf-8")).hexdigest()
|
|
119
|
+
return _KB
|
|
120
|
+
|
|
121
|
+
def get_kb_hash() -> str:
|
|
122
|
+
"""Retourne l'empreinte SHA-256 de la base de connaissance active."""
|
|
123
|
+
if _KB_HASH is None:
|
|
124
|
+
_get_kb()
|
|
125
|
+
assert _KB_HASH is not None
|
|
126
|
+
return _KB_HASH
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# ─── Fonctions principales ────────────────────────────────────────────────────
|
|
130
|
+
|
|
131
|
+
def kpoli_index(nom: str) -> int:
|
|
132
|
+
"""
|
|
133
|
+
Retourne l'index (0-15) d'un Kpoli par son nom.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
nom: Nom du Kpoli (ex: "GBE", "YEKU", "AKLAN")
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
Index 0-15
|
|
140
|
+
|
|
141
|
+
Raises:
|
|
142
|
+
ValueError si le nom est inconnu.
|
|
143
|
+
|
|
144
|
+
Exemple:
|
|
145
|
+
>>> kpoli_index("GBE")
|
|
146
|
+
0
|
|
147
|
+
>>> kpoli_index("YEKU")
|
|
148
|
+
1
|
|
149
|
+
"""
|
|
150
|
+
key = nom.strip().upper()
|
|
151
|
+
if key in _KPOLI_BY_NAME:
|
|
152
|
+
return _KPOLI_BY_NAME[key]
|
|
153
|
+
raise ValueError(
|
|
154
|
+
f"Kpoli inconnu : '{nom}'. "
|
|
155
|
+
f"Valeurs valides : {[k['nom'] for k in KPOLI_16]}"
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def kpoli_name(index: int) -> str:
|
|
160
|
+
"""
|
|
161
|
+
Retourne le nom Fon d'un Kpoli par son index.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
index: Entier 0-15
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
Nom du Kpoli (ex: "GBE")
|
|
168
|
+
|
|
169
|
+
Exemple:
|
|
170
|
+
>>> kpoli_name(0)
|
|
171
|
+
'GBE'
|
|
172
|
+
"""
|
|
173
|
+
if not 0 <= index <= 15:
|
|
174
|
+
raise ValueError(f"Index Kpoli invalide : {index}. Attendu : 0-15.")
|
|
175
|
+
return str(KPOLI_16[index]["nom"]) # cast explicite : TypedDict garantit str
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def encode_du(left: Union[str, int], right: Union[str, int]) -> str:
|
|
179
|
+
"""
|
|
180
|
+
Encode deux Kpoli en un code binaire 8 bits représentant un du.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
left: Kpoli de gauche (nom ou index 0-15)
|
|
184
|
+
right: Kpoli de droite (nom ou index 0-15)
|
|
185
|
+
|
|
186
|
+
Returns:
|
|
187
|
+
Code binaire 8 bits (ex: "00000000")
|
|
188
|
+
|
|
189
|
+
Exemples:
|
|
190
|
+
>>> encode_du("GBE", "GBE")
|
|
191
|
+
'00000000'
|
|
192
|
+
>>> encode_du("GBE", "YEKU")
|
|
193
|
+
'00000001'
|
|
194
|
+
>>> encode_du(1, 0)
|
|
195
|
+
'00010000'
|
|
196
|
+
"""
|
|
197
|
+
li = left if isinstance(left, int) else kpoli_index(left)
|
|
198
|
+
ri = right if isinstance(right, int) else kpoli_index(right)
|
|
199
|
+
if not (0 <= li <= 15 and 0 <= ri <= 15):
|
|
200
|
+
raise ValueError(f"Index hors limites : left={li}, right={ri}")
|
|
201
|
+
return f"{li:04b}{ri:04b}"
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def decode_du(code: Union[str, int]) -> dict:
|
|
205
|
+
"""
|
|
206
|
+
Décode un code binaire (ou entier 0-255) en entrée de la base de connaissance.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
code: Code binaire 8 bits (ex: "00000001") ou entier 0-255
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
Dictionnaire complet du du (depuis fa_knowledge.json)
|
|
213
|
+
|
|
214
|
+
Exemples:
|
|
215
|
+
>>> decode_du("00000000")["nom_fon"]
|
|
216
|
+
'GBE MEDJI'
|
|
217
|
+
>>> decode_du(1)["numero"]
|
|
218
|
+
2
|
|
219
|
+
"""
|
|
220
|
+
if isinstance(code, int):
|
|
221
|
+
idx = code
|
|
222
|
+
else:
|
|
223
|
+
idx = int(code, 2)
|
|
224
|
+
|
|
225
|
+
if not 0 <= idx <= 255:
|
|
226
|
+
raise ValueError(f"Code hors limites : {code}. Attendu : 0-255.")
|
|
227
|
+
|
|
228
|
+
kb = _get_kb()
|
|
229
|
+
return kb[idx]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def du_from_kpoli(left: Union[str, int], right: Union[str, int]) -> dict:
|
|
233
|
+
"""
|
|
234
|
+
Retourne le du complet à partir de deux Kpoli.
|
|
235
|
+
|
|
236
|
+
C'est la fonction principale du système : simule le résultat d'un tirage Fâ.
|
|
237
|
+
|
|
238
|
+
Args:
|
|
239
|
+
left: Kpoli de gauche
|
|
240
|
+
right: Kpoli de droite
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
Dictionnaire complet du du
|
|
244
|
+
|
|
245
|
+
Exemple:
|
|
246
|
+
>>> d = du_from_kpoli("GBE", "YEKU")
|
|
247
|
+
>>> print(d["nom_fon"], d["polarite"])
|
|
248
|
+
"""
|
|
249
|
+
code = encode_du(left, right)
|
|
250
|
+
return decode_du(code)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def value_to_du(value: float, domain: float = 1.0) -> dict:
|
|
254
|
+
"""
|
|
255
|
+
Convertit une valeur numérique (float) en du correspondant.
|
|
256
|
+
|
|
257
|
+
Utilisé par le moteur ML pour "lire" une sortie de réseau de neurones
|
|
258
|
+
à travers la grille de lecture du Fâ.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
value: Valeur numérique (typiquement entre 0.0 et domain)
|
|
262
|
+
domain: Valeur maximale (défaut: 1.0)
|
|
263
|
+
|
|
264
|
+
Returns:
|
|
265
|
+
Dictionnaire du du le plus proche
|
|
266
|
+
|
|
267
|
+
Exemple:
|
|
268
|
+
>>> d = value_to_du(0.5)
|
|
269
|
+
>>> print(d["id"], d["nom_canonique"])
|
|
270
|
+
"""
|
|
271
|
+
normalized = max(0.0, min(1.0, value / domain))
|
|
272
|
+
idx = int(normalized * 255)
|
|
273
|
+
return decode_du(idx)
|
|
274
|
+
|
|
275
|
+
def value_to_algorithmic_state(value: float, domain: float = 1.0) -> dict:
|
|
276
|
+
"""
|
|
277
|
+
Interface ML Externe.
|
|
278
|
+
Convertit la valeur en un état mathématique pur (Ontologie Sécurisée).
|
|
279
|
+
Supprime tous les vocabulaires culturels (Mèdji, Gbé) pour l'API.
|
|
280
|
+
"""
|
|
281
|
+
raw_du = value_to_du(value, domain)
|
|
282
|
+
# Traduction en ontologie algorithmique universelle
|
|
283
|
+
# On garantit l'anonymisation culturelle
|
|
284
|
+
polarite_str = str(raw_du.get("polarite", "neutre")).upper()
|
|
285
|
+
return {
|
|
286
|
+
"state_id": int(raw_du.get("numero", 0)),
|
|
287
|
+
"binary_matrix": f"{raw_du.get('code_binaire', '00000000')[:4]} x {raw_du.get('code_binaire', '00000000')[4:]}",
|
|
288
|
+
"ontological_state": f"STATE_{raw_du.get('numero', 0):03d}",
|
|
289
|
+
"system_polarity": polarite_str,
|
|
290
|
+
"is_primary_node": bool(raw_du.get("est_meji", False))
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def get_all_meji() -> list[dict]:
|
|
295
|
+
"""Retourne les 16 signes Meji (doubles — les plus puissants du Fâ)."""
|
|
296
|
+
kb = _get_kb()
|
|
297
|
+
return [d for d in kb if d.get("est_meji", False)]
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def binary_to_marks(code: str) -> str:
|
|
301
|
+
"""
|
|
302
|
+
Convertit un code binaire en représentation visuelle Fâ.
|
|
303
|
+
1 → "|" (marque simple, ouvert)
|
|
304
|
+
0 → "||" (marque double, fermé)
|
|
305
|
+
|
|
306
|
+
Exemple:
|
|
307
|
+
>>> binary_to_marks("00000001")
|
|
308
|
+
'|| || || || || || || |'
|
|
309
|
+
"""
|
|
310
|
+
return " ".join("|" if b == "1" else "||" for b in code)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def marks_to_binary(marks: str) -> str:
|
|
314
|
+
"""
|
|
315
|
+
Convertit une représentation visuelle Fâ en code binaire.
|
|
316
|
+
"|" → 1
|
|
317
|
+
"||" → 0
|
|
318
|
+
|
|
319
|
+
Exemple:
|
|
320
|
+
>>> marks_to_binary("|| || || || || || || |")
|
|
321
|
+
'00000001'
|
|
322
|
+
"""
|
|
323
|
+
parts = marks.strip().split()
|
|
324
|
+
result = ""
|
|
325
|
+
i = 0
|
|
326
|
+
while i < len(parts):
|
|
327
|
+
if i + 1 < len(parts) and parts[i] == "|" and parts[i+1] == "|":
|
|
328
|
+
result += "0"
|
|
329
|
+
i += 2
|
|
330
|
+
elif parts[i] == "||":
|
|
331
|
+
result += "0"
|
|
332
|
+
i += 1
|
|
333
|
+
else:
|
|
334
|
+
result += "1"
|
|
335
|
+
i += 1
|
|
336
|
+
return result
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
# ─── Affichage ────────────────────────────────────────────────────────────────
|
|
340
|
+
|
|
341
|
+
def print_du(du: dict, verbose: bool = False) -> None:
|
|
342
|
+
"""Affiche un du de façon lisible."""
|
|
343
|
+
sep = "─" * 60
|
|
344
|
+
print(sep)
|
|
345
|
+
print(f" DU #{du['numero']:3d} | {du['nom_fon']}")
|
|
346
|
+
print(f" Binaire : {du['code_binaire']} → {binary_to_marks(du['code_binaire'])}")
|
|
347
|
+
print(f" Kpoli : {du['kpoli_gauche']} × {du['kpoli_droit']}")
|
|
348
|
+
print(f" Polarité : {du['polarite']}")
|
|
349
|
+
if verbose:
|
|
350
|
+
print(f" Interp : {du['interpretation'][:200]}")
|
|
351
|
+
if du["interdictions"]:
|
|
352
|
+
print(f" Interdit : {'; '.join(du['interdictions'][:3])}")
|
|
353
|
+
if du["prescriptions"]:
|
|
354
|
+
print(f" À faire : {'; '.join(du['prescriptions'][:3])}")
|
|
355
|
+
print(sep)
|