@reicek/neataptic-ts 0.1.0

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.
Files changed (272) hide show
  1. package/.github/ISSUE_TEMPLATE/bug_report.md +33 -0
  2. package/.github/ISSUE_TEMPLATE/feature_request.md +27 -0
  3. package/.github/PULL_REQUEST_TEMPLATE.md +28 -0
  4. package/.github/workflows/ci.yml +41 -0
  5. package/.github/workflows/deploy-pages.yml +29 -0
  6. package/.github/workflows/manual_release_pipeline.yml +62 -0
  7. package/.github/workflows/publish.yml +85 -0
  8. package/.github/workflows/release_dispatch.yml +38 -0
  9. package/.travis.yml +5 -0
  10. package/CONTRIBUTING.md +92 -0
  11. package/LICENSE +24 -0
  12. package/ONNX_EXPORT.md +87 -0
  13. package/README.md +1173 -0
  14. package/RELEASE.md +54 -0
  15. package/dist-docs/package.json +1 -0
  16. package/dist-docs/scripts/generate-docs.d.ts +2 -0
  17. package/dist-docs/scripts/generate-docs.d.ts.map +1 -0
  18. package/dist-docs/scripts/generate-docs.js +536 -0
  19. package/dist-docs/scripts/generate-docs.js.map +1 -0
  20. package/dist-docs/scripts/render-docs-html.d.ts +2 -0
  21. package/dist-docs/scripts/render-docs-html.d.ts.map +1 -0
  22. package/dist-docs/scripts/render-docs-html.js +148 -0
  23. package/dist-docs/scripts/render-docs-html.js.map +1 -0
  24. package/docs/FOLDERS.md +14 -0
  25. package/docs/README.md +1173 -0
  26. package/docs/architecture/README.md +1391 -0
  27. package/docs/architecture/index.html +938 -0
  28. package/docs/architecture/network/README.md +1210 -0
  29. package/docs/architecture/network/index.html +908 -0
  30. package/docs/assets/ascii-maze.bundle.js +16542 -0
  31. package/docs/assets/ascii-maze.bundle.js.map +7 -0
  32. package/docs/index.html +1419 -0
  33. package/docs/methods/README.md +670 -0
  34. package/docs/methods/index.html +477 -0
  35. package/docs/multithreading/README.md +274 -0
  36. package/docs/multithreading/index.html +215 -0
  37. package/docs/multithreading/workers/README.md +23 -0
  38. package/docs/multithreading/workers/browser/README.md +39 -0
  39. package/docs/multithreading/workers/browser/index.html +70 -0
  40. package/docs/multithreading/workers/index.html +57 -0
  41. package/docs/multithreading/workers/node/README.md +33 -0
  42. package/docs/multithreading/workers/node/index.html +66 -0
  43. package/docs/neat/README.md +1284 -0
  44. package/docs/neat/index.html +906 -0
  45. package/docs/src/README.md +2659 -0
  46. package/docs/src/index.html +1579 -0
  47. package/jest.config.ts +32 -0
  48. package/package.json +99 -0
  49. package/plans/HyperMorphoNEAT.md +293 -0
  50. package/plans/ONNX_EXPORT_PLAN.md +46 -0
  51. package/scripts/generate-docs.ts +486 -0
  52. package/scripts/render-docs-html.ts +138 -0
  53. package/scripts/types.d.ts +2 -0
  54. package/src/README.md +2659 -0
  55. package/src/architecture/README.md +1391 -0
  56. package/src/architecture/activationArrayPool.ts +135 -0
  57. package/src/architecture/architect.ts +635 -0
  58. package/src/architecture/connection.ts +148 -0
  59. package/src/architecture/group.ts +406 -0
  60. package/src/architecture/layer.ts +804 -0
  61. package/src/architecture/network/README.md +1210 -0
  62. package/src/architecture/network/network.activate.ts +223 -0
  63. package/src/architecture/network/network.connect.ts +157 -0
  64. package/src/architecture/network/network.deterministic.ts +167 -0
  65. package/src/architecture/network/network.evolve.ts +426 -0
  66. package/src/architecture/network/network.gating.ts +186 -0
  67. package/src/architecture/network/network.genetic.ts +247 -0
  68. package/src/architecture/network/network.mutate.ts +624 -0
  69. package/src/architecture/network/network.onnx.ts +463 -0
  70. package/src/architecture/network/network.prune.ts +216 -0
  71. package/src/architecture/network/network.remove.ts +96 -0
  72. package/src/architecture/network/network.serialize.ts +309 -0
  73. package/src/architecture/network/network.slab.ts +262 -0
  74. package/src/architecture/network/network.standalone.ts +246 -0
  75. package/src/architecture/network/network.stats.ts +59 -0
  76. package/src/architecture/network/network.topology.ts +86 -0
  77. package/src/architecture/network/network.training.ts +1278 -0
  78. package/src/architecture/network.ts +1302 -0
  79. package/src/architecture/node.ts +1288 -0
  80. package/src/architecture/onnx.ts +3 -0
  81. package/src/config.ts +83 -0
  82. package/src/methods/README.md +670 -0
  83. package/src/methods/activation.ts +372 -0
  84. package/src/methods/connection.ts +31 -0
  85. package/src/methods/cost.ts +347 -0
  86. package/src/methods/crossover.ts +63 -0
  87. package/src/methods/gating.ts +43 -0
  88. package/src/methods/methods.ts +8 -0
  89. package/src/methods/mutation.ts +300 -0
  90. package/src/methods/rate.ts +257 -0
  91. package/src/methods/selection.ts +65 -0
  92. package/src/multithreading/README.md +274 -0
  93. package/src/multithreading/multi.ts +339 -0
  94. package/src/multithreading/workers/README.md +23 -0
  95. package/src/multithreading/workers/browser/README.md +39 -0
  96. package/src/multithreading/workers/browser/testworker.ts +99 -0
  97. package/src/multithreading/workers/node/README.md +33 -0
  98. package/src/multithreading/workers/node/testworker.ts +72 -0
  99. package/src/multithreading/workers/node/worker.ts +70 -0
  100. package/src/multithreading/workers/workers.ts +22 -0
  101. package/src/neat/README.md +1284 -0
  102. package/src/neat/neat.adaptive.ts +544 -0
  103. package/src/neat/neat.compat.ts +164 -0
  104. package/src/neat/neat.constants.ts +20 -0
  105. package/src/neat/neat.diversity.ts +217 -0
  106. package/src/neat/neat.evaluate.ts +328 -0
  107. package/src/neat/neat.evolve.ts +1026 -0
  108. package/src/neat/neat.export.ts +249 -0
  109. package/src/neat/neat.helpers.ts +235 -0
  110. package/src/neat/neat.lineage.ts +220 -0
  111. package/src/neat/neat.multiobjective.ts +260 -0
  112. package/src/neat/neat.mutation.ts +718 -0
  113. package/src/neat/neat.objectives.ts +157 -0
  114. package/src/neat/neat.pruning.ts +190 -0
  115. package/src/neat/neat.selection.ts +269 -0
  116. package/src/neat/neat.speciation.ts +460 -0
  117. package/src/neat/neat.species.ts +151 -0
  118. package/src/neat/neat.telemetry.exports.ts +469 -0
  119. package/src/neat/neat.telemetry.ts +933 -0
  120. package/src/neat/neat.types.ts +275 -0
  121. package/src/neat.ts +1042 -0
  122. package/src/neataptic.ts +10 -0
  123. package/test/architecture/activationArrayPool.capacity.test.ts +19 -0
  124. package/test/architecture/activationArrayPool.test.ts +46 -0
  125. package/test/architecture/connection.test.ts +290 -0
  126. package/test/architecture/group.test.ts +950 -0
  127. package/test/architecture/layer.test.ts +1535 -0
  128. package/test/architecture/network.pruning.test.ts +65 -0
  129. package/test/architecture/node.test.ts +1602 -0
  130. package/test/examples/asciiMaze/asciiMaze.e2e.test.ts +499 -0
  131. package/test/examples/asciiMaze/asciiMaze.ts +41 -0
  132. package/test/examples/asciiMaze/browser-entry.ts +164 -0
  133. package/test/examples/asciiMaze/browserLogger.ts +221 -0
  134. package/test/examples/asciiMaze/browserTerminalUtility.ts +48 -0
  135. package/test/examples/asciiMaze/colors.ts +119 -0
  136. package/test/examples/asciiMaze/dashboardManager.ts +968 -0
  137. package/test/examples/asciiMaze/evolutionEngine.ts +1248 -0
  138. package/test/examples/asciiMaze/fitness.ts +136 -0
  139. package/test/examples/asciiMaze/index.html +128 -0
  140. package/test/examples/asciiMaze/index.ts +26 -0
  141. package/test/examples/asciiMaze/interfaces.ts +235 -0
  142. package/test/examples/asciiMaze/mazeMovement.ts +996 -0
  143. package/test/examples/asciiMaze/mazeUtils.ts +278 -0
  144. package/test/examples/asciiMaze/mazeVision.ts +402 -0
  145. package/test/examples/asciiMaze/mazeVisualization.ts +585 -0
  146. package/test/examples/asciiMaze/mazes.ts +245 -0
  147. package/test/examples/asciiMaze/networkRefinement.ts +76 -0
  148. package/test/examples/asciiMaze/networkVisualization.ts +901 -0
  149. package/test/examples/asciiMaze/terminalUtility.ts +73 -0
  150. package/test/methods/activation.test.ts +1142 -0
  151. package/test/methods/connection.test.ts +146 -0
  152. package/test/methods/cost.test.ts +1123 -0
  153. package/test/methods/crossover.test.ts +202 -0
  154. package/test/methods/gating.test.ts +144 -0
  155. package/test/methods/mutation.test.ts +451 -0
  156. package/test/methods/optimizers.advanced.test.ts +80 -0
  157. package/test/methods/optimizers.behavior.test.ts +105 -0
  158. package/test/methods/optimizers.formula.test.ts +89 -0
  159. package/test/methods/rate.cosineWarmRestarts.test.ts +44 -0
  160. package/test/methods/rate.linearWarmupDecay.test.ts +41 -0
  161. package/test/methods/rate.reduceOnPlateau.test.ts +45 -0
  162. package/test/methods/rate.test.ts +684 -0
  163. package/test/methods/selection.test.ts +245 -0
  164. package/test/multithreading/activations.functions.test.ts +54 -0
  165. package/test/multithreading/multi.test.ts +290 -0
  166. package/test/multithreading/worker.node.process.test.ts +39 -0
  167. package/test/multithreading/workers.coverage.test.ts +36 -0
  168. package/test/multithreading/workers.dynamic.import.test.ts +8 -0
  169. package/test/neat/neat.adaptive.complexityBudget.test.ts +34 -0
  170. package/test/neat/neat.adaptive.criterion.complexity.test.ts +50 -0
  171. package/test/neat/neat.adaptive.mutation.strategy.test.ts +37 -0
  172. package/test/neat/neat.adaptive.operator.decay.test.ts +31 -0
  173. package/test/neat/neat.adaptive.phasedComplexity.test.ts +25 -0
  174. package/test/neat/neat.adaptive.pruning.test.ts +25 -0
  175. package/test/neat/neat.adaptive.targetSpecies.test.ts +43 -0
  176. package/test/neat/neat.additional.coverage.test.ts +126 -0
  177. package/test/neat/neat.advanced.enhancements.test.ts +85 -0
  178. package/test/neat/neat.advanced.test.ts +589 -0
  179. package/test/neat/neat.diversity.autocompat.test.ts +47 -0
  180. package/test/neat/neat.diversity.metrics.test.ts +21 -0
  181. package/test/neat/neat.diversity.stats.test.ts +44 -0
  182. package/test/neat/neat.enhancements.test.ts +79 -0
  183. package/test/neat/neat.entropy.ancestorAdaptive.test.ts +133 -0
  184. package/test/neat/neat.entropy.compat.csv.test.ts +108 -0
  185. package/test/neat/neat.evolution.pruning.test.ts +39 -0
  186. package/test/neat/neat.fastmode.autotune.test.ts +42 -0
  187. package/test/neat/neat.innovation.test.ts +134 -0
  188. package/test/neat/neat.lineage.antibreeding.test.ts +35 -0
  189. package/test/neat/neat.lineage.entropy.test.ts +56 -0
  190. package/test/neat/neat.lineage.inbreeding.test.ts +49 -0
  191. package/test/neat/neat.lineage.pressure.test.ts +29 -0
  192. package/test/neat/neat.multiobjective.adaptive.test.ts +57 -0
  193. package/test/neat/neat.multiobjective.dynamic.schedule.test.ts +46 -0
  194. package/test/neat/neat.multiobjective.dynamic.test.ts +31 -0
  195. package/test/neat/neat.multiobjective.fastsort.delegation.test.ts +51 -0
  196. package/test/neat/neat.multiobjective.prune.test.ts +39 -0
  197. package/test/neat/neat.multiobjective.test.ts +21 -0
  198. package/test/neat/neat.mutation.undefined.pool.test.ts +24 -0
  199. package/test/neat/neat.objective.events.test.ts +26 -0
  200. package/test/neat/neat.objective.importance.test.ts +21 -0
  201. package/test/neat/neat.objective.lifetimes.test.ts +33 -0
  202. package/test/neat/neat.offspring.allocation.test.ts +22 -0
  203. package/test/neat/neat.operator.bandit.test.ts +17 -0
  204. package/test/neat/neat.operator.phases.test.ts +38 -0
  205. package/test/neat/neat.pruneInactive.behavior.test.ts +54 -0
  206. package/test/neat/neat.reenable.adaptation.test.ts +18 -0
  207. package/test/neat/neat.rng.state.test.ts +22 -0
  208. package/test/neat/neat.spawn.add.test.ts +123 -0
  209. package/test/neat/neat.speciation.test.ts +96 -0
  210. package/test/neat/neat.species.allocation.telemetry.test.ts +26 -0
  211. package/test/neat/neat.species.history.csv.test.ts +24 -0
  212. package/test/neat/neat.telemetry.advanced.test.ts +226 -0
  213. package/test/neat/neat.telemetry.csv.lineage.test.ts +19 -0
  214. package/test/neat/neat.telemetry.parity.test.ts +42 -0
  215. package/test/neat/neat.telemetry.stream.test.ts +19 -0
  216. package/test/neat/neat.telemetry.test.ts +16 -0
  217. package/test/neat/neat.test.ts +422 -0
  218. package/test/neat/neat.utilities.test.ts +44 -0
  219. package/test/network/__suppress_console.ts +9 -0
  220. package/test/network/acyclic.topoorder.test.ts +17 -0
  221. package/test/network/checkpoint.metricshook.test.ts +36 -0
  222. package/test/network/error.handling.test.ts +581 -0
  223. package/test/network/evolution.test.ts +285 -0
  224. package/test/network/genetic.test.ts +208 -0
  225. package/test/network/learning.capability.test.ts +244 -0
  226. package/test/network/mutation.effects.test.ts +492 -0
  227. package/test/network/network.activate.test.ts +115 -0
  228. package/test/network/network.activateBatch.test.ts +30 -0
  229. package/test/network/network.deterministic.test.ts +64 -0
  230. package/test/network/network.evolve.branches.test.ts +75 -0
  231. package/test/network/network.evolve.multithread.branches.test.ts +83 -0
  232. package/test/network/network.evolve.test.ts +100 -0
  233. package/test/network/network.gating.removal.test.ts +93 -0
  234. package/test/network/network.mutate.additional.test.ts +145 -0
  235. package/test/network/network.mutate.edgecases.test.ts +101 -0
  236. package/test/network/network.mutate.test.ts +101 -0
  237. package/test/network/network.prune.earlyexit.test.ts +38 -0
  238. package/test/network/network.remove.errors.test.ts +45 -0
  239. package/test/network/network.slab.fallbacks.test.ts +22 -0
  240. package/test/network/network.stats.test.ts +45 -0
  241. package/test/network/network.training.advanced.test.ts +149 -0
  242. package/test/network/network.training.basic.test.ts +228 -0
  243. package/test/network/network.training.helpers.test.ts +183 -0
  244. package/test/network/onnx.export.test.ts +310 -0
  245. package/test/network/onnx.import.test.ts +129 -0
  246. package/test/network/pruning.topology.test.ts +282 -0
  247. package/test/network/regularization.determinism.test.ts +83 -0
  248. package/test/network/regularization.dropconnect.test.ts +17 -0
  249. package/test/network/regularization.dropconnect.validation.test.ts +18 -0
  250. package/test/network/regularization.stochasticdepth.test.ts +27 -0
  251. package/test/network/regularization.test.ts +843 -0
  252. package/test/network/regularization.weightnoise.test.ts +30 -0
  253. package/test/network/setupTests.ts +2 -0
  254. package/test/network/standalone.test.ts +332 -0
  255. package/test/network/structure.serialization.test.ts +660 -0
  256. package/test/training/training.determinism.mixed-precision.test.ts +134 -0
  257. package/test/training/training.earlystopping.test.ts +91 -0
  258. package/test/training/training.edge-cases.test.ts +91 -0
  259. package/test/training/training.extensions.test.ts +47 -0
  260. package/test/training/training.gradient.features.test.ts +110 -0
  261. package/test/training/training.gradient.refinements.test.ts +170 -0
  262. package/test/training/training.gradient.separate-bias.test.ts +41 -0
  263. package/test/training/training.optimizer.test.ts +48 -0
  264. package/test/training/training.plateau.smoothing.test.ts +58 -0
  265. package/test/training/training.smoothing.types.test.ts +174 -0
  266. package/test/training/training.train.options.coverage.test.ts +52 -0
  267. package/test/utils/console-helper.ts +76 -0
  268. package/test/utils/jest-setup.ts +60 -0
  269. package/test/utils/test-helpers.ts +175 -0
  270. package/tsconfig.docs.json +12 -0
  271. package/tsconfig.json +21 -0
  272. package/webpack.config.js +49 -0
