tnfr 4.5.2__py3-none-any.whl → 8.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of tnfr might be problematic. Click here for more details.

Files changed (365) hide show
  1. tnfr/__init__.py +334 -50
  2. tnfr/__init__.pyi +33 -0
  3. tnfr/_compat.py +10 -0
  4. tnfr/_generated_version.py +34 -0
  5. tnfr/_version.py +49 -0
  6. tnfr/_version.pyi +7 -0
  7. tnfr/alias.py +214 -37
  8. tnfr/alias.pyi +108 -0
  9. tnfr/backends/__init__.py +354 -0
  10. tnfr/backends/jax_backend.py +173 -0
  11. tnfr/backends/numpy_backend.py +238 -0
  12. tnfr/backends/optimized_numpy.py +420 -0
  13. tnfr/backends/torch_backend.py +408 -0
  14. tnfr/cache.py +149 -556
  15. tnfr/cache.pyi +13 -0
  16. tnfr/cli/__init__.py +51 -16
  17. tnfr/cli/__init__.pyi +26 -0
  18. tnfr/cli/arguments.py +344 -32
  19. tnfr/cli/arguments.pyi +29 -0
  20. tnfr/cli/execution.py +676 -50
  21. tnfr/cli/execution.pyi +70 -0
  22. tnfr/cli/interactive_validator.py +614 -0
  23. tnfr/cli/utils.py +18 -3
  24. tnfr/cli/utils.pyi +7 -0
  25. tnfr/cli/validate.py +236 -0
  26. tnfr/compat/__init__.py +85 -0
  27. tnfr/compat/dataclass.py +136 -0
  28. tnfr/compat/jsonschema_stub.py +61 -0
  29. tnfr/compat/matplotlib_stub.py +73 -0
  30. tnfr/compat/numpy_stub.py +155 -0
  31. tnfr/config/__init__.py +224 -0
  32. tnfr/config/__init__.pyi +10 -0
  33. tnfr/{constants_glyphs.py → config/constants.py} +26 -20
  34. tnfr/config/constants.pyi +12 -0
  35. tnfr/config/defaults.py +54 -0
  36. tnfr/{constants/core.py → config/defaults_core.py} +59 -6
  37. tnfr/config/defaults_init.py +33 -0
  38. tnfr/config/defaults_metric.py +104 -0
  39. tnfr/config/feature_flags.py +81 -0
  40. tnfr/config/feature_flags.pyi +16 -0
  41. tnfr/config/glyph_constants.py +31 -0
  42. tnfr/config/init.py +77 -0
  43. tnfr/config/init.pyi +8 -0
  44. tnfr/config/operator_names.py +254 -0
  45. tnfr/config/operator_names.pyi +36 -0
  46. tnfr/config/physics_derivation.py +354 -0
  47. tnfr/config/presets.py +83 -0
  48. tnfr/config/presets.pyi +7 -0
  49. tnfr/config/security.py +927 -0
  50. tnfr/config/thresholds.py +114 -0
  51. tnfr/config/tnfr_config.py +498 -0
  52. tnfr/constants/__init__.py +51 -133
  53. tnfr/constants/__init__.pyi +92 -0
  54. tnfr/constants/aliases.py +33 -0
  55. tnfr/constants/aliases.pyi +27 -0
  56. tnfr/constants/init.py +3 -1
  57. tnfr/constants/init.pyi +12 -0
  58. tnfr/constants/metric.py +9 -15
  59. tnfr/constants/metric.pyi +19 -0
  60. tnfr/core/__init__.py +33 -0
  61. tnfr/core/container.py +226 -0
  62. tnfr/core/default_implementations.py +329 -0
  63. tnfr/core/interfaces.py +279 -0
  64. tnfr/dynamics/__init__.py +213 -633
  65. tnfr/dynamics/__init__.pyi +83 -0
  66. tnfr/dynamics/adaptation.py +267 -0
  67. tnfr/dynamics/adaptation.pyi +7 -0
  68. tnfr/dynamics/adaptive_sequences.py +189 -0
  69. tnfr/dynamics/adaptive_sequences.pyi +14 -0
  70. tnfr/dynamics/aliases.py +23 -0
  71. tnfr/dynamics/aliases.pyi +19 -0
  72. tnfr/dynamics/bifurcation.py +232 -0
  73. tnfr/dynamics/canonical.py +229 -0
  74. tnfr/dynamics/canonical.pyi +48 -0
  75. tnfr/dynamics/coordination.py +385 -0
  76. tnfr/dynamics/coordination.pyi +25 -0
  77. tnfr/dynamics/dnfr.py +2699 -398
  78. tnfr/dynamics/dnfr.pyi +26 -0
  79. tnfr/dynamics/dynamic_limits.py +225 -0
  80. tnfr/dynamics/feedback.py +252 -0
  81. tnfr/dynamics/feedback.pyi +24 -0
  82. tnfr/dynamics/fused_dnfr.py +454 -0
  83. tnfr/dynamics/homeostasis.py +157 -0
  84. tnfr/dynamics/homeostasis.pyi +14 -0
  85. tnfr/dynamics/integrators.py +496 -102
  86. tnfr/dynamics/integrators.pyi +36 -0
  87. tnfr/dynamics/learning.py +310 -0
  88. tnfr/dynamics/learning.pyi +33 -0
  89. tnfr/dynamics/metabolism.py +254 -0
  90. tnfr/dynamics/nbody.py +796 -0
  91. tnfr/dynamics/nbody_tnfr.py +783 -0
  92. tnfr/dynamics/propagation.py +326 -0
  93. tnfr/dynamics/runtime.py +908 -0
  94. tnfr/dynamics/runtime.pyi +77 -0
  95. tnfr/dynamics/sampling.py +10 -5
  96. tnfr/dynamics/sampling.pyi +7 -0
  97. tnfr/dynamics/selectors.py +711 -0
  98. tnfr/dynamics/selectors.pyi +85 -0
  99. tnfr/dynamics/structural_clip.py +207 -0
  100. tnfr/errors/__init__.py +37 -0
  101. tnfr/errors/contextual.py +492 -0
  102. tnfr/execution.py +77 -55
  103. tnfr/execution.pyi +45 -0
  104. tnfr/extensions/__init__.py +205 -0
  105. tnfr/extensions/__init__.pyi +18 -0
  106. tnfr/extensions/base.py +173 -0
  107. tnfr/extensions/base.pyi +35 -0
  108. tnfr/extensions/business/__init__.py +71 -0
  109. tnfr/extensions/business/__init__.pyi +11 -0
  110. tnfr/extensions/business/cookbook.py +88 -0
  111. tnfr/extensions/business/cookbook.pyi +8 -0
  112. tnfr/extensions/business/health_analyzers.py +202 -0
  113. tnfr/extensions/business/health_analyzers.pyi +9 -0
  114. tnfr/extensions/business/patterns.py +183 -0
  115. tnfr/extensions/business/patterns.pyi +8 -0
  116. tnfr/extensions/medical/__init__.py +73 -0
  117. tnfr/extensions/medical/__init__.pyi +11 -0
  118. tnfr/extensions/medical/cookbook.py +88 -0
  119. tnfr/extensions/medical/cookbook.pyi +8 -0
  120. tnfr/extensions/medical/health_analyzers.py +181 -0
  121. tnfr/extensions/medical/health_analyzers.pyi +9 -0
  122. tnfr/extensions/medical/patterns.py +163 -0
  123. tnfr/extensions/medical/patterns.pyi +8 -0
  124. tnfr/flatten.py +29 -50
  125. tnfr/flatten.pyi +21 -0
  126. tnfr/gamma.py +66 -53
  127. tnfr/gamma.pyi +36 -0
  128. tnfr/glyph_history.py +144 -57
  129. tnfr/glyph_history.pyi +35 -0
  130. tnfr/glyph_runtime.py +19 -0
  131. tnfr/glyph_runtime.pyi +8 -0
  132. tnfr/immutable.py +70 -30
  133. tnfr/immutable.pyi +36 -0
  134. tnfr/initialization.py +22 -16
  135. tnfr/initialization.pyi +65 -0
  136. tnfr/io.py +5 -241
  137. tnfr/io.pyi +13 -0
  138. tnfr/locking.pyi +7 -0
  139. tnfr/mathematics/__init__.py +79 -0
  140. tnfr/mathematics/backend.py +453 -0
  141. tnfr/mathematics/backend.pyi +99 -0
  142. tnfr/mathematics/dynamics.py +408 -0
  143. tnfr/mathematics/dynamics.pyi +90 -0
  144. tnfr/mathematics/epi.py +391 -0
  145. tnfr/mathematics/epi.pyi +65 -0
  146. tnfr/mathematics/generators.py +242 -0
  147. tnfr/mathematics/generators.pyi +29 -0
  148. tnfr/mathematics/metrics.py +119 -0
  149. tnfr/mathematics/metrics.pyi +16 -0
  150. tnfr/mathematics/operators.py +239 -0
  151. tnfr/mathematics/operators.pyi +59 -0
  152. tnfr/mathematics/operators_factory.py +124 -0
  153. tnfr/mathematics/operators_factory.pyi +11 -0
  154. tnfr/mathematics/projection.py +87 -0
  155. tnfr/mathematics/projection.pyi +33 -0
  156. tnfr/mathematics/runtime.py +182 -0
  157. tnfr/mathematics/runtime.pyi +64 -0
  158. tnfr/mathematics/spaces.py +256 -0
  159. tnfr/mathematics/spaces.pyi +83 -0
  160. tnfr/mathematics/transforms.py +305 -0
  161. tnfr/mathematics/transforms.pyi +62 -0
  162. tnfr/metrics/__init__.py +47 -9
  163. tnfr/metrics/__init__.pyi +20 -0
  164. tnfr/metrics/buffer_cache.py +163 -0
  165. tnfr/metrics/buffer_cache.pyi +24 -0
  166. tnfr/metrics/cache_utils.py +214 -0
  167. tnfr/metrics/coherence.py +1510 -330
  168. tnfr/metrics/coherence.pyi +129 -0
  169. tnfr/metrics/common.py +23 -16
  170. tnfr/metrics/common.pyi +35 -0
  171. tnfr/metrics/core.py +251 -36
  172. tnfr/metrics/core.pyi +13 -0
  173. tnfr/metrics/diagnosis.py +709 -110
  174. tnfr/metrics/diagnosis.pyi +86 -0
  175. tnfr/metrics/emergence.py +245 -0
  176. tnfr/metrics/export.py +60 -18
  177. tnfr/metrics/export.pyi +7 -0
  178. tnfr/metrics/glyph_timing.py +233 -43
  179. tnfr/metrics/glyph_timing.pyi +81 -0
  180. tnfr/metrics/learning_metrics.py +280 -0
  181. tnfr/metrics/learning_metrics.pyi +21 -0
  182. tnfr/metrics/phase_coherence.py +351 -0
  183. tnfr/metrics/phase_compatibility.py +349 -0
  184. tnfr/metrics/reporting.py +63 -28
  185. tnfr/metrics/reporting.pyi +25 -0
  186. tnfr/metrics/sense_index.py +1126 -43
  187. tnfr/metrics/sense_index.pyi +9 -0
  188. tnfr/metrics/trig.py +215 -23
  189. tnfr/metrics/trig.pyi +13 -0
  190. tnfr/metrics/trig_cache.py +148 -24
  191. tnfr/metrics/trig_cache.pyi +10 -0
  192. tnfr/multiscale/__init__.py +32 -0
  193. tnfr/multiscale/hierarchical.py +517 -0
  194. tnfr/node.py +646 -140
  195. tnfr/node.pyi +139 -0
  196. tnfr/observers.py +160 -45
  197. tnfr/observers.pyi +31 -0
  198. tnfr/ontosim.py +23 -19
  199. tnfr/ontosim.pyi +28 -0
  200. tnfr/operators/__init__.py +1358 -106
  201. tnfr/operators/__init__.pyi +31 -0
  202. tnfr/operators/algebra.py +277 -0
  203. tnfr/operators/canonical_patterns.py +420 -0
  204. tnfr/operators/cascade.py +267 -0
  205. tnfr/operators/cycle_detection.py +358 -0
  206. tnfr/operators/definitions.py +4108 -0
  207. tnfr/operators/definitions.pyi +78 -0
  208. tnfr/operators/grammar.py +1164 -0
  209. tnfr/operators/grammar.pyi +140 -0
  210. tnfr/operators/hamiltonian.py +710 -0
  211. tnfr/operators/health_analyzer.py +809 -0
  212. tnfr/operators/jitter.py +107 -38
  213. tnfr/operators/jitter.pyi +11 -0
  214. tnfr/operators/lifecycle.py +314 -0
  215. tnfr/operators/metabolism.py +618 -0
  216. tnfr/operators/metrics.py +2138 -0
  217. tnfr/operators/network_analysis/__init__.py +27 -0
  218. tnfr/operators/network_analysis/source_detection.py +186 -0
  219. tnfr/operators/nodal_equation.py +395 -0
  220. tnfr/operators/pattern_detection.py +660 -0
  221. tnfr/operators/patterns.py +669 -0
  222. tnfr/operators/postconditions/__init__.py +38 -0
  223. tnfr/operators/postconditions/mutation.py +236 -0
  224. tnfr/operators/preconditions/__init__.py +1226 -0
  225. tnfr/operators/preconditions/coherence.py +305 -0
  226. tnfr/operators/preconditions/dissonance.py +236 -0
  227. tnfr/operators/preconditions/emission.py +128 -0
  228. tnfr/operators/preconditions/mutation.py +580 -0
  229. tnfr/operators/preconditions/reception.py +125 -0
  230. tnfr/operators/preconditions/resonance.py +364 -0
  231. tnfr/operators/registry.py +74 -0
  232. tnfr/operators/registry.pyi +9 -0
  233. tnfr/operators/remesh.py +1415 -91
  234. tnfr/operators/remesh.pyi +26 -0
  235. tnfr/operators/structural_units.py +268 -0
  236. tnfr/operators/unified_grammar.py +105 -0
  237. tnfr/parallel/__init__.py +54 -0
  238. tnfr/parallel/auto_scaler.py +234 -0
  239. tnfr/parallel/distributed.py +384 -0
  240. tnfr/parallel/engine.py +238 -0
  241. tnfr/parallel/gpu_engine.py +420 -0
  242. tnfr/parallel/monitoring.py +248 -0
  243. tnfr/parallel/partitioner.py +459 -0
  244. tnfr/py.typed +0 -0
  245. tnfr/recipes/__init__.py +22 -0
  246. tnfr/recipes/cookbook.py +743 -0
  247. tnfr/rng.py +75 -151
  248. tnfr/rng.pyi +26 -0
  249. tnfr/schemas/__init__.py +8 -0
  250. tnfr/schemas/grammar.json +94 -0
  251. tnfr/sdk/__init__.py +107 -0
  252. tnfr/sdk/__init__.pyi +19 -0
  253. tnfr/sdk/adaptive_system.py +173 -0
  254. tnfr/sdk/adaptive_system.pyi +21 -0
  255. tnfr/sdk/builders.py +370 -0
  256. tnfr/sdk/builders.pyi +51 -0
  257. tnfr/sdk/fluent.py +1121 -0
  258. tnfr/sdk/fluent.pyi +74 -0
  259. tnfr/sdk/templates.py +342 -0
  260. tnfr/sdk/templates.pyi +41 -0
  261. tnfr/sdk/utils.py +341 -0
  262. tnfr/secure_config.py +46 -0
  263. tnfr/security/__init__.py +70 -0
  264. tnfr/security/database.py +514 -0
  265. tnfr/security/subprocess.py +503 -0
  266. tnfr/security/validation.py +290 -0
  267. tnfr/selector.py +59 -22
  268. tnfr/selector.pyi +19 -0
  269. tnfr/sense.py +92 -67
  270. tnfr/sense.pyi +23 -0
  271. tnfr/services/__init__.py +17 -0
  272. tnfr/services/orchestrator.py +325 -0
  273. tnfr/sparse/__init__.py +39 -0
  274. tnfr/sparse/representations.py +492 -0
  275. tnfr/structural.py +639 -263
  276. tnfr/structural.pyi +83 -0
  277. tnfr/telemetry/__init__.py +35 -0
  278. tnfr/telemetry/cache_metrics.py +226 -0
  279. tnfr/telemetry/cache_metrics.pyi +64 -0
  280. tnfr/telemetry/nu_f.py +422 -0
  281. tnfr/telemetry/nu_f.pyi +108 -0
  282. tnfr/telemetry/verbosity.py +36 -0
  283. tnfr/telemetry/verbosity.pyi +15 -0
  284. tnfr/tokens.py +2 -4
  285. tnfr/tokens.pyi +36 -0
  286. tnfr/tools/__init__.py +20 -0
  287. tnfr/tools/domain_templates.py +478 -0
  288. tnfr/tools/sequence_generator.py +846 -0
  289. tnfr/topology/__init__.py +13 -0
  290. tnfr/topology/asymmetry.py +151 -0
  291. tnfr/trace.py +300 -126
  292. tnfr/trace.pyi +42 -0
  293. tnfr/tutorials/__init__.py +38 -0
  294. tnfr/tutorials/autonomous_evolution.py +285 -0
  295. tnfr/tutorials/interactive.py +1576 -0
  296. tnfr/tutorials/structural_metabolism.py +238 -0
  297. tnfr/types.py +743 -12
  298. tnfr/types.pyi +357 -0
  299. tnfr/units.py +68 -0
  300. tnfr/units.pyi +13 -0
  301. tnfr/utils/__init__.py +282 -0
  302. tnfr/utils/__init__.pyi +215 -0
  303. tnfr/utils/cache.py +4223 -0
  304. tnfr/utils/cache.pyi +470 -0
  305. tnfr/{callback_utils.py → utils/callbacks.py} +26 -39
  306. tnfr/utils/callbacks.pyi +49 -0
  307. tnfr/utils/chunks.py +108 -0
  308. tnfr/utils/chunks.pyi +22 -0
  309. tnfr/utils/data.py +428 -0
  310. tnfr/utils/data.pyi +74 -0
  311. tnfr/utils/graph.py +85 -0
  312. tnfr/utils/graph.pyi +10 -0
  313. tnfr/utils/init.py +821 -0
  314. tnfr/utils/init.pyi +80 -0
  315. tnfr/utils/io.py +559 -0
  316. tnfr/utils/io.pyi +66 -0
  317. tnfr/{helpers → utils}/numeric.py +51 -24
  318. tnfr/utils/numeric.pyi +21 -0
  319. tnfr/validation/__init__.py +257 -0
  320. tnfr/validation/__init__.pyi +85 -0
  321. tnfr/validation/compatibility.py +460 -0
  322. tnfr/validation/compatibility.pyi +6 -0
  323. tnfr/validation/config.py +73 -0
  324. tnfr/validation/graph.py +139 -0
  325. tnfr/validation/graph.pyi +18 -0
  326. tnfr/validation/input_validation.py +755 -0
  327. tnfr/validation/invariants.py +712 -0
  328. tnfr/validation/rules.py +253 -0
  329. tnfr/validation/rules.pyi +44 -0
  330. tnfr/validation/runtime.py +279 -0
  331. tnfr/validation/runtime.pyi +28 -0
  332. tnfr/validation/sequence_validator.py +162 -0
  333. tnfr/validation/soft_filters.py +170 -0
  334. tnfr/validation/soft_filters.pyi +32 -0
  335. tnfr/validation/spectral.py +164 -0
  336. tnfr/validation/spectral.pyi +42 -0
  337. tnfr/validation/validator.py +1266 -0
  338. tnfr/validation/window.py +39 -0
  339. tnfr/validation/window.pyi +1 -0
  340. tnfr/visualization/__init__.py +98 -0
  341. tnfr/visualization/cascade_viz.py +256 -0
  342. tnfr/visualization/hierarchy.py +284 -0
  343. tnfr/visualization/sequence_plotter.py +784 -0
  344. tnfr/viz/__init__.py +60 -0
  345. tnfr/viz/matplotlib.py +278 -0
  346. tnfr/viz/matplotlib.pyi +35 -0
  347. tnfr-8.5.0.dist-info/METADATA +573 -0
  348. tnfr-8.5.0.dist-info/RECORD +353 -0
  349. {tnfr-4.5.2.dist-info → tnfr-8.5.0.dist-info}/entry_points.txt +1 -0
  350. {tnfr-4.5.2.dist-info → tnfr-8.5.0.dist-info}/licenses/LICENSE.md +1 -1
  351. tnfr/collections_utils.py +0 -300
  352. tnfr/config.py +0 -32
  353. tnfr/grammar.py +0 -344
  354. tnfr/graph_utils.py +0 -84
  355. tnfr/helpers/__init__.py +0 -71
  356. tnfr/import_utils.py +0 -228
  357. tnfr/json_utils.py +0 -162
  358. tnfr/logging_utils.py +0 -116
  359. tnfr/presets.py +0 -60
  360. tnfr/validators.py +0 -84
  361. tnfr/value_utils.py +0 -59
  362. tnfr-4.5.2.dist-info/METADATA +0 -379
  363. tnfr-4.5.2.dist-info/RECORD +0 -67
  364. {tnfr-4.5.2.dist-info → tnfr-8.5.0.dist-info}/WHEEL +0 -0
  365. {tnfr-4.5.2.dist-info → tnfr-8.5.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1576 @@
1
+ """Interactive tutorial implementations for TNFR learning.
2
+
3
+ This module contains the actual tutorial functions that guide users
4
+ through TNFR concepts with executable examples and clear explanations.
5
+
6
+ Each tutorial is self-contained and can be run independently:
7
+ - hello_tnfr(): 5-minute introduction
8
+ - biological_example(): Cell communication model
9
+ - social_network_example(): Social dynamics simulation
10
+ - technology_example(): Distributed systems analogy
11
+
12
+ All tutorials maintain TNFR canonical invariants and demonstrate
13
+ the 13 structural operators in action.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Optional
19
+ import time
20
+
21
+ try:
22
+ from ..sdk import TNFRNetwork, TNFRTemplates
23
+
24
+ _HAS_SDK = True
25
+ except ImportError:
26
+ _HAS_SDK = False
27
+
28
+ __all__ = [
29
+ "hello_tnfr",
30
+ "biological_example",
31
+ "social_network_example",
32
+ "technology_example",
33
+ "oz_dissonance_tutorial",
34
+ "run_all_tutorials",
35
+ ]
36
+
37
+
38
+ def _print_section(title: str, width: int = 70) -> None:
39
+ """Print a formatted section header."""
40
+ print(f"\n{'='*width}")
41
+ print(f"{title:^{width}}")
42
+ print(f"{'='*width}\n")
43
+
44
+
45
+ def _print_subsection(title: str, width: int = 70) -> None:
46
+ """Print a formatted subsection header."""
47
+ print(f"\n{'-'*width}")
48
+ print(f"{title}")
49
+ print(f"{'-'*width}\n")
50
+
51
+
52
+ def _explain(text: str, pause: float = 1.5) -> None:
53
+ """Print explanation text with optional pause for readability."""
54
+ print(text)
55
+ if pause > 0:
56
+ time.sleep(pause)
57
+
58
+
59
+ def hello_tnfr(interactive: bool = True, random_seed: int = 42) -> None:
60
+ """5-minute interactive introduction to TNFR.
61
+
62
+ This tutorial introduces core TNFR concepts through a simple,
63
+ hands-on example. You'll learn:
64
+
65
+ - What a node is (Nodo Fractal Resonante - NFR)
66
+ - What EPI means (Primary Information Structure)
67
+ - What structural operators do
68
+ - How to measure coherence C(t) and sense index Si
69
+ - How resonance creates stable networks
70
+
71
+ The tutorial uses the simplified SDK API, so you can start
72
+ using TNFR immediately without deep theoretical knowledge.
73
+
74
+ Parameters
75
+ ----------
76
+ interactive : bool, default=True
77
+ If True, pauses between sections for reading.
78
+ random_seed : int, default=42
79
+ Random seed for reproducibility.
80
+
81
+ Examples
82
+ --------
83
+ >>> from tnfr.tutorials import hello_tnfr
84
+ >>> hello_tnfr() # Run the full tutorial
85
+ >>> hello_tnfr(interactive=False) # Run without pauses
86
+
87
+ Notes
88
+ -----
89
+ This tutorial maintains TNFR canonical invariants:
90
+ - Operator closure (Invariant #4)
91
+ - Phase synchrony (Invariant #5)
92
+ - Structural units (νf in Hz_str)
93
+ """
94
+ if not _HAS_SDK:
95
+ print("Error: SDK not available. Install with: pip install tnfr")
96
+ return
97
+
98
+ pause = 1.5 if interactive else 0
99
+
100
+ _print_section("Hello, TNFR! 👋")
101
+
102
+ _explain(
103
+ "Welcome to TNFR - Resonant Fractal Nature Theory!\n"
104
+ "Let's learn the basics in just 5 minutes with a working example.",
105
+ pause,
106
+ )
107
+
108
+ # Part 1: What is a node?
109
+ _print_subsection("Part 1: What is a Resonant Fractal Node (NFR)?")
110
+
111
+ _explain(
112
+ "In TNFR, everything is made of 'nodes' that resonate with each other.\n"
113
+ "Think of them like musical notes - they have:\n"
114
+ " • A frequency (νf) - how fast they vibrate\n"
115
+ " • A phase (φ) - when they vibrate\n"
116
+ " • A form (EPI) - what they 'look like' structurally\n\n"
117
+ "Let's create a simple network of 10 nodes:",
118
+ pause,
119
+ )
120
+
121
+ print(" >>> from tnfr.sdk import TNFRNetwork")
122
+ print(" >>> network = TNFRNetwork('hello_example')")
123
+ print(" >>> network.add_nodes(10, random_seed=42)\n")
124
+
125
+ network = TNFRNetwork("hello_example")
126
+ network.add_nodes(10, random_seed=random_seed)
127
+
128
+ _explain("✓ Created 10 resonant nodes!", pause * 0.5)
129
+
130
+ # Part 2: Connecting nodes
131
+ _print_subsection("Part 2: Connecting Nodes")
132
+
133
+ _explain(
134
+ "Nodes need to connect to form a network. We'll connect them randomly\n"
135
+ "with 30% probability (like neurons forming synapses):\n",
136
+ pause,
137
+ )
138
+
139
+ print(" >>> network.connect_nodes(0.3, 'random')\n")
140
+ network.connect_nodes(0.3, "random")
141
+
142
+ _explain("✓ Nodes connected! Now they can resonate together.", pause * 0.5)
143
+
144
+ # Part 3: Applying operators
145
+ _print_subsection("Part 3: The 13 Structural Operators")
146
+
147
+ _explain(
148
+ "TNFR has 13 fundamental operators that reorganize networks:\n"
149
+ " 1. Emission - Start sending signals\n"
150
+ " 2. Reception - Receive signals from neighbors\n"
151
+ " 3. Coherence - Stabilize structures\n"
152
+ " 4. Resonance - Amplify synchronized patterns\n"
153
+ " 5. Silence - Pause evolution\n"
154
+ " ...and 8 more!\n\n"
155
+ "Let's apply a basic activation sequence:",
156
+ pause,
157
+ )
158
+
159
+ print(" >>> network.apply_sequence('basic_activation', repeat=3)\n")
160
+ network.apply_sequence("basic_activation", repeat=3)
161
+
162
+ _explain(
163
+ "✓ Applied: emission → reception → coherence → resonance → silence\n"
164
+ " This sequence activated the network 3 times!",
165
+ pause,
166
+ )
167
+
168
+ # Part 4: Measuring results
169
+ _print_subsection("Part 4: Measuring Coherence and Sense Index")
170
+
171
+ _explain(
172
+ "Now let's measure what happened:\n"
173
+ " • C(t) = Coherence - how stable is the network?\n"
174
+ " • Si = Sense Index - how well can each node reorganize?\n",
175
+ pause,
176
+ )
177
+
178
+ print(" >>> results = network.measure()")
179
+ print(" >>> print(results.summary())\n")
180
+
181
+ results = network.measure()
182
+
183
+ # Extract key metrics for display
184
+ coherence = results.coherence
185
+ avg_si = (
186
+ sum(results.sense_indices.values()) / len(results.sense_indices)
187
+ if results.sense_indices
188
+ else 0
189
+ )
190
+
191
+ print(f" Coherence C(t) = {coherence:.3f}")
192
+ print(f" Average Si = {avg_si:.3f}")
193
+ print(f" Nodes = {len(results.sense_indices)}")
194
+
195
+ _explain("", pause)
196
+
197
+ # Part 5: Interpretation
198
+ _print_subsection("Part 5: What Does This Mean?")
199
+
200
+ _explain(
201
+ f"Results interpretation:\n"
202
+ f" • Coherence C(t) = {coherence:.3f}\n"
203
+ f" {'High' if coherence > 0.5 else 'Moderate' if coherence > 0.2 else 'Low'} stability - "
204
+ f"the network holds its structure well!\n\n"
205
+ f" • Average Si = {avg_si:.3f}\n"
206
+ f" Each node can {'effectively' if avg_si > 0.5 else 'moderately'} reorganize "
207
+ f"while staying coherent.\n\n"
208
+ "In TNFR terms: Your network exhibits resonant coherence! 🎵\n"
209
+ "The nodes synchronized their phases and created stable patterns.",
210
+ pause,
211
+ )
212
+
213
+ # Part 6: Try it yourself
214
+ _print_subsection("Part 6: Try It Yourself!")
215
+
216
+ _explain(
217
+ "That's the basics! Here's a complete example you can modify:\n", pause * 0.5
218
+ )
219
+
220
+ print(
221
+ """
222
+ from tnfr.sdk import TNFRNetwork
223
+
224
+ # Create your network
225
+ net = TNFRNetwork("my_experiment")
226
+
227
+ # Add nodes and connect them
228
+ net.add_nodes(20, random_seed=123)
229
+ net.connect_nodes(0.4, "random")
230
+
231
+ # Apply operators (try different sequences!)
232
+ net.apply_sequence("basic_activation", repeat=5)
233
+
234
+ # Or try: "stabilization", "creative_mutation",
235
+ # "network_sync", "exploration"
236
+
237
+ # Measure results
238
+ results = net.measure()
239
+ print(results.summary())
240
+
241
+ # Access detailed data
242
+ print(f"Coherence: {results.coherence:.3f}")
243
+ for node_id, si in results.sense_indices.items():
244
+ print(f" Node {node_id}: Si = {si:.3f}")
245
+ """
246
+ )
247
+
248
+ _print_section("Tutorial Complete! 🎉")
249
+
250
+ _explain(
251
+ "You've learned:\n"
252
+ " ✓ How to create TNFR networks\n"
253
+ " ✓ What structural operators do\n"
254
+ " ✓ How to measure coherence and sense index\n"
255
+ " ✓ How to interpret results\n\n"
256
+ "Next steps:\n"
257
+ " • Try biological_example() - cell communication\n"
258
+ " • Try social_network_example() - social dynamics\n"
259
+ " • Try technology_example() - distributed systems\n"
260
+ " • Read the full docs: docs/source/getting-started/",
261
+ 0,
262
+ )
263
+
264
+ print(f"\n{'='*70}\n")
265
+
266
+
267
+ def biological_example(interactive: bool = True, random_seed: int = 42) -> dict:
268
+ """Cell communication model using TNFR.
269
+
270
+ This tutorial models how cells communicate through chemical signals,
271
+ demonstrating TNFR's application to biological systems.
272
+
273
+ Concepts demonstrated:
274
+ - Nodes as cells
275
+ - Emission as signal secretion
276
+ - Reception as receptor binding
277
+ - Coupling as direct cell-cell contact
278
+ - Coherence as tissue organization
279
+
280
+ Parameters
281
+ ----------
282
+ interactive : bool, default=True
283
+ If True, pauses between sections for reading.
284
+ random_seed : int, default=42
285
+ Random seed for reproducibility.
286
+
287
+ Returns
288
+ -------
289
+ dict
290
+ Simulation results with coherence, sense indices, and interpretation.
291
+
292
+ Examples
293
+ --------
294
+ >>> from tnfr.tutorials import biological_example
295
+ >>> results = biological_example()
296
+ >>> print(f"Tissue coherence: {results['coherence']:.3f}")
297
+
298
+ Notes
299
+ -----
300
+ This tutorial demonstrates:
301
+ - Emission operator (signal secretion)
302
+ - Reception operator (signal detection)
303
+ - Coupling operator (cell-cell contact)
304
+ - Coherence operator (tissue stability)
305
+ """
306
+ if not _HAS_SDK:
307
+ print("Error: SDK not available. Install with: pip install tnfr")
308
+ return {}
309
+
310
+ pause = 1.5 if interactive else 0
311
+
312
+ _print_section("TNFR Tutorial: Cell Communication 🧬")
313
+
314
+ _explain(
315
+ "In this example, we'll model how cells in a tissue communicate\n"
316
+ "and organize themselves using TNFR principles.\n\n"
317
+ "Biological → TNFR mapping:\n"
318
+ " • Cell → Node (NFR)\n"
319
+ " • Chemical signal → Emission operator\n"
320
+ " • Receptor binding → Reception operator\n"
321
+ " • Cell-cell contact → Coupling operator\n"
322
+ " • Tissue organization → Coherence",
323
+ pause,
324
+ )
325
+
326
+ _print_subsection("Step 1: Create Cell Population")
327
+
328
+ _explain(
329
+ "Let's create a tissue with 25 cells. Each cell has:\n"
330
+ " • Structural frequency νf ∈ [0.3, 0.9] Hz_str (metabolic rate)\n"
331
+ " • Phase φ (cell cycle position)\n"
332
+ " • EPI (cell state/phenotype)",
333
+ pause,
334
+ )
335
+
336
+ print(" >>> network = TNFRNetwork('cell_tissue')")
337
+ print(" >>> network.add_nodes(25, vf_range=(0.3, 0.9), random_seed=42)\n")
338
+
339
+ network = TNFRNetwork("cell_tissue")
340
+ network.add_nodes(25, vf_range=(0.3, 0.9), random_seed=random_seed)
341
+
342
+ _explain("✓ Created 25 cells with varying metabolic rates", pause * 0.5)
343
+
344
+ _print_subsection("Step 2: Establish Cell Connections")
345
+
346
+ _explain(
347
+ "Cells connect through:\n"
348
+ " • Physical contacts (gap junctions)\n"
349
+ " • Paracrine signaling (nearby cells)\n\n"
350
+ "We'll use a ring topology (like epithelial cells) with 50% connectivity:",
351
+ pause,
352
+ )
353
+
354
+ print(" >>> network.connect_nodes(0.5, 'ring')\n")
355
+ network.connect_nodes(0.5, "ring")
356
+
357
+ _explain("✓ Cells connected in tissue-like structure", pause * 0.5)
358
+
359
+ _print_subsection("Step 3: Simulate Cell Signaling")
360
+
361
+ _explain(
362
+ "Now let's simulate cell communication cycles:\n"
363
+ " 1. Emission - Cells secrete signaling molecules\n"
364
+ " 2. Reception - Neighboring cells detect signals\n"
365
+ " 3. Coherence - Cells stabilize coordinated state\n"
366
+ " 4. Coupling - Direct cell-cell interaction\n"
367
+ " 5. Resonance - Synchronized response amplification\n"
368
+ " 6. Silence - Rest period between cycles\n\n"
369
+ "We'll run 5 signaling cycles:",
370
+ pause,
371
+ )
372
+
373
+ print(" >>> network.apply_sequence('network_sync', repeat=5)\n")
374
+ network.apply_sequence("network_sync", repeat=5)
375
+
376
+ _explain("✓ Completed 5 cell signaling cycles", pause * 0.5)
377
+
378
+ _print_subsection("Step 4: Measure Tissue Organization")
379
+
380
+ _explain("Let's measure how well the tissue organized:", pause * 0.5)
381
+
382
+ print(" >>> results = network.measure()\n")
383
+ results = network.measure()
384
+
385
+ coherence = results.coherence
386
+ avg_si = (
387
+ sum(results.sense_indices.values()) / len(results.sense_indices)
388
+ if results.sense_indices
389
+ else 0
390
+ )
391
+
392
+ print(f" Tissue Coherence C(t) = {coherence:.3f}")
393
+ print(f" Average Cell Si = {avg_si:.3f}")
394
+ print(f" Number of Cells = {len(results.sense_indices)}\n")
395
+
396
+ _print_subsection("Step 5: Biological Interpretation")
397
+
398
+ if coherence > 0.6:
399
+ tissue_status = "well-organized"
400
+ bio_meaning = "Cells are synchronized and functioning as coordinated tissue."
401
+ elif coherence > 0.3:
402
+ tissue_status = "moderately organized"
403
+ bio_meaning = "Cells show some coordination but not fully synchronized."
404
+ else:
405
+ tissue_status = "loosely organized"
406
+ bio_meaning = "Cells are relatively independent with weak coordination."
407
+
408
+ _explain(
409
+ f"Results:\n"
410
+ f" • Tissue Status: {tissue_status}\n"
411
+ f" • Biological Meaning: {bio_meaning}\n"
412
+ f" • Cell Responsiveness: Average Si = {avg_si:.3f}\n\n"
413
+ f"In biological terms:\n"
414
+ f" This simulates how cells in a tissue coordinate their behavior\n"
415
+ f" through chemical signaling and physical contacts. The coherence\n"
416
+ f" value indicates how well they form organized tissue structure.\n\n"
417
+ f" Higher coherence = Better tissue organization\n"
418
+ f" Higher Si = Better individual cell adaptability",
419
+ pause,
420
+ )
421
+
422
+ _print_section("Cell Communication Tutorial Complete! 🧬")
423
+
424
+ return {
425
+ "coherence": coherence,
426
+ "sense_indices": results.sense_indices,
427
+ "interpretation": {
428
+ "tissue_status": tissue_status,
429
+ "biological_meaning": bio_meaning,
430
+ "avg_cell_responsiveness": avg_si,
431
+ },
432
+ "results": results,
433
+ }
434
+
435
+
436
+ def social_network_example(interactive: bool = True, random_seed: int = 42) -> dict:
437
+ """Social dynamics simulation using TNFR.
438
+
439
+ This tutorial models social network dynamics, demonstrating how
440
+ TNFR applies to social systems and group behavior.
441
+
442
+ Concepts demonstrated:
443
+ - Nodes as people
444
+ - Emission as communication/expression
445
+ - Reception as listening/influence
446
+ - Resonance as shared understanding
447
+ - Coherence as group cohesion
448
+ - Dissonance as conflict/disagreement
449
+
450
+ Parameters
451
+ ----------
452
+ interactive : bool, default=True
453
+ If True, pauses between sections for reading.
454
+ random_seed : int, default=42
455
+ Random seed for reproducibility.
456
+
457
+ Returns
458
+ -------
459
+ dict
460
+ Simulation results with social metrics and interpretation.
461
+
462
+ Examples
463
+ --------
464
+ >>> from tnfr.tutorials import social_network_example
465
+ >>> results = social_network_example()
466
+ >>> print(f"Group cohesion: {results['coherence']:.3f}")
467
+
468
+ Notes
469
+ -----
470
+ This tutorial demonstrates:
471
+ - Dissonance operator (conflict/debate)
472
+ - Mutation operator (opinion change)
473
+ - Resonance operator (consensus building)
474
+ - Coherence as social cohesion measure
475
+ """
476
+ if not _HAS_SDK:
477
+ print("Error: SDK not available. Install with: pip install tnfr")
478
+ return {}
479
+
480
+ pause = 1.5 if interactive else 0
481
+
482
+ _print_section("TNFR Tutorial: Social Network Dynamics 👥")
483
+
484
+ _explain(
485
+ "In this example, we'll model social dynamics in a group of people\n"
486
+ "using TNFR to understand consensus, conflict, and cohesion.\n\n"
487
+ "Social → TNFR mapping:\n"
488
+ " • Person → Node (NFR)\n"
489
+ " • Communication → Emission/Reception operators\n"
490
+ " • Shared understanding → Resonance operator\n"
491
+ " • Conflict/debate → Dissonance operator\n"
492
+ " • Opinion change → Mutation operator\n"
493
+ " • Group cohesion → Coherence C(t)",
494
+ pause,
495
+ )
496
+
497
+ _print_subsection("Step 1: Create Social Group")
498
+
499
+ _explain(
500
+ "Let's model a community of 30 people. Each person has:\n"
501
+ " • Structural frequency νf (communication frequency)\n"
502
+ " • Phase φ (opinion/perspective)\n"
503
+ " • EPI (belief system/worldview)",
504
+ pause,
505
+ )
506
+
507
+ print(" >>> network = TNFRNetwork('social_group')")
508
+ print(" >>> network.add_nodes(30, random_seed=42)\n")
509
+
510
+ network = TNFRNetwork("social_group")
511
+ network.add_nodes(30, random_seed=random_seed)
512
+
513
+ _explain("✓ Created community of 30 people", pause * 0.5)
514
+
515
+ _print_subsection("Step 2: Establish Social Connections")
516
+
517
+ _explain(
518
+ "People form social connections (friendships, work relationships).\n"
519
+ "We'll use random connections with 25% probability (realistic social density):",
520
+ pause,
521
+ )
522
+
523
+ print(" >>> network.connect_nodes(0.25, 'random')\n")
524
+ network.connect_nodes(0.25, "random")
525
+
526
+ _explain("✓ Social network formed", pause * 0.5)
527
+
528
+ _print_subsection("Step 3: Simulate Social Interaction")
529
+
530
+ _explain(
531
+ "We'll simulate a scenario with:\n"
532
+ " Phase A: Basic activation and debate\n"
533
+ " Phase B: Opinion evolution (creative mutation)\n"
534
+ " Phase C: Consensus building (stabilization)\n\n"
535
+ "First, let's activate the social network:",
536
+ pause,
537
+ )
538
+
539
+ print(" >>> network.apply_sequence('basic_activation', repeat=3)\n")
540
+ network.apply_sequence("basic_activation", repeat=3)
541
+
542
+ _explain("✓ Completed initial social interaction phase", pause)
543
+
544
+ _explain(
545
+ "\nNow, let's allow opinions to synchronize and reach consensus:", pause * 0.5
546
+ )
547
+
548
+ print(" >>> network.apply_sequence('basic_activation', repeat=2)")
549
+ print(" >>> network.apply_sequence('stabilization', repeat=3)\n")
550
+
551
+ network.apply_sequence("basic_activation", repeat=2)
552
+ network.apply_sequence("stabilization", repeat=3)
553
+
554
+ _explain("✓ Opinions evolved and group stabilized", pause * 0.5)
555
+
556
+ _print_subsection("Step 4: Measure Group Cohesion")
557
+
558
+ _explain("Let's measure the social dynamics:", pause * 0.5)
559
+
560
+ print(" >>> results = network.measure()\n")
561
+ results = network.measure()
562
+
563
+ coherence = results.coherence
564
+ avg_si = (
565
+ sum(results.sense_indices.values()) / len(results.sense_indices)
566
+ if results.sense_indices
567
+ else 0
568
+ )
569
+
570
+ print(f" Group Coherence C(t) = {coherence:.3f}")
571
+ print(f" Average Individual Si = {avg_si:.3f}")
572
+ print(f" Group Size = {len(results.sense_indices)}\n")
573
+
574
+ _print_subsection("Step 5: Social Interpretation")
575
+
576
+ if coherence > 0.6:
577
+ social_status = "highly cohesive"
578
+ social_meaning = "Strong group consensus and shared understanding."
579
+ elif coherence > 0.3:
580
+ social_status = "moderately cohesive"
581
+ social_meaning = "Some agreement but diverse opinions remain."
582
+ else:
583
+ social_status = "loosely cohesive"
584
+ social_meaning = "Fragmented group with weak consensus."
585
+
586
+ if avg_si > 0.5:
587
+ adaptability = "high"
588
+ adapt_meaning = "Individuals can adjust views while maintaining identity."
589
+ else:
590
+ adaptability = "moderate"
591
+ adapt_meaning = "Individuals have some flexibility in their opinions."
592
+
593
+ _explain(
594
+ f"Results:\n"
595
+ f" • Group Status: {social_status}\n"
596
+ f" • Social Meaning: {social_meaning}\n"
597
+ f" • Individual Adaptability: {adaptability}\n"
598
+ f" • Adaptability Meaning: {adapt_meaning}\n\n"
599
+ f"In social terms:\n"
600
+ f" After debate and discussion, the group reached a coherence of {coherence:.3f}.\n"
601
+ f" This indicates how well the group coordinated their beliefs and opinions.\n\n"
602
+ f" The dissonance phase (debate) introduced diverse perspectives.\n"
603
+ f" The mutation phase allowed opinions to evolve naturally.\n"
604
+ f" The stabilization phase built consensus and shared understanding.\n\n"
605
+ f" Higher coherence = Stronger group consensus\n"
606
+ f" Higher Si = Better individual adaptability without losing identity",
607
+ pause,
608
+ )
609
+
610
+ _print_section("Social Network Tutorial Complete! 👥")
611
+
612
+ return {
613
+ "coherence": coherence,
614
+ "sense_indices": results.sense_indices,
615
+ "interpretation": {
616
+ "social_status": social_status,
617
+ "social_meaning": social_meaning,
618
+ "adaptability": adaptability,
619
+ "adapt_meaning": adapt_meaning,
620
+ "avg_si": avg_si,
621
+ },
622
+ "results": results,
623
+ }
624
+
625
+
626
+ def technology_example(interactive: bool = True, random_seed: int = 42) -> dict:
627
+ """Distributed systems model using TNFR.
628
+
629
+ This tutorial models distributed computing systems, demonstrating
630
+ how TNFR applies to technology and computer networks.
631
+
632
+ Concepts demonstrated:
633
+ - Nodes as servers/microservices
634
+ - Emission as message broadcasting
635
+ - Reception as message processing
636
+ - Coupling as service dependencies
637
+ - Coherence as system reliability
638
+ - Silence as graceful degradation
639
+
640
+ Parameters
641
+ ----------
642
+ interactive : bool, default=True
643
+ If True, pauses between sections for reading.
644
+ random_seed : int, default=42
645
+ Random seed for reproducibility.
646
+
647
+ Returns
648
+ -------
649
+ dict
650
+ Simulation results with system metrics and interpretation.
651
+
652
+ Examples
653
+ --------
654
+ >>> from tnfr.tutorials import technology_example
655
+ >>> results = technology_example()
656
+ >>> print(f"System reliability: {results['coherence']:.3f}")
657
+
658
+ Notes
659
+ -----
660
+ This tutorial demonstrates:
661
+ - Coupling operator (service dependencies)
662
+ - Silence operator (graceful degradation)
663
+ - Resonance operator (load balancing)
664
+ - Coherence as system reliability measure
665
+ """
666
+ if not _HAS_SDK:
667
+ print("Error: SDK not available. Install with: pip install tnfr")
668
+ return {}
669
+
670
+ pause = 1.5 if interactive else 0
671
+
672
+ _print_section("TNFR Tutorial: Distributed Systems 💻")
673
+
674
+ _explain(
675
+ "In this example, we'll model a distributed microservices architecture\n"
676
+ "using TNFR to analyze system reliability and resilience.\n\n"
677
+ "Technology → TNFR mapping:\n"
678
+ " • Microservice → Node (NFR)\n"
679
+ " • Message passing → Emission/Reception operators\n"
680
+ " • Service dependency → Coupling operator\n"
681
+ " • Load balancing → Resonance operator\n"
682
+ " • Graceful degradation → Silence operator\n"
683
+ " • System reliability → Coherence C(t)",
684
+ pause,
685
+ )
686
+
687
+ _print_subsection("Step 1: Create Microservices Cluster")
688
+
689
+ _explain(
690
+ "Let's model a cluster of 15 microservices. Each service has:\n"
691
+ " • Structural frequency νf (request processing rate)\n"
692
+ " • Phase φ (operational state/timing)\n"
693
+ " • EPI (service configuration/state)",
694
+ pause,
695
+ )
696
+
697
+ print(" >>> network = TNFRNetwork('microservices')")
698
+ print(" >>> network.add_nodes(15, vf_range=(0.5, 1.2), random_seed=42)\n")
699
+
700
+ network = TNFRNetwork("microservices")
701
+ network.add_nodes(15, vf_range=(0.5, 1.2), random_seed=random_seed)
702
+
703
+ _explain("✓ Created cluster of 15 microservices", pause * 0.5)
704
+
705
+ _print_subsection("Step 2: Establish Service Dependencies")
706
+
707
+ _explain(
708
+ "Microservices communicate through:\n"
709
+ " • REST APIs\n"
710
+ " • Message queues\n"
711
+ " • Service mesh\n\n"
712
+ "We'll use a network topology with 40% connectivity:",
713
+ pause,
714
+ )
715
+
716
+ print(" >>> network.connect_nodes(0.4, 'random')\n")
717
+ network.connect_nodes(0.4, "random")
718
+
719
+ _explain("✓ Service dependencies established", pause * 0.5)
720
+
721
+ _print_subsection("Step 3: Simulate System Operations")
722
+
723
+ _explain(
724
+ "We'll simulate normal operations followed by load testing:\n\n"
725
+ "Phase A: Normal operations with synchronization\n"
726
+ " (network_sync sequence - coordinated request handling)",
727
+ pause,
728
+ )
729
+
730
+ print(" >>> network.apply_sequence('network_sync', repeat=5)\n")
731
+ network.apply_sequence("network_sync", repeat=5)
732
+
733
+ _explain("✓ Completed normal operation cycles", pause * 0.5)
734
+
735
+ _explain(
736
+ "\nPhase B: System consolidation and stabilization\n"
737
+ " (consolidation sequence - optimize and stabilize)",
738
+ pause * 0.5,
739
+ )
740
+
741
+ print(" >>> network.apply_sequence('consolidation', repeat=3)\n")
742
+ network.apply_sequence("consolidation", repeat=3)
743
+
744
+ _explain("✓ System consolidated and stabilized", pause * 0.5)
745
+
746
+ _print_subsection("Step 4: Measure System Reliability")
747
+
748
+ _explain("Let's measure the system health:", pause * 0.5)
749
+
750
+ print(" >>> results = network.measure()\n")
751
+ results = network.measure()
752
+
753
+ coherence = results.coherence
754
+ avg_si = (
755
+ sum(results.sense_indices.values()) / len(results.sense_indices)
756
+ if results.sense_indices
757
+ else 0
758
+ )
759
+ avg_vf = results.avg_vf or 0
760
+
761
+ print(f" System Coherence C(t) = {coherence:.3f}")
762
+ print(f" Average Service Si = {avg_si:.3f}")
763
+ print(f" Average Processing Rate νf = {avg_vf:.3f} Hz_str")
764
+ print(f" Number of Services = {len(results.sense_indices)}\n")
765
+
766
+ _print_subsection("Step 5: Technical Interpretation")
767
+
768
+ if coherence > 0.6:
769
+ system_status = "highly reliable"
770
+ tech_meaning = "Services are well-coordinated with low failure risk."
771
+ elif coherence > 0.3:
772
+ system_status = "moderately reliable"
773
+ tech_meaning = "System is functional but may have coordination issues."
774
+ else:
775
+ system_status = "needs attention"
776
+ tech_meaning = "Services are poorly coordinated, high failure risk."
777
+
778
+ if avg_si > 0.5:
779
+ resilience = "high resilience"
780
+ resilience_meaning = "Services can adapt to load changes and failures."
781
+ else:
782
+ resilience = "moderate resilience"
783
+ resilience_meaning = "Services have limited adaptability to disruptions."
784
+
785
+ _explain(
786
+ f"Results:\n"
787
+ f" • System Status: {system_status}\n"
788
+ f" • Technical Meaning: {tech_meaning}\n"
789
+ f" • Resilience: {resilience}\n"
790
+ f" • Resilience Meaning: {resilience_meaning}\n\n"
791
+ f"In technical terms:\n"
792
+ f" The system achieved coherence of {coherence:.3f}, indicating how well\n"
793
+ f" the microservices coordinate their operations and handle requests.\n\n"
794
+ f" Key insights:\n"
795
+ f" • Coherence C(t) = System reliability and coordination\n"
796
+ f" • Sense Index Si = Service resilience and adaptability\n"
797
+ f" • Frequency νf = Request processing rate\n\n"
798
+ f" The network_sync sequence simulates:\n"
799
+ f" - Message broadcasting (emission)\n"
800
+ f" - Request processing (reception)\n"
801
+ f" - State synchronization (coherence)\n"
802
+ f" - Service coupling (coupling)\n"
803
+ f" - Load distribution (resonance)\n"
804
+ f" - Graceful handling (silence)\n\n"
805
+ f" Higher coherence = More reliable distributed system\n"
806
+ f" Higher Si = Better fault tolerance and adaptability",
807
+ pause,
808
+ )
809
+
810
+ _print_section("Distributed Systems Tutorial Complete! 💻")
811
+
812
+ return {
813
+ "coherence": coherence,
814
+ "sense_indices": results.sense_indices,
815
+ "interpretation": {
816
+ "system_status": system_status,
817
+ "technical_meaning": tech_meaning,
818
+ "resilience": resilience,
819
+ "resilience_meaning": resilience_meaning,
820
+ "avg_si": avg_si,
821
+ "avg_vf": avg_vf,
822
+ },
823
+ "results": results,
824
+ }
825
+
826
+
827
+ def run_all_tutorials(interactive: bool = True, random_seed: int = 42) -> dict:
828
+ """Run all tutorials in sequence.
829
+
830
+ This function runs the complete tutorial sequence:
831
+ 1. hello_tnfr() - Introduction
832
+ 2. biological_example() - Cell communication
833
+ 3. social_network_example() - Social dynamics
834
+ 4. technology_example() - Distributed systems
835
+
836
+ Parameters
837
+ ----------
838
+ interactive : bool, default=True
839
+ If True, pauses between tutorials for reading.
840
+ random_seed : int, default=42
841
+ Random seed for reproducibility across all tutorials.
842
+
843
+ Returns
844
+ -------
845
+ dict
846
+ Combined results from all tutorials.
847
+
848
+ Examples
849
+ --------
850
+ >>> from tnfr.tutorials import run_all_tutorials
851
+ >>> all_results = run_all_tutorials()
852
+ >>> print(f"Completed {len(all_results)} tutorials!")
853
+ """
854
+ if not _HAS_SDK:
855
+ print("Error: SDK not available. Install with: pip install tnfr")
856
+ return {}
857
+
858
+ results = {}
859
+
860
+ print("\n" + "=" * 70)
861
+ print("TNFR Complete Tutorial Series")
862
+ print("=" * 70)
863
+ print("\nThis will run all 4 tutorials in sequence:")
864
+ print(" 1. Hello TNFR (5 min)")
865
+ print(" 2. Biological Example (cell communication)")
866
+ print(" 3. Social Network Example (group dynamics)")
867
+ print(" 4. Technology Example (distributed systems)")
868
+ print("\nEstimated time: ~15-20 minutes")
869
+ print("=" * 70 + "\n")
870
+
871
+ if interactive:
872
+ time.sleep(3)
873
+
874
+ # Tutorial 1
875
+ hello_tnfr(interactive=interactive, random_seed=random_seed)
876
+ results["hello_tnfr"] = "completed"
877
+
878
+ if interactive:
879
+ print("\nPress Enter to continue to the next tutorial...")
880
+ input()
881
+
882
+ # Tutorial 2
883
+ bio_results = biological_example(interactive=interactive, random_seed=random_seed)
884
+ results["biological"] = bio_results
885
+
886
+ if interactive:
887
+ print("\nPress Enter to continue to the next tutorial...")
888
+ input()
889
+
890
+ # Tutorial 3
891
+ social_results = social_network_example(
892
+ interactive=interactive, random_seed=random_seed
893
+ )
894
+ results["social"] = social_results
895
+
896
+ if interactive:
897
+ print("\nPress Enter to continue to the final tutorial...")
898
+ input()
899
+
900
+ # Tutorial 4
901
+ tech_results = technology_example(interactive=interactive, random_seed=random_seed)
902
+ results["technology"] = tech_results
903
+
904
+ # Summary
905
+ _print_section("All Tutorials Complete! 🎉")
906
+
907
+ print("You've completed the full TNFR tutorial series!\n")
908
+ print("Summary of Results:")
909
+ print("-" * 70)
910
+
911
+ if "biological" in results:
912
+ print(
913
+ f" • Cell Communication: C(t) = {results['biological']['coherence']:.3f}"
914
+ )
915
+ if "social" in results:
916
+ print(f" • Social Network: C(t) = {results['social']['coherence']:.3f}")
917
+ if "technology" in results:
918
+ print(
919
+ f" • Distributed Systems: C(t) = {results['technology']['coherence']:.3f}"
920
+ )
921
+
922
+ print("\n" + "-" * 70)
923
+ print("\nNext Steps:")
924
+ print(" • Explore the SDK: from tnfr.sdk import TNFRNetwork")
925
+ print(" • Read the docs: docs/source/getting-started/")
926
+ print(" • Try your own experiments!")
927
+ print(" • Check out examples/ directory for more")
928
+ print("\n" + "=" * 70 + "\n")
929
+
930
+ return results
931
+
932
+
933
+ def team_communication_example(interactive: bool = True, random_seed: int = 42) -> dict:
934
+ """Team communication comparison example using TNFR.
935
+
936
+ This example demonstrates how to model and optimize team communication
937
+ patterns using different network topologies. It's the hands-on version
938
+ of the tutorial in INTERACTIVE_TUTORIAL.md Part 3.
939
+
940
+ Concepts demonstrated:
941
+ - Comparing network topologies (random, ring, small-world)
942
+ - Measuring communication effectiveness via coherence
943
+ - Optimizing team structure
944
+ - Interpreting individual node metrics
945
+
946
+ Parameters
947
+ ----------
948
+ interactive : bool, default=True
949
+ If True, pauses between sections for reading.
950
+ random_seed : int, default=42
951
+ Random seed for reproducibility.
952
+
953
+ Returns
954
+ -------
955
+ dict
956
+ Results for each team structure with analysis.
957
+
958
+ Examples
959
+ --------
960
+ >>> from tnfr.tutorials import team_communication_example
961
+ >>> results = team_communication_example()
962
+ >>> print(f"Best structure: {results['best_structure']}")
963
+
964
+ Notes
965
+ -----
966
+ This tutorial demonstrates practical application of TNFR to
967
+ organizational design and communication optimization.
968
+ """
969
+ if not _HAS_SDK:
970
+ print("Error: SDK not available. Install with: pip install tnfr")
971
+ return {}
972
+
973
+ pause = 1.5 if interactive else 0
974
+
975
+ _print_section("TNFR Tutorial: Team Communication 👥")
976
+
977
+ _explain(
978
+ "In this example, we'll compare different team communication structures\n"
979
+ "and identify which topology creates the most coherent organization.\n\n"
980
+ "We'll model:\n"
981
+ " • Team members as nodes\n"
982
+ " • Communication relationships as connections\n"
983
+ " • Information flow as operator sequences\n"
984
+ " • Team alignment as coherence C(t)",
985
+ pause,
986
+ )
987
+
988
+ _print_subsection("Step 1: Create Three Team Structures")
989
+
990
+ _explain(
991
+ "We'll create 8-person teams with different topologies:\n"
992
+ " 1. Random - Organic, unstructured\n"
993
+ " 2. Ring - Linear communication chain\n"
994
+ " 3. Small-World - Mix of local and distant connections",
995
+ pause,
996
+ )
997
+
998
+ print(" >>> random_team = TNFRNetwork('random_team')")
999
+ print(" >>> random_team.add_nodes(8, random_seed=42)")
1000
+ print(" >>> random_team.connect_nodes(0.3, connection_pattern='random')\n")
1001
+
1002
+ random_team = TNFRNetwork("random_team")
1003
+ random_team.add_nodes(8, random_seed=random_seed)
1004
+ random_team.connect_nodes(0.3, connection_pattern="random")
1005
+
1006
+ print(" >>> ring_team = TNFRNetwork('ring_team')")
1007
+ print(" >>> ring_team.add_nodes(8, random_seed=42)")
1008
+ print(" >>> ring_team.connect_nodes(connection_pattern='ring')\n")
1009
+
1010
+ ring_team = TNFRNetwork("ring_team")
1011
+ ring_team.add_nodes(8, random_seed=random_seed)
1012
+ ring_team.connect_nodes(connection_pattern="ring")
1013
+
1014
+ print(" >>> sw_team = TNFRNetwork('small_world_team')")
1015
+ print(" >>> sw_team.add_nodes(8, random_seed=42)")
1016
+ print(" >>> sw_team.connect_nodes(0.15, connection_pattern='small_world')\n")
1017
+
1018
+ sw_team = TNFRNetwork("small_world_team")
1019
+ sw_team.add_nodes(8, random_seed=random_seed)
1020
+ sw_team.connect_nodes(0.15, connection_pattern="small_world")
1021
+
1022
+ _explain(
1023
+ f"✓ Created 3 team structures:\n"
1024
+ f" - Random: {random_team.get_edge_count()} connections\n"
1025
+ f" - Ring: {ring_team.get_edge_count()} connections\n"
1026
+ f" - Small-world: {sw_team.get_edge_count()} connections",
1027
+ pause,
1028
+ )
1029
+
1030
+ _print_subsection("Step 2: Simulate Communication")
1031
+
1032
+ _explain(
1033
+ "Now we'll apply the same communication sequence to all teams\n"
1034
+ "and measure which structure achieves better alignment:",
1035
+ pause,
1036
+ )
1037
+
1038
+ print(" >>> for team in [random_team, ring_team, sw_team]:")
1039
+ print(" ... team.apply_sequence('network_sync', repeat=5)\n")
1040
+
1041
+ random_team.apply_sequence("network_sync", repeat=5)
1042
+ ring_team.apply_sequence("network_sync", repeat=5)
1043
+ sw_team.apply_sequence("network_sync", repeat=5)
1044
+
1045
+ _explain("✓ Applied 5 communication cycles to each team", pause * 0.5)
1046
+
1047
+ _print_subsection("Step 3: Compare Results")
1048
+
1049
+ random_results = random_team.measure()
1050
+ ring_results = ring_team.measure()
1051
+ sw_results = sw_team.measure()
1052
+
1053
+ print(" Communication Effectiveness:\n")
1054
+ print(f" Random Team:")
1055
+ print(f" - Coherence: {random_results.coherence:.3f}")
1056
+ print(f" - Density: {random_team.get_density():.3f}\n")
1057
+
1058
+ print(f" Ring Team:")
1059
+ print(f" - Coherence: {ring_results.coherence:.3f}")
1060
+ print(f" - Density: {ring_team.get_density():.3f}\n")
1061
+
1062
+ print(f" Small-World Team:")
1063
+ print(f" - Coherence: {sw_results.coherence:.3f}")
1064
+ print(f" - Density: {sw_team.get_density():.3f}\n")
1065
+
1066
+ teams = {
1067
+ "Random": random_results.coherence,
1068
+ "Ring": ring_results.coherence,
1069
+ "Small-World": sw_results.coherence,
1070
+ }
1071
+ best_team = max(teams, key=teams.get)
1072
+
1073
+ _explain(
1074
+ f"🏆 Most coherent team structure: {best_team}\n\n"
1075
+ f"Interpretation:\n"
1076
+ f" The {best_team} topology achieved highest coherence ({teams[best_team]:.3f}),\n"
1077
+ f" indicating better information synchronization across the team.",
1078
+ pause,
1079
+ )
1080
+
1081
+ _print_section("Team Communication Tutorial Complete! 👥")
1082
+
1083
+ return {
1084
+ "random": {
1085
+ "coherence": random_results.coherence,
1086
+ "density": random_team.get_density(),
1087
+ },
1088
+ "ring": {
1089
+ "coherence": ring_results.coherence,
1090
+ "density": ring_team.get_density(),
1091
+ },
1092
+ "small_world": {
1093
+ "coherence": sw_results.coherence,
1094
+ "density": sw_team.get_density(),
1095
+ },
1096
+ "best_structure": best_team,
1097
+ "results": {
1098
+ "random": random_results,
1099
+ "ring": ring_results,
1100
+ "small_world": sw_results,
1101
+ },
1102
+ }
1103
+
1104
+
1105
+ def adaptive_ai_example(interactive: bool = True, random_seed: int = 42) -> dict:
1106
+ """Adaptive AI system example using TNFR.
1107
+
1108
+ This tutorial demonstrates how TNFR can model learning and adaptation
1109
+ through resonance rather than traditional gradient descent. It shows
1110
+ structural learning principles.
1111
+
1112
+ Concepts demonstrated:
1113
+ - Learning as coherence increase (not error minimization)
1114
+ - Adaptation via structural reorganization
1115
+ - Memory as stable EPI patterns
1116
+ - Context sensitivity via phase coupling
1117
+
1118
+ Parameters
1119
+ ----------
1120
+ interactive : bool, default=True
1121
+ If True, pauses between sections for reading.
1122
+ random_seed : int, default=42
1123
+ Random seed for reproducibility.
1124
+
1125
+ Returns
1126
+ -------
1127
+ dict
1128
+ Learning trajectory and final system state.
1129
+
1130
+ Examples
1131
+ --------
1132
+ >>> from tnfr.tutorials import adaptive_ai_example
1133
+ >>> results = adaptive_ai_example()
1134
+ >>> print(f"Learning improvement: {results['improvement']:.1f}%")
1135
+
1136
+ Notes
1137
+ -----
1138
+ This demonstrates TNFR's alternative to traditional ML:
1139
+ - No backpropagation or gradient descent
1140
+ - Learning through resonance and structural operators
1141
+ - Maintains coherence throughout adaptation
1142
+ """
1143
+ if not _HAS_SDK:
1144
+ print("Error: SDK not available. Install with: pip install tnfr")
1145
+ return {}
1146
+
1147
+ pause = 1.5 if interactive else 0
1148
+
1149
+ _print_section("TNFR Tutorial: Adaptive AI System 🤖")
1150
+
1151
+ _explain(
1152
+ "In this example, we'll model a learning system using TNFR principles.\n"
1153
+ "Unlike traditional ML, learning happens through structural resonance,\n"
1154
+ "not gradient descent.\n\n"
1155
+ "TNFR Learning Model:\n"
1156
+ " • Nodes = Processing units (like neurons, but resonant)\n"
1157
+ " • Coherence increase = Learning (not error reduction)\n"
1158
+ " • Mutation operator = Exploration\n"
1159
+ " • Resonance operator = Pattern consolidation",
1160
+ pause,
1161
+ )
1162
+
1163
+ _print_subsection("Step 1: Create Initial 'Naive' System")
1164
+
1165
+ _explain(
1166
+ "We start with an unorganized network representing\n"
1167
+ "a system before training:",
1168
+ pause,
1169
+ )
1170
+
1171
+ print(" >>> naive_system = TNFRNetwork('learning_system')")
1172
+ print(" >>> naive_system.add_nodes(15, random_seed=42)")
1173
+ print(" >>> naive_system.connect_nodes(0.25, 'random') # Sparse connections\n")
1174
+
1175
+ naive_system = TNFRNetwork("learning_system")
1176
+ naive_system.add_nodes(15, random_seed=random_seed)
1177
+ naive_system.connect_nodes(0.25, "random")
1178
+
1179
+ print(" >>> naive_system.apply_sequence('basic_activation', repeat=2)")
1180
+ print(" >>> initial_state = naive_system.measure()\n")
1181
+
1182
+ naive_system.apply_sequence("basic_activation", repeat=2)
1183
+ initial_state = naive_system.measure()
1184
+
1185
+ initial_coherence = initial_state.coherence
1186
+
1187
+ _explain(
1188
+ f"Initial system state (before learning):\n"
1189
+ f" • Coherence: {initial_coherence:.3f}\n"
1190
+ f" • This represents an 'untrained' system",
1191
+ pause,
1192
+ )
1193
+
1194
+ _print_subsection("Step 2: 'Training' via Structural Reorganization")
1195
+
1196
+ _explain(
1197
+ "Training in TNFR means applying sequences that increase coherence:\n"
1198
+ " 1. Exploration (mutation + dissonance)\n"
1199
+ " 2. Consolidation (coherence + resonance)\n"
1200
+ " 3. Repeat until convergence\n\n"
1201
+ "This is fundamentally different from backpropagation!",
1202
+ pause,
1203
+ )
1204
+
1205
+ print(" >>> # Training loop")
1206
+ print(" >>> for epoch in range(3):")
1207
+ print(" ... naive_system.apply_sequence('network_sync', repeat=2)")
1208
+ print(" ... naive_system.apply_sequence('consolidation', repeat=3)\n")
1209
+
1210
+ coherence_trajectory = [initial_coherence]
1211
+
1212
+ for epoch in range(3):
1213
+ naive_system.apply_sequence("network_sync", repeat=2)
1214
+ naive_system.apply_sequence("consolidation", repeat=3)
1215
+ epoch_results = naive_system.measure()
1216
+ coherence_trajectory.append(epoch_results.coherence)
1217
+ if interactive:
1218
+ print(f" Epoch {epoch+1}: C(t) = {epoch_results.coherence:.3f}")
1219
+
1220
+ print()
1221
+
1222
+ _print_subsection("Step 3: Evaluate Learning")
1223
+
1224
+ final_state = naive_system.measure()
1225
+ final_coherence = final_state.coherence
1226
+ improvement = ((final_coherence - initial_coherence) / initial_coherence) * 100
1227
+
1228
+ _explain(
1229
+ f"Learning Results:\n"
1230
+ f" • Initial coherence: {initial_coherence:.3f}\n"
1231
+ f" • Final coherence: {final_coherence:.3f}\n"
1232
+ f" • Improvement: {improvement:+.1f}%\n\n"
1233
+ f"Interpretation:\n"
1234
+ f" The system 'learned' by increasing its internal coherence.\n"
1235
+ f" Higher coherence = Better organized = More 'trained'\n\n"
1236
+ f" This demonstrates learning as structural reorganization,\n"
1237
+ f" not as weight optimization!",
1238
+ pause,
1239
+ )
1240
+
1241
+ _print_subsection("Step 4: TNFR vs Traditional ML")
1242
+
1243
+ _explain(
1244
+ "Key Differences:\n\n"
1245
+ "Traditional ML (backprop):\n"
1246
+ " • Minimize error/loss\n"
1247
+ " • Adjust weights via gradients\n"
1248
+ " • Fixed architecture\n\n"
1249
+ "TNFR Adaptive Systems:\n"
1250
+ " • Maximize coherence\n"
1251
+ " • Reorganize structure via operators\n"
1252
+ " • Dynamic, self-organizing architecture\n\n"
1253
+ "Both work, but TNFR preserves structural meaning throughout.",
1254
+ pause,
1255
+ )
1256
+
1257
+ _print_section("Adaptive AI Tutorial Complete! 🤖")
1258
+
1259
+ return {
1260
+ "initial_coherence": initial_coherence,
1261
+ "final_coherence": final_coherence,
1262
+ "improvement": improvement,
1263
+ "coherence_trajectory": coherence_trajectory,
1264
+ "final_state": final_state,
1265
+ "interpretation": (
1266
+ f"System improved coherence by {improvement:.1f}% through "
1267
+ f"structural reorganization, demonstrating learning without "
1268
+ f"traditional gradient descent."
1269
+ ),
1270
+ }
1271
+
1272
+
1273
+ def oz_dissonance_tutorial(interactive: bool = True, random_seed: int = 42) -> dict:
1274
+ """Interactive tutorial on OZ (Dissonance) operator and canonical sequences.
1275
+
1276
+ This tutorial covers:
1277
+ - Theoretical foundations of OZ (topological dissonance)
1278
+ - When to use OZ vs when to avoid
1279
+ - 6 canonical sequences with OZ from TNFR theory
1280
+ - Bifurcation paths and resolution patterns
1281
+ - Common errors and how to fix them
1282
+
1283
+ Parameters
1284
+ ----------
1285
+ interactive : bool, default=True
1286
+ If True, pauses between sections for reading.
1287
+ random_seed : int, default=42
1288
+ Random seed for reproducibility.
1289
+
1290
+ Returns
1291
+ -------
1292
+ dict
1293
+ Tutorial results including sequence demonstrations and coherence metrics.
1294
+
1295
+ Examples
1296
+ --------
1297
+ >>> from tnfr.tutorials import oz_dissonance_tutorial
1298
+ >>> oz_dissonance_tutorial() # Run full tutorial
1299
+ >>> oz_dissonance_tutorial(interactive=False) # Run without pauses
1300
+
1301
+ Notes
1302
+ -----
1303
+ This tutorial demonstrates canonical sequences from "El pulso que nos
1304
+ atraviesa" Table 2.5, maintaining full TNFR theoretical fidelity.
1305
+ """
1306
+ if not _HAS_SDK:
1307
+ print("Error: SDK not available. Install with: pip install tnfr")
1308
+ return {}
1309
+
1310
+ pause = 1.5 if interactive else 0
1311
+
1312
+ _print_section("OZ (DISSONANCE) OPERATOR - Interactive Tutorial")
1313
+
1314
+ _explain(
1315
+ "Welcome to the OZ (Dissonance) tutorial!\n\n"
1316
+ "OZ is one of the 13 canonical structural operators in TNFR.\n"
1317
+ "It introduces CONTROLLED INSTABILITY to enable creative exploration\n"
1318
+ "and transformation. This tutorial will show you how to use it effectively.",
1319
+ pause,
1320
+ )
1321
+
1322
+ # Section 1: What is OZ?
1323
+ _print_subsection("Part 1: What is OZ (Dissonance)?")
1324
+
1325
+ _explain(
1326
+ "🌀 OZ introduces controlled instability that enables:\n\n"
1327
+ " ✓ Creative exploration of new structural configurations\n"
1328
+ " ✓ Bifurcation into alternative reorganization paths\n"
1329
+ " ✓ Mutation enablement (OZ → ZHIR canonical pattern)\n"
1330
+ " ✓ Topological disruption of rigid patterns\n\n"
1331
+ "Important: OZ is NOT destructive - it's GENERATIVE dissonance.\n"
1332
+ "Think of it as asking challenging questions rather than breaking things.",
1333
+ pause,
1334
+ )
1335
+
1336
+ # Section 2: When to use OZ
1337
+ _print_subsection("Part 2: When to Use OZ")
1338
+
1339
+ _explain(
1340
+ "⚠️ Use OZ in these situations:\n\n"
1341
+ " ✅ After stabilization (IL) to explore new possibilities\n"
1342
+ " ✅ Before mutation (ZHIR) to justify transformation\n"
1343
+ " ✅ In therapeutic protocols to confront blockages\n"
1344
+ " ✅ In learning to challenge existing mental models\n\n"
1345
+ "OZ works best when the system is stable enough to handle disruption.",
1346
+ pause,
1347
+ )
1348
+
1349
+ # Section 3: When to AVOID OZ
1350
+ _print_subsection("Part 3: When to AVOID OZ")
1351
+
1352
+ _explain(
1353
+ "🚫 Avoid OZ in these situations:\n\n"
1354
+ " ❌ On latent/weak nodes (EPI < 0.2) → causes collapse\n"
1355
+ " ❌ When ΔNFR already critical (ΔNFR > 0.8) → overload\n"
1356
+ " ❌ Multiple OZ without IL resolution → entropic noise\n"
1357
+ " ❌ Immediately before SHA (silence) → contradictory\n\n"
1358
+ "Rule of thumb: Stabilize before you destabilize!",
1359
+ pause,
1360
+ )
1361
+
1362
+ # Section 4: Canonical Sequences with OZ
1363
+ _print_subsection("Part 4: Canonical Sequences with OZ")
1364
+
1365
+ _explain(
1366
+ "TNFR theory defines 6 archetypal sequences involving OZ.\n"
1367
+ "Let's explore them with live demonstrations...",
1368
+ pause,
1369
+ )
1370
+
1371
+ from ..operators.canonical_patterns import CANONICAL_SEQUENCES
1372
+ from ..types import Glyph
1373
+
1374
+ # Get sequences with OZ
1375
+ oz_sequences = {
1376
+ name: seq for name, seq in CANONICAL_SEQUENCES.items() if Glyph.OZ in seq.glyphs
1377
+ }
1378
+
1379
+ _explain(f"\nFound {len(oz_sequences)} canonical sequences with OZ:\n", pause * 0.5)
1380
+
1381
+ for i, (name, seq) in enumerate(sorted(oz_sequences.items()), 1):
1382
+ glyphs_str = " → ".join(g.value for g in seq.glyphs)
1383
+ print(f"{i}. {name.upper()}")
1384
+ print(f" Pattern: {seq.pattern_type.value}")
1385
+ print(f" Domain: {seq.domain}")
1386
+ print(f" Glyphs: {glyphs_str}")
1387
+ print(f" Use: {seq.use_cases[0]}\n")
1388
+
1389
+ # Section 5: Hands-on Demonstration - Bifurcated Pattern
1390
+ _print_subsection("Part 5: Hands-On Demo - Bifurcated Pattern")
1391
+
1392
+ _explain(
1393
+ "Let's demonstrate the BIFURCATED pattern:\n"
1394
+ "This pattern shows how OZ creates a decision point where the node\n"
1395
+ "can either mutate (ZHIR) or collapse (NUL).\n\n"
1396
+ "We'll apply the 'bifurcated_base' sequence (mutation path):",
1397
+ pause,
1398
+ )
1399
+
1400
+ print(" >>> from tnfr.sdk import TNFRNetwork")
1401
+ print(" >>> net = TNFRNetwork('bifurcation_demo')")
1402
+ print(" >>> net.add_nodes(1)")
1403
+ print(" >>> net.apply_canonical_sequence('bifurcated_base')\n")
1404
+
1405
+ from ..sdk import TNFRNetwork, NetworkConfig
1406
+
1407
+ net_bifurc = TNFRNetwork("bifurcation_demo", NetworkConfig(random_seed=random_seed))
1408
+ net_bifurc.add_nodes(1)
1409
+ net_bifurc.apply_canonical_sequence("bifurcated_base")
1410
+
1411
+ results_bifurc = net_bifurc.measure()
1412
+
1413
+ print(f" ✓ Bifurcation completed!")
1414
+ print(f" Final Coherence C(t): {results_bifurc.coherence:.3f}\n")
1415
+
1416
+ _explain(
1417
+ "Interpretation:\n"
1418
+ " The sequence AL → EN → IL → OZ → ZHIR → IL → SHA shows:\n"
1419
+ " 1. Node is activated and stabilized (AL → EN → IL)\n"
1420
+ " 2. Dissonance introduced (OZ) creating instability\n"
1421
+ " 3. Node mutates to new form (ZHIR)\n"
1422
+ " 4. New form is stabilized (IL) and enters rest (SHA)\n\n"
1423
+ f" High coherence ({results_bifurc.coherence:.3f}) shows successful transformation!",
1424
+ pause,
1425
+ )
1426
+
1427
+ # Section 6: Therapeutic Protocol Demo
1428
+ _print_subsection("Part 6: Therapeutic Protocol Demo")
1429
+
1430
+ _explain(
1431
+ "Now let's demonstrate the THERAPEUTIC protocol:\n"
1432
+ "This is used for healing and personal transformation.\n"
1433
+ "We'll create a small network to represent a therapeutic context:",
1434
+ pause,
1435
+ )
1436
+
1437
+ print(" >>> net = TNFRNetwork('therapy')")
1438
+ print(" >>> net.add_nodes(3).connect_nodes(0.4, 'random')")
1439
+ print(" >>> net.apply_canonical_sequence('therapeutic_protocol')\n")
1440
+
1441
+ net_therapy = TNFRNetwork("therapy", NetworkConfig(random_seed=random_seed))
1442
+ net_therapy.add_nodes(3)
1443
+ net_therapy.connect_nodes(0.4, "random")
1444
+ net_therapy.apply_canonical_sequence("therapeutic_protocol")
1445
+
1446
+ results_therapy = net_therapy.measure()
1447
+ avg_si_therapy = (
1448
+ sum(results_therapy.sense_indices.values()) / len(results_therapy.sense_indices)
1449
+ if results_therapy.sense_indices
1450
+ else 0
1451
+ )
1452
+
1453
+ print(f" ✓ Therapeutic protocol completed!")
1454
+ print(f" Final Coherence C(t): {results_therapy.coherence:.3f}")
1455
+ print(f" Average Sense Index Si: {avg_si_therapy:.3f}\n")
1456
+
1457
+ _explain(
1458
+ "Interpretation:\n"
1459
+ " The therapeutic protocol (AL → EN → IL → OZ → ZHIR → IL → RA → SHA):\n"
1460
+ " 1. Initiates symbolic field (AL)\n"
1461
+ " 2. Stabilizes the therapeutic context (EN → IL)\n"
1462
+ " 3. Introduces creative confrontation (OZ)\n"
1463
+ " 4. Enables personal transformation (ZHIR)\n"
1464
+ " 5. Integrates new form (IL)\n"
1465
+ " 6. Propagates through network (RA)\n"
1466
+ " 7. Enters restful integration (SHA)\n\n"
1467
+ f" Coherence of {results_therapy.coherence:.3f} shows therapeutic effectiveness!",
1468
+ pause,
1469
+ )
1470
+
1471
+ # Section 7: MOD_STABILIZER - Reusable Macro
1472
+ _print_subsection("Part 7: MOD_STABILIZER - Reusable Transformation")
1473
+
1474
+ _explain(
1475
+ "The MOD_STABILIZER is a reusable macro for safe transformation:\n"
1476
+ "REMESH → EN → IL → OZ → ZHIR → IL → REMESH\n\n"
1477
+ "It's designed to be composable within larger sequences.\n"
1478
+ "This is your 'safe transformation module':",
1479
+ pause,
1480
+ )
1481
+
1482
+ print(" >>> net = TNFRNetwork('modular')")
1483
+ print(" >>> net.add_nodes(1)")
1484
+ print(" >>> net.apply_canonical_sequence('mod_stabilizer')\n")
1485
+
1486
+ net_mod = TNFRNetwork("modular", NetworkConfig(random_seed=random_seed))
1487
+ net_mod.add_nodes(1)
1488
+ net_mod.apply_canonical_sequence("mod_stabilizer")
1489
+
1490
+ results_mod = net_mod.measure()
1491
+
1492
+ print(f" ✓ MOD_STABILIZER completed!")
1493
+ print(f" Final Coherence C(t): {results_mod.coherence:.3f}\n")
1494
+
1495
+ _explain(
1496
+ "This module can be nested in larger sequences:\n"
1497
+ " THOL[MOD_STABILIZER] ≡ THOL[REMESH → EN → IL → OZ → ZHIR → IL → REMESH]\n\n"
1498
+ "It's a building block for complex transformations!",
1499
+ pause,
1500
+ )
1501
+
1502
+ # Section 8: Filtering and Discovery
1503
+ _print_subsection("Part 8: Discovering OZ Sequences")
1504
+
1505
+ _explain("You can programmatically discover sequences with OZ:\n", pause * 0.5)
1506
+
1507
+ print(" >>> net = TNFRNetwork('explorer')")
1508
+ print(" >>> oz_seqs = net.list_canonical_sequences(with_oz=True)")
1509
+ print(f" >>> print(f'Found {{len(oz_seqs)}} sequences with OZ')\n")
1510
+
1511
+ net_explorer = TNFRNetwork("explorer")
1512
+ oz_seqs = net_explorer.list_canonical_sequences(with_oz=True)
1513
+
1514
+ print(f" Found {len(oz_seqs)} sequences with OZ\n")
1515
+
1516
+ _explain("You can also filter by domain:", pause * 0.5)
1517
+
1518
+ print(" >>> bio_seqs = net.list_canonical_sequences(domain='biomedical')")
1519
+ print(" >>> cog_seqs = net.list_canonical_sequences(domain='cognitive')\n")
1520
+
1521
+ bio_seqs = net_explorer.list_canonical_sequences(domain="biomedical")
1522
+ cog_seqs = net_explorer.list_canonical_sequences(domain="cognitive")
1523
+
1524
+ print(f" Biomedical sequences: {len(bio_seqs)}")
1525
+ print(f" Cognitive sequences: {len(cog_seqs)}\n")
1526
+
1527
+ # Section 9: Summary and Best Practices
1528
+ _print_subsection("Part 9: Summary and Best Practices")
1529
+
1530
+ _explain(
1531
+ "KEY TAKEAWAYS:\n\n"
1532
+ "1. OZ is GENERATIVE dissonance, not destructive\n"
1533
+ "2. Always stabilize (IL) before introducing dissonance (OZ)\n"
1534
+ "3. OZ typically pairs with ZHIR (mutation) for transformation\n"
1535
+ "4. Use canonical sequences for reliable patterns\n"
1536
+ "5. Filter sequences by domain for specific applications\n\n"
1537
+ "BEST PRACTICES:\n\n"
1538
+ " • Start with canonical sequences before custom patterns\n"
1539
+ " • Test on simple networks before complex ones\n"
1540
+ " • Monitor coherence C(t) to ensure stability\n"
1541
+ " • Use MOD_STABILIZER as a building block\n"
1542
+ " • Consult theoretical docs for deeper understanding",
1543
+ pause,
1544
+ )
1545
+
1546
+ _print_section("OZ Dissonance Tutorial Complete! 🌀")
1547
+
1548
+ _explain(
1549
+ "You now understand:\n"
1550
+ " ✓ What OZ (Dissonance) does\n"
1551
+ " ✓ When to use and avoid OZ\n"
1552
+ " ✓ 6 canonical sequences with OZ\n"
1553
+ " ✓ How to apply them programmatically\n"
1554
+ " ✓ How to discover and filter sequences\n\n"
1555
+ "Next steps:\n"
1556
+ " • Explore examples/oz_canonical_sequences.py for more details\n"
1557
+ " • Try creating your own sequences with OZ\n"
1558
+ " • Read 'El pulso que nos atraviesa' for theoretical depth",
1559
+ pause,
1560
+ )
1561
+
1562
+ return {
1563
+ "bifurcated_coherence": results_bifurc.coherence,
1564
+ "therapeutic_coherence": results_therapy.coherence,
1565
+ "therapeutic_avg_si": avg_si_therapy,
1566
+ "mod_stabilizer_coherence": results_mod.coherence,
1567
+ "total_oz_sequences": len(oz_seqs),
1568
+ "biomedical_sequences": len(bio_seqs),
1569
+ "cognitive_sequences": len(cog_seqs),
1570
+ "interpretation": (
1571
+ f"Successfully demonstrated {len(oz_seqs)} canonical sequences with OZ. "
1572
+ f"Bifurcation achieved {results_bifurc.coherence:.3f} coherence, "
1573
+ f"therapeutic protocol achieved {results_therapy.coherence:.3f} coherence. "
1574
+ f"All patterns maintain TNFR canonical invariants."
1575
+ ),
1576
+ }