tnfr 3.0.3__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 (360) hide show
  1. tnfr/__init__.py +375 -56
  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 +723 -0
  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 +171 -0
  15. tnfr/cache.pyi +13 -0
  16. tnfr/cli/__init__.py +110 -0
  17. tnfr/cli/__init__.pyi +26 -0
  18. tnfr/cli/arguments.py +489 -0
  19. tnfr/cli/arguments.pyi +29 -0
  20. tnfr/cli/execution.py +914 -0
  21. tnfr/cli/execution.pyi +70 -0
  22. tnfr/cli/interactive_validator.py +614 -0
  23. tnfr/cli/utils.py +51 -0
  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/config/constants.py +104 -0
  34. tnfr/config/constants.pyi +12 -0
  35. tnfr/config/defaults.py +54 -0
  36. tnfr/config/defaults_core.py +212 -0
  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 +92 -0
  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 +33 -0
  57. tnfr/constants/init.pyi +12 -0
  58. tnfr/constants/metric.py +104 -0
  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 +238 -0
  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 +3034 -0
  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 +661 -0
  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 +36 -0
  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 +223 -0
  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 +262 -0
  125. tnfr/flatten.pyi +21 -0
  126. tnfr/gamma.py +354 -0
  127. tnfr/gamma.pyi +36 -0
  128. tnfr/glyph_history.py +377 -0
  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 +218 -0
  133. tnfr/immutable.pyi +36 -0
  134. tnfr/initialization.py +203 -0
  135. tnfr/initialization.pyi +65 -0
  136. tnfr/io.py +10 -0
  137. tnfr/io.pyi +13 -0
  138. tnfr/locking.py +37 -0
  139. tnfr/locking.pyi +7 -0
  140. tnfr/mathematics/__init__.py +79 -0
  141. tnfr/mathematics/backend.py +453 -0
  142. tnfr/mathematics/backend.pyi +99 -0
  143. tnfr/mathematics/dynamics.py +408 -0
  144. tnfr/mathematics/dynamics.pyi +90 -0
  145. tnfr/mathematics/epi.py +391 -0
  146. tnfr/mathematics/epi.pyi +65 -0
  147. tnfr/mathematics/generators.py +242 -0
  148. tnfr/mathematics/generators.pyi +29 -0
  149. tnfr/mathematics/metrics.py +119 -0
  150. tnfr/mathematics/metrics.pyi +16 -0
  151. tnfr/mathematics/operators.py +239 -0
  152. tnfr/mathematics/operators.pyi +59 -0
  153. tnfr/mathematics/operators_factory.py +124 -0
  154. tnfr/mathematics/operators_factory.pyi +11 -0
  155. tnfr/mathematics/projection.py +87 -0
  156. tnfr/mathematics/projection.pyi +33 -0
  157. tnfr/mathematics/runtime.py +182 -0
  158. tnfr/mathematics/runtime.pyi +64 -0
  159. tnfr/mathematics/spaces.py +256 -0
  160. tnfr/mathematics/spaces.pyi +83 -0
  161. tnfr/mathematics/transforms.py +305 -0
  162. tnfr/mathematics/transforms.pyi +62 -0
  163. tnfr/metrics/__init__.py +79 -0
  164. tnfr/metrics/__init__.pyi +20 -0
  165. tnfr/metrics/buffer_cache.py +163 -0
  166. tnfr/metrics/buffer_cache.pyi +24 -0
  167. tnfr/metrics/cache_utils.py +214 -0
  168. tnfr/metrics/coherence.py +2009 -0
  169. tnfr/metrics/coherence.pyi +129 -0
  170. tnfr/metrics/common.py +158 -0
  171. tnfr/metrics/common.pyi +35 -0
  172. tnfr/metrics/core.py +316 -0
  173. tnfr/metrics/core.pyi +13 -0
  174. tnfr/metrics/diagnosis.py +833 -0
  175. tnfr/metrics/diagnosis.pyi +86 -0
  176. tnfr/metrics/emergence.py +245 -0
  177. tnfr/metrics/export.py +179 -0
  178. tnfr/metrics/export.pyi +7 -0
  179. tnfr/metrics/glyph_timing.py +379 -0
  180. tnfr/metrics/glyph_timing.pyi +81 -0
  181. tnfr/metrics/learning_metrics.py +280 -0
  182. tnfr/metrics/learning_metrics.pyi +21 -0
  183. tnfr/metrics/phase_coherence.py +351 -0
  184. tnfr/metrics/phase_compatibility.py +349 -0
  185. tnfr/metrics/reporting.py +183 -0
  186. tnfr/metrics/reporting.pyi +25 -0
  187. tnfr/metrics/sense_index.py +1203 -0
  188. tnfr/metrics/sense_index.pyi +9 -0
  189. tnfr/metrics/trig.py +373 -0
  190. tnfr/metrics/trig.pyi +13 -0
  191. tnfr/metrics/trig_cache.py +233 -0
  192. tnfr/metrics/trig_cache.pyi +10 -0
  193. tnfr/multiscale/__init__.py +32 -0
  194. tnfr/multiscale/hierarchical.py +517 -0
  195. tnfr/node.py +763 -0
  196. tnfr/node.pyi +139 -0
  197. tnfr/observers.py +255 -130
  198. tnfr/observers.pyi +31 -0
  199. tnfr/ontosim.py +144 -137
  200. tnfr/ontosim.pyi +28 -0
  201. tnfr/operators/__init__.py +1672 -0
  202. tnfr/operators/__init__.pyi +31 -0
  203. tnfr/operators/algebra.py +277 -0
  204. tnfr/operators/canonical_patterns.py +420 -0
  205. tnfr/operators/cascade.py +267 -0
  206. tnfr/operators/cycle_detection.py +358 -0
  207. tnfr/operators/definitions.py +4108 -0
  208. tnfr/operators/definitions.pyi +78 -0
  209. tnfr/operators/grammar.py +1164 -0
  210. tnfr/operators/grammar.pyi +140 -0
  211. tnfr/operators/hamiltonian.py +710 -0
  212. tnfr/operators/health_analyzer.py +809 -0
  213. tnfr/operators/jitter.py +272 -0
  214. tnfr/operators/jitter.pyi +11 -0
  215. tnfr/operators/lifecycle.py +314 -0
  216. tnfr/operators/metabolism.py +618 -0
  217. tnfr/operators/metrics.py +2138 -0
  218. tnfr/operators/network_analysis/__init__.py +27 -0
  219. tnfr/operators/network_analysis/source_detection.py +186 -0
  220. tnfr/operators/nodal_equation.py +395 -0
  221. tnfr/operators/pattern_detection.py +660 -0
  222. tnfr/operators/patterns.py +669 -0
  223. tnfr/operators/postconditions/__init__.py +38 -0
  224. tnfr/operators/postconditions/mutation.py +236 -0
  225. tnfr/operators/preconditions/__init__.py +1226 -0
  226. tnfr/operators/preconditions/coherence.py +305 -0
  227. tnfr/operators/preconditions/dissonance.py +236 -0
  228. tnfr/operators/preconditions/emission.py +128 -0
  229. tnfr/operators/preconditions/mutation.py +580 -0
  230. tnfr/operators/preconditions/reception.py +125 -0
  231. tnfr/operators/preconditions/resonance.py +364 -0
  232. tnfr/operators/registry.py +74 -0
  233. tnfr/operators/registry.pyi +9 -0
  234. tnfr/operators/remesh.py +1809 -0
  235. tnfr/operators/remesh.pyi +26 -0
  236. tnfr/operators/structural_units.py +268 -0
  237. tnfr/operators/unified_grammar.py +105 -0
  238. tnfr/parallel/__init__.py +54 -0
  239. tnfr/parallel/auto_scaler.py +234 -0
  240. tnfr/parallel/distributed.py +384 -0
  241. tnfr/parallel/engine.py +238 -0
  242. tnfr/parallel/gpu_engine.py +420 -0
  243. tnfr/parallel/monitoring.py +248 -0
  244. tnfr/parallel/partitioner.py +459 -0
  245. tnfr/py.typed +0 -0
  246. tnfr/recipes/__init__.py +22 -0
  247. tnfr/recipes/cookbook.py +743 -0
  248. tnfr/rng.py +178 -0
  249. tnfr/rng.pyi +26 -0
  250. tnfr/schemas/__init__.py +8 -0
  251. tnfr/schemas/grammar.json +94 -0
  252. tnfr/sdk/__init__.py +107 -0
  253. tnfr/sdk/__init__.pyi +19 -0
  254. tnfr/sdk/adaptive_system.py +173 -0
  255. tnfr/sdk/adaptive_system.pyi +21 -0
  256. tnfr/sdk/builders.py +370 -0
  257. tnfr/sdk/builders.pyi +51 -0
  258. tnfr/sdk/fluent.py +1121 -0
  259. tnfr/sdk/fluent.pyi +74 -0
  260. tnfr/sdk/templates.py +342 -0
  261. tnfr/sdk/templates.pyi +41 -0
  262. tnfr/sdk/utils.py +341 -0
  263. tnfr/secure_config.py +46 -0
  264. tnfr/security/__init__.py +70 -0
  265. tnfr/security/database.py +514 -0
  266. tnfr/security/subprocess.py +503 -0
  267. tnfr/security/validation.py +290 -0
  268. tnfr/selector.py +247 -0
  269. tnfr/selector.pyi +19 -0
  270. tnfr/sense.py +378 -0
  271. tnfr/sense.pyi +23 -0
  272. tnfr/services/__init__.py +17 -0
  273. tnfr/services/orchestrator.py +325 -0
  274. tnfr/sparse/__init__.py +39 -0
  275. tnfr/sparse/representations.py +492 -0
  276. tnfr/structural.py +705 -0
  277. tnfr/structural.pyi +83 -0
  278. tnfr/telemetry/__init__.py +35 -0
  279. tnfr/telemetry/cache_metrics.py +226 -0
  280. tnfr/telemetry/cache_metrics.pyi +64 -0
  281. tnfr/telemetry/nu_f.py +422 -0
  282. tnfr/telemetry/nu_f.pyi +108 -0
  283. tnfr/telemetry/verbosity.py +36 -0
  284. tnfr/telemetry/verbosity.pyi +15 -0
  285. tnfr/tokens.py +58 -0
  286. tnfr/tokens.pyi +36 -0
  287. tnfr/tools/__init__.py +20 -0
  288. tnfr/tools/domain_templates.py +478 -0
  289. tnfr/tools/sequence_generator.py +846 -0
  290. tnfr/topology/__init__.py +13 -0
  291. tnfr/topology/asymmetry.py +151 -0
  292. tnfr/trace.py +543 -0
  293. tnfr/trace.pyi +42 -0
  294. tnfr/tutorials/__init__.py +38 -0
  295. tnfr/tutorials/autonomous_evolution.py +285 -0
  296. tnfr/tutorials/interactive.py +1576 -0
  297. tnfr/tutorials/structural_metabolism.py +238 -0
  298. tnfr/types.py +775 -0
  299. tnfr/types.pyi +357 -0
  300. tnfr/units.py +68 -0
  301. tnfr/units.pyi +13 -0
  302. tnfr/utils/__init__.py +282 -0
  303. tnfr/utils/__init__.pyi +215 -0
  304. tnfr/utils/cache.py +4223 -0
  305. tnfr/utils/cache.pyi +470 -0
  306. tnfr/utils/callbacks.py +375 -0
  307. tnfr/utils/callbacks.pyi +49 -0
  308. tnfr/utils/chunks.py +108 -0
  309. tnfr/utils/chunks.pyi +22 -0
  310. tnfr/utils/data.py +428 -0
  311. tnfr/utils/data.pyi +74 -0
  312. tnfr/utils/graph.py +85 -0
  313. tnfr/utils/graph.pyi +10 -0
  314. tnfr/utils/init.py +821 -0
  315. tnfr/utils/init.pyi +80 -0
  316. tnfr/utils/io.py +559 -0
  317. tnfr/utils/io.pyi +66 -0
  318. tnfr/utils/numeric.py +114 -0
  319. tnfr/utils/numeric.pyi +21 -0
  320. tnfr/validation/__init__.py +257 -0
  321. tnfr/validation/__init__.pyi +85 -0
  322. tnfr/validation/compatibility.py +460 -0
  323. tnfr/validation/compatibility.pyi +6 -0
  324. tnfr/validation/config.py +73 -0
  325. tnfr/validation/graph.py +139 -0
  326. tnfr/validation/graph.pyi +18 -0
  327. tnfr/validation/input_validation.py +755 -0
  328. tnfr/validation/invariants.py +712 -0
  329. tnfr/validation/rules.py +253 -0
  330. tnfr/validation/rules.pyi +44 -0
  331. tnfr/validation/runtime.py +279 -0
  332. tnfr/validation/runtime.pyi +28 -0
  333. tnfr/validation/sequence_validator.py +162 -0
  334. tnfr/validation/soft_filters.py +170 -0
  335. tnfr/validation/soft_filters.pyi +32 -0
  336. tnfr/validation/spectral.py +164 -0
  337. tnfr/validation/spectral.pyi +42 -0
  338. tnfr/validation/validator.py +1266 -0
  339. tnfr/validation/window.py +39 -0
  340. tnfr/validation/window.pyi +1 -0
  341. tnfr/visualization/__init__.py +98 -0
  342. tnfr/visualization/cascade_viz.py +256 -0
  343. tnfr/visualization/hierarchy.py +284 -0
  344. tnfr/visualization/sequence_plotter.py +784 -0
  345. tnfr/viz/__init__.py +60 -0
  346. tnfr/viz/matplotlib.py +278 -0
  347. tnfr/viz/matplotlib.pyi +35 -0
  348. tnfr-8.5.0.dist-info/METADATA +573 -0
  349. tnfr-8.5.0.dist-info/RECORD +353 -0
  350. tnfr-8.5.0.dist-info/entry_points.txt +3 -0
  351. tnfr-3.0.3.dist-info/licenses/LICENSE.txt → tnfr-8.5.0.dist-info/licenses/LICENSE.md +1 -1
  352. tnfr/constants.py +0 -183
  353. tnfr/dynamics.py +0 -543
  354. tnfr/helpers.py +0 -198
  355. tnfr/main.py +0 -37
  356. tnfr/operators.py +0 -296
  357. tnfr-3.0.3.dist-info/METADATA +0 -35
  358. tnfr-3.0.3.dist-info/RECORD +0 -13
  359. {tnfr-3.0.3.dist-info → tnfr-8.5.0.dist-info}/WHEEL +0 -0
  360. {tnfr-3.0.3.dist-info → tnfr-8.5.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,743 @@
1
+ """TNFR Pattern Cookbook - Programmatic access to validated recipes.
2
+
3
+ This module provides a comprehensive library of pre-validated operator sequences
4
+ organized by domain. All recipes are validated against TNFR Grammar 2.0 and
5
+ include health metrics, use cases, and variations.
6
+
7
+ Examples
8
+ --------
9
+ >>> from tnfr.recipes import TNFRCookbook
10
+ >>> cookbook = TNFRCookbook()
11
+ >>> recipe = cookbook.get_recipe("therapeutic", "crisis_intervention")
12
+ >>> print(recipe.sequence)
13
+ ['emission', 'reception', 'coherence', 'dissonance', 'contraction', 'coherence', 'coupling', 'silence']
14
+ >>> print(recipe.health_metrics.overall_health)
15
+ 0.786
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import List, Dict, Optional, Any
21
+ from ..compat.dataclass import dataclass
22
+ from ..operators.health_analyzer import SequenceHealthMetrics, SequenceHealthAnalyzer
23
+ from ..operators.grammar import validate_sequence_with_health
24
+
25
+
26
+ __all__ = [
27
+ "CookbookRecipe",
28
+ "RecipeVariation",
29
+ "TNFRCookbook",
30
+ ]
31
+
32
+
33
+ @dataclass
34
+ class RecipeVariation:
35
+ """A variation of a cookbook recipe for specific contexts.
36
+
37
+ Attributes
38
+ ----------
39
+ name : str
40
+ Name of the variation
41
+ description : str
42
+ What changes in this variation
43
+ sequence : List[str]
44
+ Modified operator sequence
45
+ health_impact : float
46
+ Expected change in health score (positive or negative)
47
+ context : str
48
+ When to use this variation
49
+ """
50
+
51
+ name: str
52
+ description: str
53
+ sequence: List[str]
54
+ health_impact: float
55
+ context: str
56
+
57
+
58
+ @dataclass
59
+ class CookbookRecipe:
60
+ """A validated TNFR operator sequence recipe with full context.
61
+
62
+ Attributes
63
+ ----------
64
+ name : str
65
+ Recipe name (e.g., "Crisis Intervention")
66
+ domain : str
67
+ Application domain (therapeutic, educational, organizational, creative)
68
+ sequence : List[str]
69
+ Validated operator sequence
70
+ health_metrics : SequenceHealthMetrics
71
+ Computed health metrics for the sequence
72
+ use_cases : List[str]
73
+ Specific real-world applications
74
+ when_to_use : str
75
+ Context description for applying this pattern
76
+ structural_flow : List[str]
77
+ Operator-by-operator explanation of structural effects
78
+ key_insights : List[str]
79
+ Critical success factors and mechanisms
80
+ variations : List[RecipeVariation]
81
+ Adaptations for related contexts
82
+ pattern_type : str
83
+ Detected TNFR pattern type
84
+ """
85
+
86
+ name: str
87
+ domain: str
88
+ sequence: List[str]
89
+ health_metrics: SequenceHealthMetrics
90
+ use_cases: List[str]
91
+ when_to_use: str
92
+ structural_flow: List[str]
93
+ key_insights: List[str]
94
+ variations: List[RecipeVariation]
95
+ pattern_type: str
96
+
97
+
98
+ class TNFRCookbook:
99
+ """Library of validated TNFR operator sequence recipes.
100
+
101
+ Provides programmatic access to the pattern cookbook with search,
102
+ filtering, and recommendation capabilities.
103
+
104
+ Examples
105
+ --------
106
+ >>> cookbook = TNFRCookbook()
107
+ >>> # Get specific recipe
108
+ >>> recipe = cookbook.get_recipe("therapeutic", "crisis_intervention")
109
+ >>> print(f"Health: {recipe.health_metrics.overall_health:.3f}")
110
+ Health: 0.786
111
+
112
+ >>> # List all recipes in domain
113
+ >>> therapeutic = cookbook.list_recipes(domain="therapeutic")
114
+ >>> len(therapeutic)
115
+ 5
116
+
117
+ >>> # Search by keyword
118
+ >>> results = cookbook.search_recipes("team")
119
+ >>> [r.name for r in results]
120
+ ['Team Formation', 'Strategic Planning']
121
+ """
122
+
123
+ def __init__(self) -> None:
124
+ """Initialize the cookbook with all validated recipes."""
125
+ self._recipes: Dict[str, Dict[str, CookbookRecipe]] = {}
126
+ self._analyzer = SequenceHealthAnalyzer()
127
+ self._load_recipes()
128
+
129
+ def _load_recipes(self) -> None:
130
+ """Load all recipes from domain pattern modules."""
131
+ # Import domain patterns
132
+ try:
133
+ from examples.domain_applications import therapeutic_patterns
134
+ from examples.domain_applications import educational_patterns
135
+ from examples.domain_applications import organizational_patterns
136
+ from examples.domain_applications import creative_patterns
137
+ except ImportError:
138
+ # Fallback for when examples are not in path
139
+ import sys
140
+ from pathlib import Path
141
+
142
+ examples_path = (
143
+ Path(__file__).parent.parent.parent.parent
144
+ / "examples"
145
+ / "domain_applications"
146
+ )
147
+ sys.path.insert(0, str(examples_path))
148
+ import therapeutic_patterns
149
+ import educational_patterns
150
+ import organizational_patterns
151
+ import creative_patterns
152
+
153
+ # Load therapeutic recipes
154
+ self._load_domain_recipes(
155
+ "therapeutic",
156
+ therapeutic_patterns,
157
+ [
158
+ (
159
+ "crisis_intervention",
160
+ "Crisis Intervention",
161
+ [
162
+ "Panic attack management",
163
+ "Acute grief response",
164
+ "Immediate post-trauma stabilization",
165
+ "Emergency emotional support",
166
+ ],
167
+ "Immediate stabilization needed, limited time available, high-intensity crisis requiring rapid containment.",
168
+ ),
169
+ (
170
+ "process_therapy",
171
+ "Process Therapy",
172
+ [
173
+ "Long-term psychotherapy processes",
174
+ "Personal transformation work",
175
+ "Complex trauma resolution",
176
+ "Deep character structure change",
177
+ ],
178
+ "Deep change required, sufficient time and resources available, client readiness for transformative work established.",
179
+ ),
180
+ (
181
+ "regenerative_healing",
182
+ "Regenerative Healing",
183
+ [
184
+ "Chronic condition management",
185
+ "Ongoing recovery processes",
186
+ "Building resilience patterns",
187
+ "Preventive mental health work",
188
+ ],
189
+ "Long-term healing journey, building sustainable coping patterns, emphasis on self-renewal capacity.",
190
+ ),
191
+ (
192
+ "insight_integration",
193
+ "Insight Integration",
194
+ [
195
+ "Post-breakthrough consolidation",
196
+ "Integrate therapeutic insights into daily life",
197
+ "Stabilize sudden understanding or awareness",
198
+ "Connect insights to behavioral change",
199
+ ],
200
+ "After significant therapeutic breakthrough, to anchor and propagate new understanding across life domains.",
201
+ ),
202
+ (
203
+ "relapse_prevention",
204
+ "Relapse Prevention",
205
+ [
206
+ "Addiction recovery maintenance",
207
+ "Prevent regression after therapy",
208
+ "Maintain behavioral changes",
209
+ "Strengthen therapeutic gains",
210
+ ],
211
+ "Post-treatment phase, building relapse prevention skills, strengthening recovery patterns.",
212
+ ),
213
+ ],
214
+ )
215
+
216
+ # Load educational recipes
217
+ self._load_domain_recipes(
218
+ "educational",
219
+ educational_patterns,
220
+ [
221
+ (
222
+ "conceptual_breakthrough",
223
+ "Conceptual Breakthrough",
224
+ [
225
+ "Mathematical concept breakthroughs",
226
+ "Scientific paradigm shifts",
227
+ "Language structure insights",
228
+ "Artistic technique breakthroughs",
229
+ ],
230
+ "Facilitating 'aha!' moments, paradigm shifts in understanding, sudden insight into complex concepts.",
231
+ ),
232
+ (
233
+ "competency_development",
234
+ "Competency Development",
235
+ [
236
+ "Sustained learning processes",
237
+ "Professional skill development",
238
+ "Complex skill acquisition",
239
+ "Career-long competency building",
240
+ ],
241
+ "Long-term skill building, step-by-step mastery progression, comprehensive competency development.",
242
+ ),
243
+ (
244
+ "knowledge_spiral",
245
+ "Knowledge Spiral",
246
+ [
247
+ "Iterative knowledge deepening cycles",
248
+ "Research and scholarly inquiry",
249
+ "Progressive understanding development",
250
+ "Cumulative learning trajectories",
251
+ ],
252
+ "Building knowledge over time, spiral curriculum design, regenerative learning cycles.",
253
+ ),
254
+ (
255
+ "collaborative_learning",
256
+ "Collaborative Learning",
257
+ [
258
+ "Group project work",
259
+ "Peer tutoring",
260
+ "Learning communities",
261
+ "Collaborative knowledge construction",
262
+ ],
263
+ "Peer learning contexts, group work, social learning environments.",
264
+ ),
265
+ (
266
+ "practice_mastery",
267
+ "Practice Mastery",
268
+ [
269
+ "Deliberate practice routines",
270
+ "Skill refinement",
271
+ "Performance improvement cycles",
272
+ "Expertise development",
273
+ ],
274
+ "Focused practice sessions, skill refinement work, performance optimization.",
275
+ ),
276
+ ],
277
+ )
278
+
279
+ # Load organizational recipes
280
+ self._load_domain_recipes(
281
+ "organizational",
282
+ organizational_patterns,
283
+ [
284
+ (
285
+ "crisis_management",
286
+ "Crisis Management",
287
+ [
288
+ "Market disruption response",
289
+ "Leadership transition crisis",
290
+ "Operational emergency management",
291
+ "Reputation crisis containment",
292
+ ],
293
+ "Immediate organizational crisis, emergency institutional response, acute disruption requiring rapid coordination.",
294
+ ),
295
+ (
296
+ "team_formation",
297
+ "Team Formation",
298
+ [
299
+ "New team assembly",
300
+ "Cross-functional project initiation",
301
+ "Department reorganization",
302
+ "Merger integration",
303
+ ],
304
+ "Building new teams, establishing group coherence, creating high-performing collaborative units.",
305
+ ),
306
+ (
307
+ "strategic_planning",
308
+ "Strategic Planning",
309
+ [
310
+ "Comprehensive strategic planning",
311
+ "Vision development",
312
+ "Major transformation initiatives",
313
+ "Long-term change management",
314
+ ],
315
+ "Strategic planning processes, long-term organizational transformation, vision-driven institutional evolution.",
316
+ ),
317
+ (
318
+ "innovation_cycle",
319
+ "Innovation Cycle",
320
+ [
321
+ "Innovation programs",
322
+ "R&D project cycles",
323
+ "Product development sprints",
324
+ "Process innovation",
325
+ ],
326
+ "Innovation projects from ideation through implementation, systematic innovation programs.",
327
+ ),
328
+ (
329
+ "organizational_transformation",
330
+ "Organizational Transformation",
331
+ [
332
+ "Major restructuring",
333
+ "Culture transformation",
334
+ "Digital transformation",
335
+ "Business model evolution",
336
+ ],
337
+ "Comprehensive institutional change, transforming organizational culture and structure, fundamental business model shifts.",
338
+ ),
339
+ (
340
+ "change_resistance_resolution",
341
+ "Change Resistance Resolution",
342
+ [
343
+ "Overcoming resistance",
344
+ "Addressing opposition",
345
+ "Building change adoption",
346
+ "Managing transition conflicts",
347
+ ],
348
+ "High resistance to organizational change, need to transform opposition into engagement.",
349
+ ),
350
+ ],
351
+ )
352
+
353
+ # Load creative recipes
354
+ self._load_domain_recipes(
355
+ "creative",
356
+ creative_patterns,
357
+ [
358
+ (
359
+ "artistic_creation",
360
+ "Artistic Creation",
361
+ [
362
+ "Painting/sculpture creation",
363
+ "Musical composition",
364
+ "Novel/screenplay writing",
365
+ "Choreography",
366
+ "Architectural design",
367
+ ],
368
+ "Complete artistic projects, major creative works requiring full creative cycle from impulse through consolidation.",
369
+ ),
370
+ (
371
+ "design_thinking",
372
+ "Design Thinking",
373
+ [
374
+ "Product design",
375
+ "Service design",
376
+ "UX design",
377
+ "Human-centered innovation",
378
+ "Design sprints",
379
+ ],
380
+ "Design thinking processes, human-centered problem solving, empathy-driven innovation.",
381
+ ),
382
+ (
383
+ "innovation_cycle",
384
+ "Innovation Cycle",
385
+ [
386
+ "Continuous innovation programs",
387
+ "Product pipelines",
388
+ "Creative R&D cycles",
389
+ "Innovation portfolio management",
390
+ ],
391
+ "Sustained innovation work, regenerative innovation capability building, ongoing creative renewal.",
392
+ ),
393
+ (
394
+ "creative_flow",
395
+ "Creative Flow",
396
+ [
397
+ "Maintaining creative momentum",
398
+ "Flow state cultivation",
399
+ "Sustained artistic practice",
400
+ "Creative productivity optimization",
401
+ ],
402
+ "Developing sustained creative practice, maintaining flow states, building creative momentum.",
403
+ ),
404
+ (
405
+ "creative_block_resolution",
406
+ "Creative Block Resolution",
407
+ [
408
+ "Overcoming writer's block",
409
+ "Resolving stagnation",
410
+ "Reinvigorating work",
411
+ "Breaking through plateaus",
412
+ ],
413
+ "Stuck in creative process, experiencing creative block, need breakthrough to restart creative flow.",
414
+ ),
415
+ ],
416
+ )
417
+
418
+ def _load_domain_recipes(
419
+ self, domain: str, module: Any, recipe_specs: List[tuple]
420
+ ) -> None:
421
+ """Load recipes for a specific domain.
422
+
423
+ Parameters
424
+ ----------
425
+ domain : str
426
+ Domain name (therapeutic, educational, organizational, creative)
427
+ module : module
428
+ Python module containing pattern functions
429
+ recipe_specs : List[tuple]
430
+ List of (function_suffix, display_name, use_cases, when_to_use) tuples
431
+ """
432
+ if domain not in self._recipes:
433
+ self._recipes[domain] = {}
434
+
435
+ for spec in recipe_specs:
436
+ func_suffix, display_name, use_cases, when_to_use = spec
437
+
438
+ # Get sequence function
439
+ func_name = f"get_{func_suffix}_sequence"
440
+ if not hasattr(module, func_name):
441
+ continue
442
+
443
+ func = getattr(module, func_name)
444
+ sequence = func()
445
+
446
+ # Validate and get health metrics
447
+ result = validate_sequence_with_health(sequence)
448
+ if not result.passed:
449
+ continue
450
+
451
+ # Create recipe
452
+ recipe = CookbookRecipe(
453
+ name=display_name,
454
+ domain=domain,
455
+ sequence=sequence,
456
+ health_metrics=result.health_metrics,
457
+ use_cases=use_cases,
458
+ when_to_use=when_to_use,
459
+ structural_flow=[], # Could be extracted from docstring
460
+ key_insights=[], # Could be extracted from docstring
461
+ variations=[], # Future enhancement
462
+ pattern_type=result.health_metrics.dominant_pattern,
463
+ )
464
+
465
+ self._recipes[domain][func_suffix] = recipe
466
+
467
+ def get_recipe(self, domain: str, use_case: str) -> CookbookRecipe:
468
+ """Get a specific recipe by domain and use case identifier.
469
+
470
+ Parameters
471
+ ----------
472
+ domain : str
473
+ Domain name: "therapeutic", "educational", "organizational", "creative"
474
+ use_case : str
475
+ Use case identifier (e.g., "crisis_intervention", "team_formation")
476
+
477
+ Returns
478
+ -------
479
+ CookbookRecipe
480
+ The requested recipe with full context and metrics
481
+
482
+ Raises
483
+ ------
484
+ KeyError
485
+ If domain or use_case not found
486
+
487
+ Examples
488
+ --------
489
+ >>> cookbook = TNFRCookbook()
490
+ >>> recipe = cookbook.get_recipe("therapeutic", "crisis_intervention")
491
+ >>> print(recipe.name)
492
+ Crisis Intervention
493
+ """
494
+ if domain not in self._recipes:
495
+ raise KeyError(
496
+ f"Domain '{domain}' not found. Available: {list(self._recipes.keys())}"
497
+ )
498
+
499
+ if use_case not in self._recipes[domain]:
500
+ raise KeyError(
501
+ f"Use case '{use_case}' not found in '{domain}'. "
502
+ f"Available: {list(self._recipes[domain].keys())}"
503
+ )
504
+
505
+ return self._recipes[domain][use_case]
506
+
507
+ def list_recipes(
508
+ self,
509
+ domain: Optional[str] = None,
510
+ min_health: float = 0.0,
511
+ max_length: Optional[int] = None,
512
+ pattern_type: Optional[str] = None,
513
+ ) -> List[CookbookRecipe]:
514
+ """List recipes with optional filtering.
515
+
516
+ Parameters
517
+ ----------
518
+ domain : str, optional
519
+ Filter by domain (therapeutic, educational, organizational, creative)
520
+ min_health : float, default=0.0
521
+ Minimum health score threshold
522
+ max_length : int, optional
523
+ Maximum sequence length
524
+ pattern_type : str, optional
525
+ Filter by pattern type (activation, therapeutic, regenerative, etc.)
526
+
527
+ Returns
528
+ -------
529
+ List[CookbookRecipe]
530
+ Filtered list of recipes
531
+
532
+ Examples
533
+ --------
534
+ >>> cookbook = TNFRCookbook()
535
+ >>> # Get all high-quality therapeutic recipes
536
+ >>> recipes = cookbook.list_recipes(domain="therapeutic", min_health=0.80)
537
+ >>> [r.name for r in recipes]
538
+ ['Process Therapy', 'Regenerative Healing']
539
+ """
540
+ results = []
541
+
542
+ domains = [domain] if domain else list(self._recipes.keys())
543
+
544
+ for dom in domains:
545
+ if dom not in self._recipes:
546
+ continue
547
+
548
+ for recipe in self._recipes[dom].values():
549
+ # Apply filters
550
+ if recipe.health_metrics.overall_health < min_health:
551
+ continue
552
+
553
+ if max_length and len(recipe.sequence) > max_length:
554
+ continue
555
+
556
+ if pattern_type and recipe.pattern_type != pattern_type:
557
+ continue
558
+
559
+ results.append(recipe)
560
+
561
+ # Sort by health score descending
562
+ results.sort(key=lambda r: r.health_metrics.overall_health, reverse=True)
563
+
564
+ return results
565
+
566
+ def search_recipes(self, query: str) -> List[CookbookRecipe]:
567
+ """Search recipes by text query across names, use cases, and context.
568
+
569
+ Parameters
570
+ ----------
571
+ query : str
572
+ Search query string (case-insensitive)
573
+
574
+ Returns
575
+ -------
576
+ List[CookbookRecipe]
577
+ Recipes matching the query, sorted by relevance
578
+
579
+ Examples
580
+ --------
581
+ >>> cookbook = TNFRCookbook()
582
+ >>> results = cookbook.search_recipes("crisis")
583
+ >>> [r.name for r in results]
584
+ ['Crisis Intervention', 'Crisis Management']
585
+ """
586
+ query_lower = query.lower()
587
+ results = []
588
+
589
+ for domain_recipes in self._recipes.values():
590
+ for recipe in domain_recipes.values():
591
+ # Search in name
592
+ if query_lower in recipe.name.lower():
593
+ results.append((recipe, 3)) # High relevance
594
+ continue
595
+
596
+ # Search in use cases
597
+ if any(query_lower in uc.lower() for uc in recipe.use_cases):
598
+ results.append((recipe, 2)) # Medium relevance
599
+ continue
600
+
601
+ # Search in when_to_use
602
+ if query_lower in recipe.when_to_use.lower():
603
+ results.append((recipe, 1)) # Low relevance
604
+ continue
605
+
606
+ # Sort by relevance then health
607
+ results.sort(
608
+ key=lambda x: (x[1], x[0].health_metrics.overall_health), reverse=True
609
+ )
610
+
611
+ return [r[0] for r in results]
612
+
613
+ def recommend_recipe(
614
+ self,
615
+ context: str,
616
+ constraints: Optional[Dict[str, Any]] = None,
617
+ ) -> Optional[CookbookRecipe]:
618
+ """Recommend a recipe based on context description and constraints.
619
+
620
+ Uses keyword matching and constraint satisfaction to find the best
621
+ matching recipe for the described context.
622
+
623
+ Parameters
624
+ ----------
625
+ context : str
626
+ Description of the situation or need
627
+ constraints : Dict[str, Any], optional
628
+ Additional constraints:
629
+ - max_length: int - maximum sequence length
630
+ - min_health: float - minimum health score
631
+ - domain: str - restrict to specific domain
632
+ - prefer_pattern: str - preferred pattern type
633
+
634
+ Returns
635
+ -------
636
+ CookbookRecipe or None
637
+ Best matching recipe, or None if no good match found
638
+
639
+ Examples
640
+ --------
641
+ >>> cookbook = TNFRCookbook()
642
+ >>> recipe = cookbook.recommend_recipe(
643
+ ... context="Need to help team work together on new project",
644
+ ... constraints={"min_health": 0.80, "max_length": 10}
645
+ ... )
646
+ >>> recipe.name
647
+ 'Team Formation'
648
+ """
649
+ constraints = constraints or {}
650
+
651
+ # Start with all recipes matching constraints
652
+ candidates = self.list_recipes(
653
+ domain=constraints.get("domain"),
654
+ min_health=constraints.get("min_health", 0.75),
655
+ max_length=constraints.get("max_length"),
656
+ pattern_type=constraints.get("prefer_pattern"),
657
+ )
658
+
659
+ if not candidates:
660
+ return None
661
+
662
+ # Extract keywords from context
663
+ context_lower = context.lower()
664
+ keywords = set(context_lower.split())
665
+
666
+ # Score each candidate by keyword overlap
667
+ scored_candidates = []
668
+ for recipe in candidates:
669
+ score = 0
670
+
671
+ # Check name overlap
672
+ name_words = set(recipe.name.lower().split())
673
+ score += len(keywords & name_words) * 5
674
+
675
+ # Check use cases overlap
676
+ for use_case in recipe.use_cases:
677
+ use_case_words = set(use_case.lower().split())
678
+ score += len(keywords & use_case_words) * 3
679
+
680
+ # Check when_to_use overlap
681
+ when_words = set(recipe.when_to_use.lower().split())
682
+ score += len(keywords & when_words) * 2
683
+
684
+ # Boost by health score
685
+ score += recipe.health_metrics.overall_health * 10
686
+
687
+ scored_candidates.append((recipe, score))
688
+
689
+ if not scored_candidates:
690
+ return None
691
+
692
+ # Return highest scoring recipe
693
+ scored_candidates.sort(key=lambda x: x[1], reverse=True)
694
+ return scored_candidates[0][0]
695
+
696
+ def get_all_domains(self) -> List[str]:
697
+ """Get list of all available domains.
698
+
699
+ Returns
700
+ -------
701
+ List[str]
702
+ List of domain names
703
+ """
704
+ return list(self._recipes.keys())
705
+
706
+ def get_domain_summary(self, domain: str) -> Dict[str, Any]:
707
+ """Get summary statistics for a domain.
708
+
709
+ Parameters
710
+ ----------
711
+ domain : str
712
+ Domain name
713
+
714
+ Returns
715
+ -------
716
+ Dict[str, Any]
717
+ Summary with recipe count, average health, patterns, etc.
718
+ """
719
+ if domain not in self._recipes:
720
+ raise KeyError(f"Domain '{domain}' not found")
721
+
722
+ recipes = list(self._recipes[domain].values())
723
+
724
+ if not recipes:
725
+ return {
726
+ "domain": domain,
727
+ "recipe_count": 0,
728
+ "average_health": 0.0,
729
+ "health_range": (0.0, 0.0),
730
+ "patterns": [],
731
+ }
732
+
733
+ healths = [r.health_metrics.overall_health for r in recipes]
734
+ patterns = [r.pattern_type for r in recipes]
735
+
736
+ return {
737
+ "domain": domain,
738
+ "recipe_count": len(recipes),
739
+ "average_health": sum(healths) / len(healths),
740
+ "health_range": (min(healths), max(healths)),
741
+ "patterns": list(set(patterns)),
742
+ "recipes": [r.name for r in recipes],
743
+ }