@@ -0,0 +1,1284 @@
1
+ # neat
2
+
3
+ ## neat/neat.adaptive.ts
4
+
5
+ ### applyAdaptiveMutation
6
+
7
+ `() => void`
8
+
9
+ Self-adaptive per-genome mutation tuning.
10
+
11
+ This function implements several strategies to adjust each genome's
12
+ internal mutation rate (`g._mutRate`) and optionally its mutation
13
+ amount (`g._mutAmount`) over time. Strategies include:
14
+ - `twoTier`: push top and bottom halves in opposite directions to
15
+ create exploration/exploitation balance.
16
+ - `exploreLow`: preferentially increase mutation for lower-scoring
17
+ genomes to promote exploration.
18
+ - `anneal`: gradually reduce mutation deltas over time.
19
+
20
+ The method reads `this.options.adaptiveMutation` for configuration
21
+ and mutates genomes in-place.
22
+
23
+ ### applyAncestorUniqAdaptive
24
+
25
+ `() => void`
26
+
27
+ Adaptive adjustments based on ancestor uniqueness telemetry.
28
+
29
+ This helper inspects the most recent telemetry lineage block (if
30
+ available) for an `ancestorUniq` metric indicating how unique
31
+ ancestry is across the population. If ancestry uniqueness drifts
32
+ outside configured thresholds, the method will adjust either the
33
+ multi-objective dominance epsilon (if `mode === 'epsilon'`) or the
34
+ lineage pressure strength (if `mode === 'lineagePressure'`).
35
+
36
+ Typical usage: keep population lineage diversity within a healthy
37
+ band. Low ancestor uniqueness means too many genomes share ancestors
38
+ (risking premature convergence); high uniqueness might indicate
39
+ excessive divergence.
40
+
41
+ ### applyComplexityBudget
42
+
43
+ `() => void`
44
+
45
+ Apply complexity budget scheduling to the evolving population.
46
+
47
+ This routine updates `this.options.maxNodes` (and optionally
48
+ `this.options.maxConns`) according to a configured complexity budget
49
+ strategy. Two modes are supported:
50
+
51
+ - `adaptive`: reacts to recent population improvement (or stagnation)
52
+ by increasing or decreasing the current complexity cap using
53
+ heuristics such as slope (linear trend) of recent best scores,
54
+ novelty, and configured increase/stagnation factors.
55
+ - `linear` (default behaviour when not `adaptive`): linearly ramps
56
+ the budget from `maxNodesStart` to `maxNodesEnd` over a horizon.
57
+
58
+ Internal state used/maintained on the `this` object:
59
+ - `_cbHistory`: rolling window of best scores used to compute trends.
60
+ - `_cbMaxNodes`: current complexity budget for nodes.
61
+ - `_cbMaxConns`: current complexity budget for connections (optional).
62
+
63
+ The method is intended to be called on the NEAT engine instance with
64
+ `this` bound appropriately (i.e. a NeatapticTS `Neat`-like object).
65
+
66
+ Returns: Updates `this.options.maxNodes` and possibly
67
+ `this.options.maxConns` in-place; no value is returned.
68
+
69
+ ### applyMinimalCriterionAdaptive
70
+
71
+ `() => void`
72
+
73
+ Apply adaptive minimal criterion (MC) acceptance.
74
+
75
+ This method maintains an MC threshold used to decide whether an
76
+ individual genome is considered acceptable. It adapts the threshold
77
+ based on the proportion of the population that meets the current
78
+ threshold, trying to converge to a target acceptance rate.
79
+
80
+ Behavior summary:
81
+ - Initializes `_mcThreshold` from configuration if undefined.
82
+ - Computes the proportion of genomes with score >= threshold.
83
+ - Adjusts threshold multiplicatively by `adjustRate` to move the
84
+ observed proportion towards `targetAcceptance`.
85
+ - Sets `g.score = 0` for genomes that fall below the final threshold
86
+ — effectively rejecting them from selection.
87
+
88
+ ### applyOperatorAdaptation
89
+
90
+ `() => void`
91
+
92
+ Decay operator adaptation statistics (success/attempt counters).
93
+
94
+ Many adaptive operator-selection schemes keep running tallies of how
95
+ successful each operator has been. This helper applies an exponential
96
+ moving-average style decay to those counters so older outcomes
97
+ progressively matter less.
98
+
99
+ The `_operatorStats` map on `this` is expected to contain values of
100
+ the shape `{ success: number, attempts: number }` keyed by operator
101
+ id/name.
102
+
103
+ ### applyPhasedComplexity
104
+
105
+ `() => void`
106
+
107
+ Toggle phased complexity mode between 'complexify' and 'simplify'.
108
+
109
+ Phased complexity supports alternating periods where the algorithm
110
+ is encouraged to grow (complexify) or shrink (simplify) network
111
+ structures. This can help escape local minima or reduce bloat.
112
+
113
+ The current phase and its start generation are stored on `this` as
114
+ `_phase` and `_phaseStartGeneration` so the state persists across
115
+ generations.
116
+
117
+ Returns: Mutates `this._phase` and `this._phaseStartGeneration`.
118
+
119
+ ## neat/neat.compat.ts
120
+
121
+ ### _compatibilityDistance
122
+
123
+ `(genomeA: any, genomeB: any) => number`
124
+
125
+ Compute the NEAT compatibility distance between two genomes (networks).
126
+
127
+ The compatibility distance is used for speciation in NEAT. It combines the
128
+ number of excess and disjoint genes with the average weight difference of
129
+ matching genes. A generation-scoped cache is used to avoid recomputing the
130
+ same pair distances repeatedly within a generation.
131
+
132
+ Formula:
133
+ distance = (c1 * excess + c2 * disjoint) / N + c3 * avgWeightDiff
134
+ where N = max(number of genes in genomeA, number of genes in genomeB)
135
+ and c1,c2,c3 are coefficients provided in `this.options`.
136
+
137
+ Example:
138
+ const d = _compatibilityDistance.call(neatInstance, genomeA, genomeB);
139
+ if (d < neatInstance.options.compatibilityThreshold) { // same species }
140
+
141
+ Parameters:
142
+ - `this` - - The NEAT instance / context which holds generation, options, and caches.
143
+ - `genomeA` - - First genome (network) to compare. Expected to expose `_id` and `connections`.
144
+ - `genomeB` - - Second genome (network) to compare. Expected to expose `_id` and `connections`.
145
+
146
+ Returns: A numeric compatibility distance; lower means more similar.
147
+
148
+ ### _fallbackInnov
149
+
150
+ `(connection: any) => number`
151
+
152
+ Generate a deterministic fallback innovation id for a connection when the
153
+ connection does not provide an explicit innovation number.
154
+
155
+ This function encodes the (from.index, to.index) pair into a single number
156
+ by multiplying the `from` index by a large base and adding the `to` index.
157
+ The large base reduces collisions between different pairs and keeps the id
158
+ stable and deterministic across runs. It is intended as a fallback only —
159
+ explicit innovation numbers (when present) should be preferred.
160
+
161
+ Example:
162
+ const conn = { from: { index: 2 }, to: { index: 5 } };
163
+ const id = _fallbackInnov.call(neatContext, conn); // 200005
164
+
165
+ Notes:
166
+ - Not globally guaranteed unique, but deterministic for the same indices.
167
+ - Useful during compatibility checks when some connections are missing innovation ids.
168
+
169
+ Parameters:
170
+ - `this` - - The NEAT instance / context (kept for symmetry with other helpers).
171
+ - `connection` - - Connection object expected to contain `from.index` and `to.index`.
172
+
173
+ Returns: A numeric innovation id derived from the (from, to) index pair.
174
+
175
+ ## neat/neat.constants.ts
176
+
177
+ ### EPSILON
178
+
179
+ ### EXTRA_CONNECTION_PROBABILITY
180
+
181
+ ### NORM_EPSILON
182
+
183
+ ### PROB_EPSILON
184
+
185
+ ## neat/neat.diversity.ts
186
+
187
+ ### arrayMean
188
+
189
+ `(values: number[]) => number`
190
+
191
+ Compute the arithmetic mean of a numeric array. Returns 0 for empty arrays.
192
+ Extracted as a helper so it can be documented/tested independently.
193
+
194
+ ### arrayVariance
195
+
196
+ `(values: number[]) => number`
197
+
198
+ Compute the variance (population variance) of a numeric array.
199
+ Returns 0 for empty arrays. Uses arrayMean internally.
200
+
201
+ ### CompatComputer
202
+
203
+ Minimal interface that provides a compatibility distance function.
204
+ Implementors should expose a compatible signature with legacy NEAT code.
205
+
206
+ ### computeDiversityStats
207
+
208
+ `(population: any[], compatibilityComputer: CompatComputer) => import("D:/code-practice/NeatapticTS/src/neat/neat.diversity").DiversityStats | undefined`
209
+
210
+ Compute diversity statistics for a NEAT population.
211
+ This is a pure helper used by reporting and diagnostics. It intentionally
212
+ samples pairwise computations to keep cost bounded for large populations.
213
+
214
+ Notes for documentation:
215
+ - Lineage metrics rely on genomes exposing a numeric `_depth` property.
216
+ - Compatibility distances are computed via the provided compatComputer
217
+ which mirrors legacy code and may use historical marker logic.
218
+
219
+ Parameters:
220
+ - `population` - - array of genome-like objects (nodes, connections, optional _depth)
221
+ - `compatibilityComputer` - - object exposing _compatibilityDistance(a,b)
222
+
223
+ Returns: DiversityStats object with all computed aggregates, or undefined if input empty
224
+
225
+ ### DiversityStats
226
+
227
+ Diversity statistics returned by computeDiversityStats.
228
+ Each field represents an aggregate metric for a NEAT population.
229
+
230
+ ### structuralEntropy
231
+
232
+ `(graph: import("D:/code-practice/NeatapticTS/src/architecture/network").default) => number`
233
+
234
+ const JSDoc short descriptions above each constant
235
+
236
+ ## neat/neat.evaluate.ts
237
+
238
+ ### evaluate
239
+
240
+ `() => Promise<void>`
241
+
242
+ Evaluate the population or population-wide fitness delegate.
243
+
244
+ This function mirrors the legacy `evaluate` behaviour used by NeatapticTS
245
+ but adds documentation and clearer local variable names for readability.
246
+
247
+ Top-level responsibilities (method steps descriptions):
248
+ 1) Run fitness either on each genome or once for the population depending
249
+ on `options.fitnessPopulation`.
250
+ 2) Optionally clear genome internal state before evaluation when
251
+ `options.clear` is set.
252
+ 3) After scoring, apply optional novelty blending using a user-supplied
253
+ descriptor function. Novelty is blended into scores using a blend
254
+ factor and may be archived.
255
+ 4) Apply several adaptive tuning behaviors (entropy-sharing, compatibility
256
+ threshold tuning, auto-distance coefficient tuning) guarded by options.
257
+ 5) Trigger light-weight speciation when speciation-related controller
258
+ options are enabled so tests that only call evaluate still exercise
259
+ threshold tuning.
260
+
261
+ Example usage:
262
+ // await evaluate.call(controller); // where controller has `population`, `fitness` etc.
263
+
264
+ Returns: Promise<void> resolves after evaluation and adaptive updates complete.
265
+
266
+ ## neat/neat.evolve.ts
267
+
268
+ ### evolve
269
+
270
+ `() => Promise<import("D:/code-practice/NeatapticTS/src/architecture/network").default>`
271
+
272
+ Run a single evolution step for this NEAT population.
273
+
274
+ This method performs a full generation update: evaluation (if needed),
275
+ adaptive hooks, speciation and fitness sharing, multi-objective
276
+ processing, elitism/provenance, offspring allocation (within or without
277
+ species), mutation, pruning, and telemetry recording. It mutates the
278
+ controller state (`this.population`, `this.generation`, and telemetry
279
+ caches) and returns a copy of the best discovered `Network` for the
280
+ generation.
281
+
282
+ Important side-effects:
283
+ - Replaces `this.population` with the newly constructed generation.
284
+ - Increments `this.generation`.
285
+ - May register or remove dynamic objectives via adaptive controllers.
286
+
287
+ Example:
288
+ // assuming `neat` is an instance with configured population/options
289
+ await neat.evolve();
290
+ console.log('generation:', neat.generation);
291
+
292
+ Returns: a deep-cloned Network representing the best genome
293
+ in the previous generation (useful for evaluation)
294
+
295
+ ## neat/neat.export.ts
296
+
297
+ ### exportPopulation
298
+
299
+ `() => import("D:/code-practice/NeatapticTS/src/neat/neat.export").GenomeJSON[]`
300
+
301
+ Export the current population (array of genomes) into plain JSON objects.
302
+ Each genome is converted via its `toJSON()` method. You can persist this
303
+ result (e.g. to disk, a database, or localStorage) and later rehydrate it
304
+ with {@link importPopulation}.
305
+
306
+ Why export population only? Sometimes you want to snapshot *just* the set of
307
+ candidate solutions (e.g. for ensemble evaluation) without freezing the
308
+ innovation counters or hyper‑parameters.
309
+
310
+ Example:
311
+ ```ts
312
+ // Assuming `neat` is an instance exposing this helper
313
+ const popSnapshot = neat.exportPopulation();
314
+ fs.writeFileSync('population.json', JSON.stringify(popSnapshot, null, 2));
315
+ ```
316
+
317
+ Returns: Array of genome JSON objects.
318
+
319
+ ### exportState
320
+
321
+ `() => import("D:/code-practice/NeatapticTS/src/neat/neat.export").NeatStateJSON`
322
+
323
+ Convenience helper that returns a full evolutionary snapshot: both NEAT meta
324
+ information and the serialized population array. Use this when you want a
325
+ truly *pause‑and‑resume* capability including innovation bookkeeping.
326
+
327
+ Example:
328
+ ```ts
329
+ const state = neat.exportState();
330
+ fs.writeFileSync('state.json', JSON.stringify(state));
331
+ // ...later / elsewhere...
332
+ const raw = JSON.parse(fs.readFileSync('state.json','utf8')) as NeatStateJSON;
333
+ const neat2 = Neat.importState(raw, fitnessFn); // identical evolutionary context
334
+ ```
335
+
336
+ ### fromJSONImpl
337
+
338
+ `(neatJSON: import("D:/code-practice/NeatapticTS/src/neat/neat.export").NeatMetaJSON, fitnessFunction: (network: any) => number) => any`
339
+
340
+ Static-style implementation that rehydrates a NEAT instance from previously
341
+ exported meta JSON produced by {@link toJSONImpl}. This does *not* restore a
342
+ population; callers typically follow up with `importPopulation` or use
343
+ {@link importStateImpl} for a complete restore.
344
+
345
+ Example:
346
+ ```ts
347
+ const meta: NeatMetaJSON = JSON.parse(fs.readFileSync('neat-meta.json','utf8'));
348
+ const neat = Neat.fromJSONImpl(meta, fitnessFn); // empty population, same innovations
349
+ neat.importPopulation(popSnapshot); // optional
350
+ ```
351
+
352
+ Parameters:
353
+ - `neatJSON` - Serialized meta (no population).
354
+ - `fitnessFunction` - Fitness callback used to construct the new instance.
355
+
356
+ Returns: Fresh NEAT instance with restored innovation history.
357
+
358
+ ### GenomeJSON
359
+
360
+ JSON representation of an individual genome (network). The concrete shape is
361
+ produced by `Network#toJSON()` and re‑hydrated via `Network.fromJSON()`. We use
362
+ an open record signature here because the network architecture may evolve with
363
+ plugins / future features (e.g. CPPNs, substrate metadata, ONNX export tags).
364
+
365
+ ### importPopulation
366
+
367
+ `(populationJSON: import("D:/code-practice/NeatapticTS/src/neat/neat.export").GenomeJSON[]) => void`
368
+
369
+ Import (replace) the current population from an array of serialized genomes.
370
+ This does not touch NEAT meta state (generation, innovations, etc.)—only the
371
+ population array and implied `popsize` are updated.
372
+
373
+ Example:
374
+ ```ts
375
+ const populationData: GenomeJSON[] = JSON.parse(fs.readFileSync('population.json','utf8'));
376
+ neat.importPopulation(populationData); // population replaced
377
+ neat.evolve(); // continue evolving with new starting genomes
378
+ ```
379
+
380
+ Edge cases handled:
381
+ - Empty array => becomes an empty population (popsize=0).
382
+ - Malformed entries will throw if `Network.fromJSON` rejects them.
383
+
384
+ Parameters:
385
+ - `populationJSON` - Array of serialized genome objects.
386
+
387
+ ### importStateImpl
388
+
389
+ `(stateBundle: import("D:/code-practice/NeatapticTS/src/neat/neat.export").NeatStateJSON, fitnessFunction: (network: any) => number) => any`
390
+
391
+ Static-style helper that rehydrates a full evolutionary state previously
392
+ produced by {@link exportState}. Invoke this with the NEAT *class* (not an
393
+ instance) bound as `this`, e.g. `Neat.importStateImpl(bundle, fitnessFn)`.
394
+ It constructs a new NEAT instance using the meta data, then imports the
395
+ population (if present).
396
+
397
+ Safety & validation:
398
+ - Throws if the bundle is not an object.
399
+ - Silently skips population import if `population` is missing or not an array.
400
+
401
+ Example:
402
+ ```ts
403
+ const bundle: NeatStateJSON = JSON.parse(fs.readFileSync('state.json','utf8'));
404
+ const neat = Neat.importStateImpl(bundle, fitnessFn);
405
+ neat.evolve();
406
+ ```
407
+
408
+ Parameters:
409
+ - `stateBundle` - Full state bundle from {@link exportState} .
410
+ *
411
+ - `fitnessFunction` - Fitness evaluation callback used for new instance.
412
+
413
+ Returns: Rehydrated NEAT instance ready to continue evolving.
414
+
415
+ ### NeatMetaJSON
416
+
417
+ Serialized meta information describing a NEAT run, excluding the concrete
418
+ population genomes. This allows you to persist & resume experiment context
419
+ (innovation history, current generation, IO sizes, hyper‑parameters) without
420
+ committing to a particular population snapshot.
421
+
422
+ ### NeatStateJSON
423
+
424
+ Top‑level bundle containing both NEAT meta information and the full array of
425
+ serialized genomes (population). This is what you get from `exportState()` and
426
+ feed into `importStateImpl()` to resume exactly where you left off.
427
+
428
+ ### toJSONImpl
429
+
430
+ `() => import("D:/code-practice/NeatapticTS/src/neat/neat.export").NeatMetaJSON`
431
+
432
+ Serialize NEAT meta (excluding the mutable population) for persistence of
433
+ innovation history and experiment configuration. This is sufficient to
434
+ recreate a *blank* NEAT run at the same evolutionary generation with the
435
+ same innovation counters, enabling deterministic continuation when combined
436
+ later with a saved population.
437
+
438
+ Example:
439
+ ```ts
440
+ const meta = neat.toJSONImpl();
441
+ fs.writeFileSync('neat-meta.json', JSON.stringify(meta));
442
+ // ... later ...
443
+ const metaLoaded = JSON.parse(fs.readFileSync('neat-meta.json','utf8')) as NeatMetaJSON;
444
+ const neat2 = Neat.fromJSONImpl(metaLoaded, fitnessFn); // empty population
445
+ ```
446
+
447
+ ## neat/neat.helpers.ts
448
+
449
+ ### addGenome
450
+
451
+ `(genome: any, parents: number[] | undefined) => void`
452
+
453
+ Register an externally constructed genome (e.g., deserialized, custom‑built,
454
+ or imported from another run) into the active population. Ensures lineage
455
+ metadata and structural invariants are consistent with internally spawned
456
+ genomes.
457
+
458
+ Defensive design: If invariant enforcement fails, the genome is still added
459
+ (best effort) so experiments remain reproducible and do not abort mid‑run.
460
+ Caller can optionally inspect or prune later during evaluation.
461
+
462
+ Parameters:
463
+ - `this` - Bound NEAT instance.
464
+ - `genome` - Genome / network object to insert. Mutated in place to add
465
+ internal metadata fields (`_id`, `_parents`, `_depth`, `_reenableProb`).
466
+ - `parents` - Optional explicit list of parent genome IDs (e.g., 2 parents
467
+ for crossover). If omitted, lineage metadata is left empty.
468
+
469
+ ### createPool
470
+
471
+ `(seedNetwork: any) => void`
472
+
473
+ Create (or reset) the initial population pool for a NEAT run.
474
+
475
+ If a `seedNetwork` is supplied, every genome is a structural + weight clone
476
+ of that seed. This is useful for transfer learning or continuing evolution
477
+ from a known good architecture. When omitted, brand‑new minimal networks are
478
+ synthesized using the configured input/output sizes (and optional minimum
479
+ hidden layer size).
480
+
481
+ Design notes:
482
+ - Population size is derived from `options.popsize` (default 50).
483
+ - Each genome gets a unique sequential `_id` for reproducible lineage.
484
+ - When lineage tracking is enabled (`_lineageEnabled`), parent & depth fields
485
+ are initialized for later analytics.
486
+ - Structural invariant checks are best effort. A single failure should not
487
+ prevent other genomes from being created, hence broad try/catch blocks.
488
+
489
+ Parameters:
490
+ - `this` - Bound NEAT instance.
491
+ - `seedNetwork` - Optional prototype network to clone for every initial genome.
492
+
493
+ ### spawnFromParent
494
+
495
+ `(parentGenome: any, mutateCount: number) => any`
496
+
497
+ Helper utilities that augment the core NEAT (NeuroEvolution of Augmenting Topologies)
498
+ implementation. These functions are kept separate from the main class so they can
499
+ be tree‑shaken when unused and independently documented for educational purposes.
500
+
501
+ The helpers focus on three core lifecycle operations:
502
+ 1. Spawning children from an existing parent genome with mutation ("sexual" reproduction not handled here).
503
+ 2. Registering externally created genomes so lineage & invariants remain consistent.
504
+ 3. Creating the initial population pool (bootstrapping evolution) either from a seed
505
+ network or by synthesizing fresh minimal networks.
506
+
507
+ All helpers expect to be invoked with a `this` context that matches `NeatLike`.
508
+ They intentionally use defensive try/catch blocks to avoid aborting broader
509
+ evolutionary runs when an individual genome operation fails; this mirrors the
510
+ tolerant/robust nature of many historical NEAT library implementations.
511
+
512
+ ## neat/neat.lineage.ts
513
+
514
+ ### buildAnc
515
+
516
+ `(genome: import("D:/code-practice/NeatapticTS/src/neat/neat.lineage").GenomeLike) => Set<number>`
517
+
518
+ Build the (shallow) ancestor ID set for a single genome using breadth‑first traversal.
519
+
520
+ Traversal Strategy:
521
+ 1. Seed queue with the genome's parent IDs (depth = 1).
522
+ 2. Repeatedly dequeue, record its ID, and enqueue its parents with incremented depth.
523
+ 3. Stop exploring a branch once the configured depth window is exceeded.
524
+
525
+ This bounded BFS gives a quick, memory‑friendly approximation of a genome's lineage neighborhood
526
+ that works well for diversity/uniqueness metrics without the expense of full historical graphs.
527
+
528
+ Edge Cases:
529
+ - Missing or empty `_parents` array ⇒ returns an empty set.
530
+ - Orphan parent IDs (not found in population) are still added (their ID), but no further expansion occurs.
531
+
532
+ Complexity (worst case): O(B^D) where B is average branching factor of parent links (usually <= 2)
533
+ and D = ANCESTOR_DEPTH_WINDOW (default 4) – so effectively constant for typical NEAT usage.
534
+
535
+ Parameters:
536
+ - `this` - NEAT / evolutionary context; must provide `population` (array) for ID lookups.
537
+ - `genome` - Genome whose shallow ancestor set you want to compute.
538
+
539
+ Returns: A Set of numeric ancestor IDs (deduplicated).
540
+
541
+ ### computeAncestorUniqueness
542
+
543
+ `() => number`
544
+
545
+ Compute an "ancestor uniqueness" diversity metric for the current population.
546
+
547
+ The metric = mean Jaccard distance between shallow ancestor sets of randomly sampled genome pairs.
548
+ A higher value indicates that individuals trace back to more distinct recent lineages (i.e. less
549
+ overlap in their ancestor windows), while a lower value indicates convergence toward similar ancestry.
550
+
551
+ Why Jaccard Distance? It is scale‑independent: adding unrelated ancestors to both sets simultaneously
552
+ does not change the proportion of shared ancestry, and distance stays within [0,1].
553
+
554
+ Sampling Strategy:
555
+ - Uniformly sample up to N = min(30, populationPairs) distinct unordered pairs (with replacement on pair selection, but indices are adjusted to avoid self‑pairs).
556
+ - For each pair, construct ancestor sets via `buildAnc` and accumulate their Jaccard distance.
557
+ - Return the average (rounded to 3 decimal places) or 0 if insufficient samples.
558
+
559
+ Edge Cases:
560
+ - Population < 2 ⇒ returns 0 (cannot form pairs).
561
+ - Both ancestor sets empty ⇒ pair skipped (no information about uniqueness).
562
+
563
+ Performance: O(S * W) where S is sampled pair count (≤ 30) and W is bounded ancestor set size
564
+ (kept small by the depth window). This is intentionally lightweight for per‑generation telemetry.
565
+
566
+ Parameters:
567
+ - `this` - NEAT context (`population` and `_getRNG` must exist).
568
+
569
+ Returns: Mean Jaccard distance in [0,1]. Higher ⇒ more lineage uniqueness / diversity.
570
+
571
+ ### GenomeLike
572
+
573
+ Lineage / ancestry analysis helpers for NEAT populations.
574
+
575
+ These utilities were migrated from the historical implementation inside `src/neat.ts`
576
+ to keep core NEAT logic lean while still exposing educational metrics for users who
577
+ want to introspect evolutionary diversity.
578
+
579
+ Glossary:
580
+ - Genome: An individual network encoding (has a unique `_id` and optional `_parents`).
581
+ - Ancestor Window: A shallow breadth‑first window (default depth = 4) over the lineage graph.
582
+ - Jaccard Distance: 1 - |A ∩ B| / |A ∪ B|, measuring dissimilarity between two sets.
583
+
584
+ ### NeatLineageContext
585
+
586
+ Expected `this` context for lineage helpers (a subset of the NEAT instance).
587
+
588
+ ## neat/neat.multiobjective.ts
589
+
590
+ ### fastNonDominated
591
+
592
+ `(pop: import("D:/code-practice/NeatapticTS/src/architecture/network").default[]) => import("D:/code-practice/NeatapticTS/src/architecture/network").default[][]`
593
+
594
+ Perform fast non-dominated sorting and compute crowding distances for a
595
+ population of networks (genomes). This implements a standard NSGA-II style
596
+ non-dominated sorting followed by crowding distance assignment.
597
+
598
+ The function annotates genomes with two fields used elsewhere in the codebase:
599
+ - `_moRank`: integer Pareto front rank (0 = best/frontier)
600
+ - `_moCrowd`: numeric crowding distance (higher is better; Infinity for
601
+ boundary solutions)
602
+
603
+ Example
604
+ ```ts
605
+ // inside a Neat class that exposes `_getObjectives()` and `options`
606
+ const fronts = fastNonDominated.call(neatInstance, population);
607
+ // fronts[0] is the Pareto-optimal set
608
+ ```
609
+
610
+ Notes for documentation generation:
611
+ - Each objective descriptor returned by `_getObjectives()` must have an
612
+ `accessor(genome: Network): number` function and may include
613
+ `direction: 'max' | 'min'` to indicate optimization direction.
614
+ - Accessor failures are guarded and will yield a default value of 0.
615
+
616
+ Parameters:
617
+ - `this` - - Neat instance providing `_getObjectives()`, `options` and
618
+ `_paretoArchive` fields (function is meant to be invoked using `.call`)
619
+ - `pop` - - population array of `Network` genomes to be ranked
620
+
621
+ Returns: Array of Pareto fronts; each front is an array of `Network` genomes.
622
+
623
+ ### ObjectiveDescriptor
624
+
625
+ Shape of an objective descriptor used by the Neat instance.
626
+ - `accessor` extracts a numeric objective from a genome
627
+ - `direction` optionally indicates whether the objective is maximized or
628
+ minimized (defaults to 'max')
629
+
630
+ ## neat/neat.mutation.ts
631
+
632
+ ### ensureMinHiddenNodes
633
+
634
+ `(network: any, multiplierOverride: number | undefined) => void`
635
+
636
+ Ensure the network has a minimum number of hidden nodes and connectivity.
637
+
638
+ ### ensureNoDeadEnds
639
+
640
+ `(network: any) => void`
641
+
642
+ Ensure there are no dead-end nodes (input/output isolation) in the network.
643
+
644
+ ### mutate
645
+
646
+ `() => void`
647
+
648
+ Mutate every genome in the population according to configured policies.
649
+
650
+ This is the high-level mutation driver used by NeatapticTS. It iterates the
651
+ current population and, depending on the configured mutation rate and
652
+ (optional) adaptive mutation controller, applies one or more mutation
653
+ operators to each genome.
654
+
655
+ Educational notes:
656
+ - Adaptive mutation allows per-genome mutation rates/amounts to evolve so
657
+ that successful genomes can reduce or increase plasticity over time.
658
+ - Structural mutations (ADD_NODE, ADD_CONN, etc.) may update global
659
+ innovation bookkeeping; this function attempts to reuse specialized
660
+ helper routines that preserve innovation ids across the population.
661
+
662
+ Example:
663
+ ```ts
664
+ // called on a Neat instance after a generation completes
665
+ neat.mutate();
666
+ ```
667
+
668
+ ### mutateAddConnReuse
669
+
670
+ `(genome: any) => void`
671
+
672
+ Add a connection between two unconnected nodes reusing a stable innovation id per pair.
673
+
674
+ ### mutateAddNodeReuse
675
+
676
+ `(genome: any) => void`
677
+
678
+ Split a random enabled connection inserting a hidden node while reusing historical
679
+ innovations for identical (from,to) pairs across genomes. Extracted from Neat class.
680
+
681
+ ### selectMutationMethod
682
+
683
+ `(genome: any, rawReturnForTest: boolean) => any`
684
+
685
+ Select a mutation method respecting structural constraints and adaptive controllers.
686
+ Mirrors legacy implementation from `neat.ts` to preserve test expectations.
687
+ `rawReturnForTest` retains historical behavior where the full FFW array is
688
+ returned for identity checks in tests.
689
+
690
+ ## neat/neat.objectives.ts
691
+
692
+ ### _getObjectives
693
+
694
+ `() => import("D:/code-practice/NeatapticTS/src/neat/neat.types").ObjectiveDescriptor[]`
695
+
696
+ Build and return the list of registered objectives for this NEAT instance.
697
+
698
+ This function lazily builds `this._objectivesList` from the built-in
699
+ fitness objective (unless suppressed) and any user-registered multi-
700
+ objective descriptors found on `this.options.multiObjective.objectives`.
701
+
702
+ Typical use: the evolution loop calls this to know which objectives to
703
+ evaluate and whether each objective should be maximized or minimized.
704
+
705
+ Example:
706
+ ```ts
707
+ const objectives = neatInstance._getObjectives();
708
+ // objectives: Array<ObjectiveDescriptor>
709
+ ```
710
+
711
+ Returns: Array of objective descriptors in the
712
+ order they should be applied. If multi-objective support is disabled or
713
+ no objectives are registered, this will contain only the built-in
714
+ fitness objective (unless suppressed).
715
+
716
+ ### clearObjectives
717
+
718
+ `() => void`
719
+
720
+ Clear all registered multi-objectives.
721
+
722
+ This resets `this.options.multiObjective.objectives` to an empty array and
723
+ clears the cached objectives list so that subsequent calls will reflect the
724
+ cleared state.
725
+
726
+ Example:
727
+ ```ts
728
+ neat.clearObjectives();
729
+ // now only the default fitness objective (unless suppressed) will remain
730
+ ```
731
+
732
+ ### registerObjective
733
+
734
+ `(key: string, direction: "max" | "min", accessor: (genome: import("D:/code-practice/NeatapticTS/src/neat/neat.types").GenomeLike) => number) => void`
735
+
736
+ Register a new objective descriptor.
737
+
738
+ This adds or replaces an objective with the given `key`. The objective is a
739
+ lightweight descriptor with a `key`, `direction` ('min' | 'max'), and an
740
+ `accessor` function that maps a genome to a numeric objective value.
741
+
742
+ Example:
743
+ ```ts
744
+ // register an objective that measures model sparsity (lower is better)
745
+ neat.registerObjective('sparsity', 'min', genome => computeSparsity(genome));
746
+ ```
747
+
748
+ Notes:
749
+ - If `this.options.multiObjective` doesn't exist it will be created and
750
+ enabled.
751
+ - Registering an objective replaces any previous objective with the same
752
+ `key`.
753
+
754
+ Parameters:
755
+ - `` - Unique name for the objective (used for sorting/lookup)
756
+ - `` - Whether the objective should be minimized or maximized
757
+ - `` - Function to extract a numeric value from a genome
758
+
759
+ ## neat/neat.pruning.ts
760
+
761
+ ### applyAdaptivePruning
762
+
763
+ `() => void`
764
+
765
+ Adaptive pruning controller.
766
+
767
+ This function monitors a population-level metric (average nodes or
768
+ average connections) and adjusts a global pruning level so the
769
+ population converges to a target sparsity automatically.
770
+
771
+ It updates `this._adaptivePruneLevel` on the Neat instance and calls
772
+ each genome's `pruneToSparsity` with the new level when adjustment
773
+ is required.
774
+
775
+ Example:
776
+ ```ts
777
+ // options.adaptivePruning = { enabled: true, metric: 'connections', targetSparsity: 0.6 }
778
+ neat.applyAdaptivePruning();
779
+ ```
780
+
781
+ ### applyEvolutionPruning
782
+
783
+ `() => void`
784
+
785
+ Apply evolution-time pruning to the current population.
786
+
787
+ This method is intended to be called from the evolve loop. It reads
788
+ pruning parameters from `this.options.evolutionPruning` and, when
789
+ appropriate for the current generation, instructs each genome to
790
+ prune its connections/nodes to reach a target sparsity.
791
+
792
+ The pruning target can be ramped in over a number of generations so
793
+ sparsification happens gradually instead of abruptly.
794
+
795
+ Example (in a Neat instance):
796
+ ```ts
797
+ // options.evolutionPruning = { startGeneration: 10, targetSparsity: 0.5 }
798
+ neat.applyEvolutionPruning();
799
+ ```
800
+
801
+ Notes for docs:
802
+ - `method` is passed through to each genome's `pruneToSparsity` and
803
+ commonly is `'magnitude'` (prune smallest-weight connections first).
804
+ - This function performs no changes if pruning options are not set or
805
+ the generation is before `startGeneration`.
806
+
807
+ ## neat/neat.selection.ts
808
+
809
+ ### getAverage
810
+
811
+ `() => number`
812
+
813
+ Compute the average (mean) fitness across the population.
814
+
815
+ If genomes have not been evaluated yet this will call `evaluate()` so
816
+ that scores exist. Missing scores are treated as 0.
817
+
818
+ Example:
819
+ const avg = neat.getAverage();
820
+ console.log(`Average fitness: ${avg}`);
821
+
822
+ Returns: The mean fitness as a number.
823
+
824
+ ### getFittest
825
+
826
+ `() => any`
827
+
828
+ Return the fittest genome in the population.
829
+
830
+ This will trigger an `evaluate()` if genomes have not been scored yet, and
831
+ will ensure the population is sorted so index 0 contains the fittest.
832
+
833
+ Example:
834
+ const best = neat.getFittest();
835
+ console.log(best.score);
836
+
837
+ Returns: The genome object judged to be the fittest (highest score).
838
+
839
+ ### getParent
840
+
841
+ `() => any`
842
+
843
+ Select a parent genome according to the configured selection strategy.
844
+
845
+ Supported strategies (via `options.selection.name`):
846
+ - 'POWER' : biased power-law selection (exploits best candidates)
847
+ - 'FITNESS_PROPORTIONATE': roulette-wheel style selection proportional to fitness
848
+ - 'TOURNAMENT' : pick N random competitors and select the best with probability p
849
+
850
+ This function intentionally makes no changes to the population except in
851
+ the POWER path where a quick sort may be triggered to ensure descending
852
+ order.
853
+
854
+ Examples:
855
+ // POWER selection (higher power => more exploitation)
856
+ neat.options.selection = { name: 'POWER', power: 2 };
857
+ const parent = neat.getParent();
858
+
859
+ // Tournament selection (size 3, 75% probability to take top of tournament)
860
+ neat.options.selection = { name: 'TOURNAMENT', size: 3, probability: 0.75 };
861
+ const parent2 = neat.getParent();
862
+
863
+ Returns: A genome object chosen as the parent according to the selection strategy
864
+
865
+ ### sort
866
+
867
+ `() => void`
868
+
869
+ Sorts the internal population in place by descending fitness.
870
+
871
+ This method mutates the `population` array on the Neat instance so that
872
+ the genome with the highest `score` appears at index 0. It treats missing
873
+ scores as 0.
874
+
875
+ Example:
876
+ const neat = new Neat(...);
877
+ neat.sort();
878
+ console.log(neat.population[0].score); // highest score
879
+
880
+ Notes for documentation generators: this is a small utility used by many
881
+ selection and evaluation routines; it intentionally sorts in-place for
882
+ performance and to preserve references to genome objects.
883
+
884
+ ## neat/neat.speciation.ts
885
+
886
+ ### _applyFitnessSharing
887
+
888
+ `() => void`
889
+
890
+ Apply fitness sharing within each species.
891
+
892
+ Fitness sharing reduces the effective fitness of genomes that are clustered
893
+ tightly together (close compatibility distance), promoting diversity by
894
+ penalizing dense species. Two modes are supported:
895
+ - Kernel sharing with bandwidth `sharingSigma` (quadratic kernel)
896
+ - Equal sharing based on species size when `sharingSigma` is 0
897
+
898
+ Example:
899
+ neat.options.sharingSigma = 3;
900
+ neat._applyFitnessSharing();
901
+
902
+ ### _sortSpeciesMembers
903
+
904
+ `(sp: any) => void`
905
+
906
+ Sort members of a species in descending order by score.
907
+
908
+ Simple utility used by stagnation checks and selection routines to ensure
909
+ the top-performing genomes are at index 0.
910
+
911
+ Parameters:
912
+ - `sp` - species-like object with a `members` array and member `.score`
913
+
914
+ ### _speciate
915
+
916
+ `() => void`
917
+
918
+ Assign genomes into species based on compatibility distance and maintain species structures.
919
+ This function creates new species for unassigned genomes, prunes empty species, updates
920
+ dynamic compatibility threshold controllers, performs optional auto coefficient tuning, and
921
+ records per‑species history statistics used by telemetry and adaptive controllers.
922
+
923
+ Implementation notes:
924
+ - Uses existing representatives; any unassigned genome that doesn't fit an existing species
925
+ creates a new species with itself as representative.
926
+ - Representatives are refreshed each generation (first member heuristic) to reduce drift cost.
927
+ - Includes optional age penalty for very old species to gently reduce their reproductive share.
928
+ - PID‑style controller adjusts the global compatibility threshold toward `targetSpecies`.
929
+ - Auto compatibility coefficient tuning slightly nudges excess/disjoint coefficients to influence
930
+ clustering granularity when enabled.
931
+ - Extended history snapshot captures structural and innovation statistics for richer telemetry.
932
+
933
+ ### _updateSpeciesStagnation
934
+
935
+ `() => void`
936
+
937
+ Update species stagnation statistics and prune species that have not
938
+ improved within the configured stagnation window.
939
+
940
+ This updates each species' `bestScore` and `lastImproved` fields and then
941
+ removes species whose age since last improvement exceeds `stagnationGenerations`.
942
+
943
+ ## neat/neat.species.ts
944
+
945
+ ### getSpeciesHistory
946
+
947
+ `() => import("D:/code-practice/NeatapticTS/src/neat/neat.types").SpeciesHistoryEntry[]`
948
+
949
+ Retrieve the recorded species history across generations.
950
+
951
+ Each entry in the returned array corresponds to a recorded generation and
952
+ contains a snapshot of statistics for every species at that generation.
953
+ This is useful for plotting species sizes over time, tracking innovation
954
+ spread, or implementing population-level diagnostics.
955
+
956
+ The shape of each entry is defined by `SpeciesHistoryEntry` in the public
957
+ types. When `options.speciesAllocation.extendedHistory` is enabled the
958
+ library attempts to include additional metrics such as `innovationRange`
959
+ and `enabledRatio`. When those extended metrics are missing they are
960
+ computed lazily from a representative genome to ensure historical data is
961
+ still useful for analysis.
962
+
963
+ Example:
964
+ ```ts
965
+ const history = neat.getSpeciesHistory();
966
+ // history => [{ generation: 0, stats: [{ id:1, size:10, innovationRange:5, enabledRatio:0.9 }, ...] }, ...]
967
+ ```
968
+
969
+ Notes for documentation:
970
+ - The function tries to avoid heavy computation. Extended metrics are
971
+ computed only when explicitly requested via options.
972
+ - Computed extended metrics are conservative fallbacks; they use the
973
+ available member connections and a fallback innovation extractor when
974
+ connection innovation IDs are not present.
975
+
976
+ Returns: Array of generation-stamped species statistic snapshots.
977
+
978
+ ### getSpeciesStats
979
+
980
+ `() => { id: number; size: number; bestScore: number; lastImproved: number; }[]`
981
+
982
+ Get lightweight per-species statistics for the current population.
983
+
984
+ This method intentionally returns a small, immutable-friendly summary per
985
+ species rather than exposing internal member lists. This avoids accidental
986
+ mutation of the library's internal state while still providing useful
987
+ telemetry for UIs, dashboards, or logging.
988
+
989
+ Example:
990
+ ```ts
991
+ const stats = neat.getSpeciesStats();
992
+ // stats => [{ id: 1, size: 12, bestScore: 0.85, lastImproved: 42 }, ...]
993
+ ```
994
+
995
+ Success criteria:
996
+ - Returns an array of objects each containing `id`, `size`, `bestScore`,
997
+ and `lastImproved`.
998
+ - Does not expose or return references to internal member arrays.
999
+
1000
+ Returns: Array of per-species summaries suitable for reporting.
1001
+
1002
+ ## neat/neat.telemetry.exports.ts
1003
+
1004
+ ### buildSpeciesHistoryCsv
1005
+
1006
+ `(recentHistory: { generation: number; stats: any[]; }[], headers: string[]) => string`
1007
+
1008
+ Build the full CSV string for species history given ordered headers and
1009
+ a slice of history entries.
1010
+
1011
+ Implementation notes:
1012
+ - The history is a 2‑level structure (generation entry -> species stats[]).
1013
+ - We emit one CSV row per species stat, repeating the generation value.
1014
+ - Values are JSON.stringify'd to remain safe for commas/quotes.
1015
+
1016
+ ### buildTelemetryHeaders
1017
+
1018
+ `(info: TelemetryHeaderInfo) => string[]`
1019
+
1020
+ Build the ordered list of CSV headers from collected metadata.
1021
+ Flattened nested metrics are emitted using group prefixes (group.key).
1022
+
1023
+ ### collectTelemetryHeaderInfo
1024
+
1025
+ `(entries: any[]) => TelemetryHeaderInfo`
1026
+
1027
+ Collect header metadata from the raw telemetry entries.
1028
+ - Discovers base (top‑level) keys excluding grouped objects.
1029
+ - Discovers nested keys inside complexity, perf, lineage, diversity groups.
1030
+ - Tracks presence of optional multi-value structures (ops, objectives, etc.).
1031
+
1032
+ ### exportSpeciesHistoryCSV
1033
+
1034
+ `(maxEntries: number) => string`
1035
+
1036
+ Export species history snapshots to CSV.
1037
+
1038
+ Each row represents a single species at a specific generation; the generation
1039
+ value is repeated per species. Dynamically discovers species stat keys so
1040
+ custom metadata added at runtime is preserved.
1041
+
1042
+ Behavior:
1043
+ - If `_speciesHistory` is absent/empty but `_species` exists, synthesizes a
1044
+ minimal snapshot to ensure deterministic headers early in a run.
1045
+ - Returns a header-only CSV when there is no history or species.
1046
+
1047
+ Parameters:
1048
+ - `this` - Neat instance (expects `_speciesHistory` and optionally `_species`).
1049
+ - `maxEntries` - Maximum number of most recent history snapshots (generations) to include (default 200).
1050
+
1051
+ Returns: CSV string (headers + rows) describing species evolution timeline.
1052
+
1053
+ ### exportTelemetryCSV
1054
+
1055
+ `(maxEntries: number) => string`
1056
+
1057
+ Export recent telemetry entries to a CSV string.
1058
+
1059
+ Responsibilities:
1060
+ - Collect a bounded slice (`maxEntries`) of recent telemetry records.
1061
+ - Discover and flatten dynamic header keys (top-level + grouped metrics).
1062
+ - Serialize each entry into a CSV row with stable, parseable values.
1063
+
1064
+ Flattening Rules:
1065
+ - Nested groups (complexity, perf, lineage, diversity) become group.key columns.
1066
+ - Optional arrays/maps (ops, objectives, objAges, speciesAlloc, objEvents, objImportance, fronts) included only if present.
1067
+
1068
+ Parameters:
1069
+ - `this` - Neat instance (expects `_telemetry` array field).
1070
+ - `maxEntries` - Maximum number of most recent telemetry entries to include (default 500).
1071
+
1072
+ Returns: CSV string (headers + rows) or empty string when no telemetry.
1073
+
1074
+ ### exportTelemetryJSONL
1075
+
1076
+ `() => string`
1077
+
1078
+ Telemetry export helpers extracted from `neat.ts`.
1079
+
1080
+ This module exposes small helpers intended to serialize the internal
1081
+ telemetry gathered by the NeatapticTS `Neat` runtime into common
1082
+ data-export formats (JSONL and CSV). The functions intentionally
1083
+ operate against `this` so they can be attached to instances.
1084
+
1085
+ ### serializeTelemetryEntry
1086
+
1087
+ `(entry: any, headers: string[]) => string`
1088
+
1089
+ Serialize one telemetry entry into a CSV row using previously computed headers.
1090
+ Uses a `switch(true)` pattern instead of a long if/else chain to reduce
1091
+ cognitive complexity while preserving readability of each scenario.
1092
+
1093
+ ### TelemetryHeaderInfo
1094
+
1095
+ Shape describing collected telemetry header discovery info.
1096
+
1097
+ ## neat/neat.telemetry.ts
1098
+
1099
+ ### applyTelemetrySelect
1100
+
1101
+ `(entry: any) => any`
1102
+
1103
+ Apply a telemetry selection whitelist to a telemetry entry.
1104
+
1105
+ This helper inspects a per-instance Set of telemetry keys stored at
1106
+ `this._telemetrySelect`. If present, only keys included in the set are
1107
+ retained on the produced entry. Core fields (generation, best score and
1108
+ species count) are always preserved.
1109
+
1110
+ Example:
1111
+
1112
+ Parameters:
1113
+ - `entry` - - Raw telemetry object to be filtered in-place.
1114
+
1115
+ Returns: The filtered telemetry object (same reference as input).
1116
+
1117
+ ### buildTelemetryEntry
1118
+
1119
+ `(fittest: any) => import("D:/code-practice/NeatapticTS/src/neat/neat.types").TelemetryEntry`
1120
+
1121
+ Build a comprehensive telemetry entry for the current generation.
1122
+
1123
+ The returned object contains a snapshot of population statistics, multi-
1124
+ objective front sizes, operator statistics, lineage summaries and optional
1125
+ complexity/performance metrics depending on configured telemetry options.
1126
+
1127
+ This function intentionally mirrors the legacy in-loop telemetry construction
1128
+ to preserve behavior relied upon by tests and consumers.
1129
+
1130
+ Example:
1131
+
1132
+ Parameters:
1133
+ - `fittest` - - The currently fittest genome (used to report `best` score).
1134
+
1135
+ Returns: A TelemetryEntry object suitable for recording/streaming.
1136
+
1137
+ ### computeDiversityStats
1138
+
1139
+ `() => void`
1140
+
1141
+ Compute several diversity statistics used by telemetry reporting.
1142
+
1143
+ This helper is intentionally conservative in runtime: when `fastMode` is
1144
+ enabled it will automatically tune a few sampling defaults to keep the
1145
+ computation cheap. The computed statistics are written to
1146
+ `this._diversityStats` as an object with keys like `meanCompat` and
1147
+ `graphletEntropy`.
1148
+
1149
+ The method mutates instance-level temporary fields and reads a number of
1150
+ runtime options from `this.options`.
1151
+
1152
+ ### recordTelemetryEntry
1153
+
1154
+ `(entry: import("D:/code-practice/NeatapticTS/src/neat/neat.types").TelemetryEntry) => void`
1155
+
1156
+ Record a telemetry entry into the instance buffer and optionally stream it.
1157
+
1158
+ Steps:
1159
+ This method performs the following steps to persist and optionally stream telemetry:
1160
+ 1. Apply `applyTelemetrySelect` to filter fields according to user selection.
1161
+ 2. Ensure `this._telemetry` buffer exists and push the entry.
1162
+ 3. If a telemetry stream callback is configured, call it.
1163
+ 4. Trim the buffer to a conservative max size (500 entries).
1164
+
1165
+ Example:
1166
+
1167
+ Parameters:
1168
+ - `entry` - - Telemetry entry to record.
1169
+
1170
+ ### structuralEntropy
1171
+
1172
+ `(graph: any) => number`
1173
+
1174
+ Lightweight proxy for structural entropy based on degree-distribution.
1175
+
1176
+ This function computes an approximate entropy of a graph topology by
1177
+ counting node degrees and computing the entropy of the degree histogram.
1178
+ The result is cached on the graph object for the current generation in
1179
+ `_entropyVal` to avoid repeated expensive recomputation.
1180
+
1181
+ Example:
1182
+
1183
+ Parameters:
1184
+ - `graph` - - A genome-like object with `nodes` and `connections` arrays.
1185
+
1186
+ Returns: A non-negative number approximating structural entropy.
1187
+
1188
+ ## neat/neat.types.ts
1189
+
1190
+ ### AnyObj
1191
+
1192
+ Shared lightweight structural types for modular NEAT components.
1193
+
1194
+ These are deliberately kept small & structural (duck-typed) so that helper
1195
+ modules can interoperate without importing the concrete (heavier) `Neat`
1196
+ class, avoiding circular references while the codebase is being
1197
+ progressively extracted / refactored.
1198
+
1199
+ Guidelines:
1200
+ - Prefer adding narrowly scoped interfaces instead of widening existing ones.
1201
+ - Avoid leaking implementation details; keep contracts minimal.
1202
+ - Feature‑detect optional telemetry fields – they may be omitted to save cost.
1203
+
1204
+ ### ComplexityMetrics
1205
+
1206
+ Aggregate structural complexity metrics capturing size & growth pressure.
1207
+
1208
+ ### DiversityStats
1209
+
1210
+ Diversity statistics captured each generation. Individual fields may be
1211
+ omitted in telemetry output if diversity tracking is partially disabled to
1212
+ reduce runtime cost.
1213
+
1214
+ ### GenomeLike
1215
+
1216
+ Minimal genome structural surface used by several helpers (incrementally expanded).
1217
+
1218
+ NOTE: `nodes` & `connections` intentionally remain `any[]` until a stable
1219
+ `NodeLike` / `ConnectionLike` abstraction is finalised.
1220
+
1221
+ ### LineageSnapshot
1222
+
1223
+ Snapshot of lineage & ancestry statistics for the current generation.
1224
+
1225
+ ### NeatLike
1226
+
1227
+ Minimal surface every helper currently expects from a NEAT instance while
1228
+ extraction continues. At present it carries no guaranteed properties besides
1229
+ an index signature. As helpers converge, promote concrete, documented fields.
1230
+
1231
+ ### ObjAges
1232
+
1233
+ Map of objective key to age in generations since introduction.
1234
+
1235
+ ### ObjectiveDescriptor
1236
+
1237
+ Descriptor for a single optimisation objective (single or multi‑objective runs).
1238
+
1239
+ ### ObjEvent
1240
+
1241
+ Dynamic objective lifecycle event (addition or removal).
1242
+
1243
+ ### ObjImportance
1244
+
1245
+ Map of objective key to its importance metrics (range / variance).
1246
+
1247
+ ### ObjImportanceEntry
1248
+
1249
+ Contribution / dispersion metrics for an objective over a recent window.
1250
+ Used to gauge whether an objective meaningfully influences selection.
1251
+
1252
+ ### OperatorStat
1253
+
1254
+ Per-generation statistic for a genetic operator.
1255
+
1256
+ Success is operator‑specific (e.g. produced a structurally valid mutation).
1257
+ A high attempt count with low success can indicate constraints becoming tight
1258
+ (e.g. structural budgets reached) – useful for adaptive operator scheduling.
1259
+
1260
+ ### OperatorStatsRecord
1261
+
1262
+ Aggregated success / attempt counters over a window or entire run.
1263
+
1264
+ ### PerformanceMetrics
1265
+
1266
+ Timing metrics for coarse evolutionary phases (milliseconds).
1267
+
1268
+ ### SpeciesAlloc
1269
+
1270
+ Offspring allocation for a species during reproduction.
1271
+
1272
+ ### SpeciesHistoryEntry
1273
+
1274
+ Species statistics captured for a particular generation.
1275
+
1276
+ ### SpeciesHistoryStat
1277
+
1278
+ Species statistics at a single historical snapshot (generation boundary).
1279
+
1280
+ ### TelemetryEntry
1281
+
1282
+ Telemetry summary for one generation.
1283
+
1284
+ Optional properties are feature‑dependent; consumers MUST test for presence.