braintools 0.1.9__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. {braintools-0.1.9 → braintools-0.2.0}/PKG-INFO +8 -2
  2. {braintools-0.1.9 → braintools-0.2.0}/README.md +2 -1
  3. {braintools-0.1.9 → braintools-0.2.0}/braintools/_misc.py +4 -4
  4. {braintools-0.1.9 → braintools-0.2.0}/braintools/_spike_encoder.py +27 -23
  5. {braintools-0.1.9 → braintools-0.2.0}/braintools/_spike_operation.py +9 -7
  6. braintools-0.2.0/braintools/_typing_test.py +173 -0
  7. {braintools-0.1.9 → braintools-0.2.0}/braintools/_version.py +1 -1
  8. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/conditional.py +114 -18
  9. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/conditional_test.py +101 -0
  10. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/conftest.py +7 -3
  11. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/encoder.py +5 -0
  12. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/encoder_test.py +11 -0
  13. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/phase.py +31 -1
  14. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/task.py +162 -43
  15. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/task_test.py +159 -3
  16. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/task_variable_length_test.py +32 -0
  17. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/tasks/working_memory.py +1 -1
  18. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/__init__.py +5 -7
  19. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_base.py +104 -37
  20. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_base_test.py +208 -3
  21. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_biological.py +43 -17
  22. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_biological_test.py +36 -0
  23. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_compartment.py +265 -59
  24. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_compartment_test.py +165 -22
  25. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_kernel.py +177 -34
  26. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_kernel_test.py +209 -25
  27. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_random.py +25 -18
  28. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_random_test.py +41 -0
  29. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_regular.py +57 -29
  30. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_regular_test.py +21 -0
  31. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_spatial.py +123 -34
  32. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_spatial_test.py +118 -7
  33. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_topological.py +144 -77
  34. {braintools-0.1.9 → braintools-0.2.0}/braintools/conn/_topological_test.py +135 -0
  35. {braintools-0.1.9 → braintools-0.2.0}/braintools/file/__init__.py +16 -7
  36. braintools-0.2.0/braintools/file/_file_comprehensive_test.py +429 -0
  37. braintools-0.2.0/braintools/file/_matfile.py +250 -0
  38. braintools-0.2.0/braintools/file/_matfile_extra_test.py +217 -0
  39. {braintools-0.1.9 → braintools-0.2.0}/braintools/file/_msg_checkpoint.py +197 -119
  40. braintools-0.2.0/braintools/file/_msg_checkpoint_extra_test.py +525 -0
  41. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_distance_base.py +28 -19
  42. braintools-0.2.0/braintools/init/_distance_base_test.py +361 -0
  43. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_distance_impl.py +92 -39
  44. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_distance_impl_test.py +114 -0
  45. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_base.py +601 -561
  46. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_base_test.py +803 -746
  47. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_basic.py +128 -75
  48. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_basic_test.py +155 -0
  49. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_composite.py +70 -40
  50. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_composite_test.py +80 -0
  51. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_orthogonal.py +10 -0
  52. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_orthogonal_test.py +24 -8
  53. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_variance_scaling.py +53 -11
  54. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_variance_scaling_test.py +124 -14
  55. braintools-0.2.0/braintools/init/_init_with_distance.py +122 -0
  56. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/_init_with_distance_test.py +79 -0
  57. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/__init__.py +97 -81
  58. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_classification.py +159 -76
  59. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_classification_test.py +212 -0
  60. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_correlation.py +125 -75
  61. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_correlation_test.py +124 -6
  62. braintools-0.2.0/braintools/metric/_fenchel_young.py +177 -0
  63. braintools-0.2.0/braintools/metric/_fenchel_young_test.py +155 -0
  64. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_firings.py +278 -198
  65. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_firings_test.py +112 -14
  66. braintools-0.2.0/braintools/metric/_lfp.py +667 -0
  67. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_lfp_test.py +135 -1
  68. braintools-0.2.0/braintools/metric/_pairwise.py +189 -0
  69. braintools-0.2.0/braintools/metric/_pairwise_test.py +136 -0
  70. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_ranking.py +99 -19
  71. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_ranking_test.py +176 -0
  72. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_regression.py +402 -207
  73. braintools-0.2.0/braintools/metric/_regression_test.py +407 -0
  74. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_smoothing.py +43 -49
  75. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_smoothing_test.py +39 -0
  76. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/__init__.py +84 -55
  77. braintools-0.2.0/braintools/optim/_audit_fixes_test.py +851 -0
  78. braintools-0.2.0/braintools/optim/_base.py +78 -0
  79. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/_nevergrad_optimizer.py +84 -4
  80. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/_optax_lr_scheduler.py +241 -89
  81. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/_optax_lr_scheduler_test.py +17 -17
  82. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/_optax_optimizer.py +304 -96
  83. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/_scipy_optimizer.py +70 -15
  84. braintools-0.2.0/braintools/optim/_sofo_optimizer.py +503 -0
  85. braintools-0.2.0/braintools/optim/_sofo_optimizer_test.py +232 -0
  86. braintools-0.2.0/braintools/py.typed +1 -0
  87. {braintools-0.1.9 → braintools-0.2.0}/braintools/quad/__init__.py +83 -105
  88. {braintools-0.1.9 → braintools-0.2.0}/braintools/quad/_dde_integrator.py +1 -1
  89. {braintools-0.1.9 → braintools-0.2.0}/braintools/quad/_ode_integrator.py +50 -29
  90. braintools-0.2.0/braintools/quad/_quad_coverage_test.py +368 -0
  91. braintools-0.2.0/braintools/quad/_quad_regression_test.py +214 -0
  92. {braintools-0.1.9 → braintools-0.2.0}/braintools/quad/_sde_integrator.py +20 -12
  93. {braintools-0.1.9 → braintools-0.2.0}/braintools/quad/_sde_integrator_test.py +10 -3
  94. {braintools-0.1.9 → braintools-0.2.0}/braintools/surrogate/_base.py +19 -0
  95. braintools-0.2.0/braintools/surrogate/_base_test.py +299 -0
  96. braintools-0.2.0/braintools/surrogate/_correctness_test.py +388 -0
  97. {braintools-0.1.9 → braintools-0.2.0}/braintools/surrogate/_impl.py +40 -21
  98. braintools-0.2.0/braintools/surrogate/_impl_extra_test.py +307 -0
  99. {braintools-0.1.9 → braintools-0.2.0}/braintools/trainer/_callbacks.py +170 -41
  100. braintools-0.2.0/braintools/trainer/_callbacks_test.py +996 -0
  101. {braintools-0.1.9 → braintools-0.2.0}/braintools/trainer/_checkpoint.py +9 -3
  102. braintools-0.2.0/braintools/trainer/_checkpoint_test.py +649 -0
  103. {braintools-0.1.9 → braintools-0.2.0}/braintools/trainer/_dataloader.py +34 -7
  104. braintools-0.2.0/braintools/trainer/_dataloader_test.py +564 -0
  105. {braintools-0.1.9 → braintools-0.2.0}/braintools/trainer/_distributed.py +8 -3
  106. braintools-0.2.0/braintools/trainer/_distributed_test.py +218 -0
  107. {braintools-0.1.9 → braintools-0.2.0}/braintools/trainer/_loggers.py +38 -6
  108. braintools-0.2.0/braintools/trainer/_loggers_backends_test.py +344 -0
  109. braintools-0.2.0/braintools/trainer/_loggers_test.py +499 -0
  110. {braintools-0.1.9 → braintools-0.2.0}/braintools/trainer/_module.py +108 -18
  111. braintools-0.2.0/braintools/trainer/_module_test.py +421 -0
  112. {braintools-0.1.9 → braintools-0.2.0}/braintools/trainer/_progress.py +13 -4
  113. braintools-0.2.0/braintools/trainer/_progress_test.py +377 -0
  114. {braintools-0.1.9 → braintools-0.2.0}/braintools/trainer/_trainer.py +363 -112
  115. braintools-0.2.0/braintools/trainer/_trainer_audit_test.py +634 -0
  116. braintools-0.2.0/braintools/trainer/_trainer_extra_test.py +732 -0
  117. {braintools-0.1.9 → braintools-0.2.0}/braintools/tree.py +3 -3
  118. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/__init__.py +59 -59
  119. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_animation.py +32 -36
  120. braintools-0.2.0/braintools/visualize/_animation_test.py +85 -0
  121. braintools-0.2.0/braintools/visualize/_audit_fixes_test.py +310 -0
  122. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_colormaps.py +53 -5
  123. braintools-0.2.0/braintools/visualize/_colormaps_extra_test.py +139 -0
  124. braintools-0.2.0/braintools/visualize/_figures_test.py +52 -0
  125. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_interactive.py +7 -1
  126. braintools-0.2.0/braintools/visualize/_interactive_extra_test.py +243 -0
  127. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_neural.py +20 -13
  128. braintools-0.2.0/braintools/visualize/_neural_extra_test.py +390 -0
  129. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_plots.py +101 -52
  130. braintools-0.2.0/braintools/visualize/_plots_extra_test.py +336 -0
  131. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_statistical.py +26 -11
  132. braintools-0.2.0/braintools/visualize/_statistical_extra_test.py +338 -0
  133. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_three_d.py +8 -1
  134. braintools-0.2.0/braintools/visualize/_three_d_extra_test.py +267 -0
  135. {braintools-0.1.9 → braintools-0.2.0}/braintools.egg-info/PKG-INFO +8 -2
  136. {braintools-0.1.9 → braintools-0.2.0}/braintools.egg-info/SOURCES.txt +34 -3
  137. {braintools-0.1.9 → braintools-0.2.0}/braintools.egg-info/requires.txt +6 -0
  138. {braintools-0.1.9 → braintools-0.2.0}/pyproject.toml +155 -109
  139. braintools-0.1.9/braintools/file/_matfile.py +0 -146
  140. braintools-0.1.9/braintools/file/_matfile_test.py +0 -148
  141. braintools-0.1.9/braintools/init/_distance_base_test.py +0 -190
  142. braintools-0.1.9/braintools/init/_init_with_distance.py +0 -83
  143. braintools-0.1.9/braintools/metric/_fenchel_young.py +0 -122
  144. braintools-0.1.9/braintools/metric/_fenchel_young_test.py +0 -53
  145. braintools-0.1.9/braintools/metric/_lfp.py +0 -620
  146. braintools-0.1.9/braintools/metric/_pariwise.py +0 -114
  147. braintools-0.1.9/braintools/metric/_regression_test.py +0 -133
  148. braintools-0.1.9/braintools/optim/_base.py +0 -60
  149. braintools-0.1.9/braintools/visualize/_style.py +0 -82
  150. {braintools-0.1.9 → braintools-0.2.0}/LICENSE +0 -0
  151. {braintools-0.1.9 → braintools-0.2.0}/braintools/__init__.py +0 -0
  152. {braintools-0.1.9 → braintools-0.2.0}/braintools/_spike_encoder_test.py +0 -0
  153. {braintools-0.1.9 → braintools-0.2.0}/braintools/_spike_operation_test.py +0 -0
  154. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/__init__.py +0 -0
  155. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/_typing.py +0 -0
  156. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/_version.py +0 -0
  157. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/context.py +0 -0
  158. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/context_test.py +0 -0
  159. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/feature.py +0 -0
  160. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/feature_test.py +0 -0
  161. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/label.py +0 -0
  162. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/label_test.py +0 -0
  163. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/phase_test.py +0 -0
  164. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/tasks/__init__.py +0 -0
  165. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/tasks/decision_making.py +0 -0
  166. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/tasks/decision_making_test.py +0 -0
  167. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/tasks/motor.py +0 -0
  168. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/tasks/motor_test.py +0 -0
  169. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/tasks/reasoning.py +0 -0
  170. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/tasks/reasoning_test.py +0 -0
  171. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/tasks/working_memory_test.py +0 -0
  172. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/utils.py +0 -0
  173. {braintools-0.1.9 → braintools-0.2.0}/braintools/cogtask/utils_test.py +0 -0
  174. {braintools-0.1.9 → braintools-0.2.0}/braintools/file/_msg_checkpoint_async_test.py +0 -0
  175. {braintools-0.1.9 → braintools-0.2.0}/braintools/file/_msg_checkpoint_test.py +0 -0
  176. {braintools-0.1.9 → braintools-0.2.0}/braintools/init/__init__.py +0 -0
  177. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/__init__.py +0 -0
  178. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_composable_base.py +0 -0
  179. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_composable_base_test.py +0 -0
  180. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_composable_basic.py +0 -0
  181. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_composable_basic_test.py +0 -0
  182. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_composable_pulses.py +0 -0
  183. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_composable_pulses_test.py +0 -0
  184. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_composable_stochastic.py +0 -0
  185. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_composable_stochastic_test.py +0 -0
  186. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_composable_waveforms.py +0 -0
  187. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_composable_waveforms_test.py +0 -0
  188. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_deprecation.py +0 -0
  189. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_functional_basic.py +0 -0
  190. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_functional_basic_test.py +0 -0
  191. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_functional_pulses.py +0 -0
  192. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_functional_pulses_test.py +0 -0
  193. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_functional_stochastic.py +0 -0
  194. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_functional_stochastic_test.py +0 -0
  195. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_functional_waveforms.py +0 -0
  196. {braintools-0.1.9 → braintools-0.2.0}/braintools/input/_functional_waveforms_test.py +0 -0
  197. {braintools-0.1.9 → braintools-0.2.0}/braintools/metric/_util.py +0 -0
  198. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/_nevergrad_optimizer_test.py +0 -0
  199. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/_optax_optimizer_test.py +0 -0
  200. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/_scipy_optimizer_test.py +0 -0
  201. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/_state_uniquifier.py +0 -0
  202. {braintools-0.1.9 → braintools-0.2.0}/braintools/optim/_state_uniquifier_test.py +0 -0
  203. {braintools-0.1.9 → braintools-0.2.0}/braintools/quad/_dde_integrator_test.py +0 -0
  204. {braintools-0.1.9 → braintools-0.2.0}/braintools/quad/_imex_integrator.py +0 -0
  205. {braintools-0.1.9 → braintools-0.2.0}/braintools/quad/_imex_integrator_test.py +0 -0
  206. {braintools-0.1.9 → braintools-0.2.0}/braintools/quad/_ode_integrator_test.py +0 -0
  207. {braintools-0.1.9 → braintools-0.2.0}/braintools/surrogate/__init__.py +0 -0
  208. {braintools-0.1.9 → braintools-0.2.0}/braintools/surrogate/_impl_test.py +0 -0
  209. {braintools-0.1.9 → braintools-0.2.0}/braintools/trainer/__init__.py +0 -0
  210. {braintools-0.1.9 → braintools-0.2.0}/braintools/trainer/_trainer_test.py +0 -0
  211. {braintools-0.1.9 → braintools-0.2.0}/braintools/tree_test.py +0 -0
  212. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_colormaps_test.py +0 -0
  213. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_figures.py +0 -0
  214. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_interactive_test.py +0 -0
  215. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_neural_test.py +0 -0
  216. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_plots_test.py +0 -0
  217. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_statistical_test.py +0 -0
  218. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_three_d_test.py +0 -0
  219. {braintools-0.1.9 → braintools-0.2.0}/braintools/visualize/_visualize_test.py +0 -0
  220. {braintools-0.1.9 → braintools-0.2.0}/braintools.egg-info/dependency_links.txt +0 -0
  221. {braintools-0.1.9 → braintools-0.2.0}/braintools.egg-info/top_level.txt +0 -0
  222. {braintools-0.1.9 → braintools-0.2.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: braintools
3
- Version: 0.1.9
3
+ Version: 0.2.0
4
4
  Summary: Modeling tools for brain simulation.
5
5
  Author-email: BrainTools Developers <chao.brain@qq.com>
6
6
  License:
@@ -240,8 +240,13 @@ Requires-Dist: msgpack
240
240
  Requires-Dist: scipy
241
241
  Provides-Extra: testing
242
242
  Requires-Dist: pytest; extra == "testing"
243
+ Requires-Dist: pytest-cov; extra == "testing"
243
244
  Requires-Dist: absl-py; extra == "testing"
244
245
  Requires-Dist: nevergrad; extra == "testing"
246
+ Requires-Dist: tqdm; extra == "testing"
247
+ Requires-Dist: rich; extra == "testing"
248
+ Provides-Extra: type-check
249
+ Requires-Dist: mypy>=1.8; extra == "type-check"
245
250
  Provides-Extra: cpu
246
251
  Requires-Dist: jax[cpu]; extra == "cpu"
247
252
  Provides-Extra: cuda12
@@ -272,7 +277,7 @@ Dynamic: license-file
272
277
  # Modeling tools for brain simulation
273
278
 
274
279
  <p align="center">
275
- <img alt="Header image of braintools." src="https://raw.githubusercontent.com/chaobrain/braintools/main/docs/_static/braintools.png" width=50%>
280
+ <img alt="Header image of braintools." src="https://brainx.chaobrain.com/images/braintools.webp" width=50%>
276
281
  </p>
277
282
 
278
283
  <p align="center">
@@ -283,6 +288,7 @@ Dynamic: license-file
283
288
  </a>
284
289
  <a href="https://badge.fury.io/py/braintools"><img alt="PyPI version" src="https://badge.fury.io/py/braintools.svg"></a>
285
290
  <a href="https://github.com/chaobrain/braintools/actions/workflows/CI.yml"><img alt="Continuous Integration" src="https://github.com/chaobrain/braintools/actions/workflows/CI.yml/badge.svg"></a>
291
+ <a href="https://codecov.io/gh/chaobrain/braintools"><img alt="Test Coverage" src="https://codecov.io/gh/chaobrain/braintools/graph/badge.svg"></a>
286
292
  <a href="https://doi.org/10.5281/zenodo.17110064"><img src="https://zenodo.org/badge/776629792.svg" alt="DOI"></a>
287
293
  </p>
288
294
 
@@ -1,7 +1,7 @@
1
1
  # Modeling tools for brain simulation
2
2
 
3
3
  <p align="center">
4
- <img alt="Header image of braintools." src="https://raw.githubusercontent.com/chaobrain/braintools/main/docs/_static/braintools.png" width=50%>
4
+ <img alt="Header image of braintools." src="https://brainx.chaobrain.com/images/braintools.webp" width=50%>
5
5
  </p>
6
6
 
7
7
  <p align="center">
@@ -12,6 +12,7 @@
12
12
  </a>
13
13
  <a href="https://badge.fury.io/py/braintools"><img alt="PyPI version" src="https://badge.fury.io/py/braintools.svg"></a>
14
14
  <a href="https://github.com/chaobrain/braintools/actions/workflows/CI.yml"><img alt="Continuous Integration" src="https://github.com/chaobrain/braintools/actions/workflows/CI.yml/badge.svg"></a>
15
+ <a href="https://codecov.io/gh/chaobrain/braintools"><img alt="Test Coverage" src="https://codecov.io/gh/chaobrain/braintools/graph/badge.svg"></a>
15
16
  <a href="https://doi.org/10.5281/zenodo.17110064"><img src="https://zenodo.org/badge/776629792.svg" alt="DOI"></a>
16
17
  </p>
17
18
 
@@ -21,19 +21,19 @@ import brainunit as u
21
21
  import jax
22
22
 
23
23
 
24
- def set_module_as(module: str):
25
- def wrapper(fun: callable):
24
+ def set_module_as(module: str) -> Callable[[Callable], Callable]:
25
+ def wrapper(fun: Callable) -> Callable:
26
26
  fun.__module__ = module
27
27
  return fun
28
28
 
29
29
  return wrapper
30
30
 
31
31
 
32
- def tree_map(f: Callable[..., Any], tree: Any, *rest: Any):
32
+ def tree_map(f: Callable[..., Any], tree: Any, *rest: Any) -> Any:
33
33
  return jax.tree.map(f, tree, *rest, is_leaf=u.math.is_quantity)
34
34
 
35
35
 
36
- def randn_like(y):
36
+ def randn_like(y: brainstate.typing.ArrayLike) -> jax.Array:
37
37
  return brainstate.random.randn(*u.math.shape(y))
38
38
 
39
39
 
@@ -87,14 +87,14 @@ class LatencyEncoder:
87
87
 
88
88
  def __init__(
89
89
  self,
90
- min_val: float = None,
91
- max_val: float = None,
90
+ min_val: Optional[float] = None,
91
+ max_val: Optional[float] = None,
92
92
  method: str = 'log',
93
93
  threshold: float = 0.01,
94
94
  clip: bool = False,
95
- tau: float = 1. * u.ms,
95
+ tau: brainstate.typing.ArrayLike = 1. * u.ms,
96
96
  normalize: bool = False,
97
- first_spk_time: float = 0. * u.ms,
97
+ first_spk_time: brainstate.typing.ArrayLike = 0. * u.ms,
98
98
  epsilon: float = 1e-7,
99
99
  ):
100
100
  super().__init__()
@@ -114,7 +114,11 @@ class LatencyEncoder:
114
114
  self.first_spk_step = int(u.get_mantissa(first_spk_time) / u.get_mantissa(brainstate.environ.get_dt()))
115
115
  self.epsilon = epsilon
116
116
 
117
- def __call__(self, data, n_time: Optional[brainstate.typing.ArrayLike] = None):
117
+ def __call__(
118
+ self,
119
+ data: brainstate.typing.ArrayLike,
120
+ n_time: Optional[brainstate.typing.ArrayLike] = None,
121
+ ) -> jax.Array:
118
122
  """Generate latency spikes according to the given input data.
119
123
 
120
124
  Ensuring x in [0., 1.].
@@ -190,10 +194,10 @@ class RateEncoder:
190
194
  gain: float = 100.0,
191
195
  method: str = 'linear',
192
196
  min_rate: float = 0.0,
193
- max_rate: float = None,
197
+ max_rate: Optional[float] = None,
194
198
  normalize: bool = False,
195
- min_val: float = None,
196
- max_val: float = None,
199
+ min_val: Optional[float] = None,
200
+ max_val: Optional[float] = None,
197
201
  ):
198
202
  if method not in ['linear', 'exponential', 'sqrt']:
199
203
  raise ValueError('Method must be "linear", "exponential", or "sqrt"')
@@ -206,7 +210,7 @@ class RateEncoder:
206
210
  self.min_val = min_val
207
211
  self.max_val = max_val
208
212
 
209
- def __call__(self, data, n_time: int):
213
+ def __call__(self, data: brainstate.typing.ArrayLike, n_time: int) -> jax.Array:
210
214
  """Generate rate-encoded spikes.
211
215
 
212
216
  Args:
@@ -272,7 +276,7 @@ class PoissonEncoder:
272
276
  self.normalize = normalize
273
277
  self.max_rate = max_rate
274
278
 
275
- def __call__(self, data, n_time: int):
279
+ def __call__(self, data: brainstate.typing.ArrayLike, n_time: int) -> jax.Array:
276
280
  """Generate Poisson spike trains.
277
281
 
278
282
  Args:
@@ -325,7 +329,7 @@ class PopulationEncoder:
325
329
  n_neurons: int,
326
330
  min_val: float = 0.0,
327
331
  max_val: float = 1.0,
328
- sigma: float = None,
332
+ sigma: Optional[float] = None,
329
333
  max_rate: float = 100.0,
330
334
  ):
331
335
  self.n_neurons = n_neurons
@@ -337,7 +341,7 @@ class PopulationEncoder:
337
341
  # Create neuron preferred values (centers of receptive fields)
338
342
  self.centers = u.math.linspace(min_val, max_val, n_neurons)
339
343
 
340
- def __call__(self, data, n_time: int):
344
+ def __call__(self, data: brainstate.typing.ArrayLike, n_time: int) -> jax.Array:
341
345
  """Generate population-encoded spikes.
342
346
 
343
347
  Args:
@@ -405,15 +409,15 @@ class BernoulliEncoder:
405
409
  self,
406
410
  scale: float = 1.0,
407
411
  normalize: bool = True,
408
- min_val: float = None,
409
- max_val: float = None,
412
+ min_val: Optional[float] = None,
413
+ max_val: Optional[float] = None,
410
414
  ):
411
415
  self.scale = scale
412
416
  self.normalize = normalize
413
417
  self.min_val = min_val
414
418
  self.max_val = max_val
415
419
 
416
- def __call__(self, data, n_time: int):
420
+ def __call__(self, data: brainstate.typing.ArrayLike, n_time: int) -> jax.Array:
417
421
  """Generate Bernoulli-encoded spikes.
418
422
 
419
423
  Args:
@@ -469,7 +473,7 @@ class DeltaEncoder:
469
473
  self.absolute = absolute
470
474
  self.normalize = normalize
471
475
 
472
- def __call__(self, data):
476
+ def __call__(self, data: brainstate.typing.ArrayLike) -> jax.Array:
473
477
  """Generate delta-encoded spikes.
474
478
 
475
479
  Args:
@@ -528,8 +532,8 @@ class StepCurrentEncoder:
528
532
  current_scale: float = 10.0, # nA
529
533
  offset: float = 0.0,
530
534
  normalize: bool = True,
531
- min_val: float = None,
532
- max_val: float = None,
535
+ min_val: Optional[float] = None,
536
+ max_val: Optional[float] = None,
533
537
  ):
534
538
  self.current_scale = current_scale
535
539
  self.offset = offset
@@ -537,7 +541,7 @@ class StepCurrentEncoder:
537
541
  self.min_val = min_val
538
542
  self.max_val = max_val
539
543
 
540
- def __call__(self, data, n_time: int):
544
+ def __call__(self, data: brainstate.typing.ArrayLike, n_time: int) -> jax.Array:
541
545
  """Generate step current signals.
542
546
 
543
547
  Args:
@@ -591,7 +595,7 @@ class SpikeCountEncoder:
591
595
  self.distribution = distribution
592
596
  self.normalize = normalize
593
597
 
594
- def __call__(self, data, n_time: int):
598
+ def __call__(self, data: brainstate.typing.ArrayLike, n_time: int) -> jax.Array:
595
599
  """Generate spike count-encoded trains.
596
600
 
597
601
  Args:
@@ -665,7 +669,7 @@ class TemporalEncoder:
665
669
  # Pre-define temporal patterns
666
670
  self.patterns = self._create_patterns()
667
671
 
668
- def _create_patterns(self):
672
+ def _create_patterns(self) -> dict:
669
673
  """Create distinct temporal patterns for each input value."""
670
674
  patterns = {}
671
675
  for i in range(self.n_patterns):
@@ -677,7 +681,7 @@ class TemporalEncoder:
677
681
  patterns[i] = pattern_times
678
682
  return patterns
679
683
 
680
- def __call__(self, data):
684
+ def __call__(self, data: brainstate.typing.ArrayLike) -> jax.Array:
681
685
  """Generate temporally-encoded spikes.
682
686
 
683
687
  Args:
@@ -741,7 +745,7 @@ class RankOrderEncoder:
741
745
  self.normalize = normalize
742
746
  self.invert = invert
743
747
 
744
- def __call__(self, data, n_time: int):
748
+ def __call__(self, data: brainstate.typing.ArrayLike, n_time: int) -> jax.Array:
745
749
  """Generate rank-order encoded spikes.
746
750
 
747
751
  Args:
@@ -14,6 +14,8 @@
14
14
  # ==============================================================================
15
15
 
16
16
 
17
+ from brainstate.typing import ArrayLike
18
+
17
19
  from braintools._misc import set_module_as
18
20
 
19
21
  __all__ = [
@@ -28,7 +30,7 @@ __all__ = [
28
30
 
29
31
 
30
32
  @set_module_as('braintools')
31
- def spike_bitwise_or(x, y):
33
+ def spike_bitwise_or(x: ArrayLike, y: ArrayLike) -> ArrayLike:
32
34
  """
33
35
  Perform a bitwise OR operation on spike tensors.
34
36
 
@@ -52,7 +54,7 @@ def spike_bitwise_or(x, y):
52
54
 
53
55
 
54
56
  @set_module_as('braintools')
55
- def spike_bitwise_and(x, y):
57
+ def spike_bitwise_and(x: ArrayLike, y: ArrayLike) -> ArrayLike:
56
58
  """
57
59
  Perform a bitwise AND operation on spike tensors.
58
60
 
@@ -75,7 +77,7 @@ def spike_bitwise_and(x, y):
75
77
 
76
78
 
77
79
  @set_module_as('braintools')
78
- def spike_bitwise_iand(x, y):
80
+ def spike_bitwise_iand(x: ArrayLike, y: ArrayLike) -> ArrayLike:
79
81
  """
80
82
  Perform a bitwise IAND (Inverse AND) operation on spike tensors.
81
83
 
@@ -98,7 +100,7 @@ def spike_bitwise_iand(x, y):
98
100
 
99
101
 
100
102
  @set_module_as('braintools')
101
- def spike_bitwise_not(x):
103
+ def spike_bitwise_not(x: ArrayLike) -> ArrayLike:
102
104
  """
103
105
  Perform a bitwise NOT operation on spike tensors.
104
106
 
@@ -120,7 +122,7 @@ def spike_bitwise_not(x):
120
122
 
121
123
 
122
124
  @set_module_as('braintools')
123
- def spike_bitwise_xor(x, y):
125
+ def spike_bitwise_xor(x: ArrayLike, y: ArrayLike) -> ArrayLike:
124
126
  """
125
127
  Perform a bitwise XOR operation on spike tensors.
126
128
 
@@ -143,7 +145,7 @@ def spike_bitwise_xor(x, y):
143
145
 
144
146
 
145
147
  @set_module_as('braintools')
146
- def spike_bitwise_ixor(x, y):
148
+ def spike_bitwise_ixor(x: ArrayLike, y: ArrayLike) -> ArrayLike:
147
149
  """
148
150
  Perform a bitwise IXOR (Inverse XOR) operation on spike tensors.
149
151
 
@@ -166,7 +168,7 @@ def spike_bitwise_ixor(x, y):
166
168
 
167
169
 
168
170
  @set_module_as('braintools')
169
- def spike_bitwise(x, y, op: str):
171
+ def spike_bitwise(x: ArrayLike, y: ArrayLike, op: str) -> ArrayLike:
170
172
  r"""
171
173
  Perform bitwise operations on spike tensors.
172
174
 
@@ -0,0 +1,173 @@
1
+ # Copyright 2025 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """Tests that braintools ships PEP 561 type information and that its public
17
+ API carries usable type annotations consumable by static type checkers."""
18
+
19
+ import importlib.util
20
+ import inspect
21
+ import sys
22
+ import tomllib
23
+ import typing
24
+ import unittest
25
+ from pathlib import Path
26
+
27
+ import braintools
28
+
29
+ # Top-level public files whose annotations are actively maintained and are
30
+ # verified to be clean under mypy (see ``test_mypy_clean_public_surface``).
31
+ TYPED_PUBLIC_MODULES = (
32
+ '__init__.py',
33
+ '_misc.py',
34
+ '_spike_operation.py',
35
+ '_spike_encoder.py',
36
+ 'tree.py',
37
+ )
38
+
39
+ SPIKE_OPERATIONS = (
40
+ 'spike_bitwise_or',
41
+ 'spike_bitwise_and',
42
+ 'spike_bitwise_iand',
43
+ 'spike_bitwise_not',
44
+ 'spike_bitwise_xor',
45
+ 'spike_bitwise_ixor',
46
+ 'spike_bitwise',
47
+ )
48
+
49
+ ENCODERS = (
50
+ 'LatencyEncoder',
51
+ 'RateEncoder',
52
+ 'PoissonEncoder',
53
+ 'PopulationEncoder',
54
+ 'BernoulliEncoder',
55
+ 'DeltaEncoder',
56
+ 'StepCurrentEncoder',
57
+ 'SpikeCountEncoder',
58
+ 'TemporalEncoder',
59
+ 'RankOrderEncoder',
60
+ )
61
+
62
+
63
+ def _package_dir() -> Path:
64
+ return Path(braintools.__file__).resolve().parent
65
+
66
+
67
+ def _unannotated_params(func) -> list:
68
+ """Return the names of parameters lacking annotations (ignoring self/cls
69
+ and variadic ``*args``/``**kwargs``)."""
70
+ sig = inspect.signature(func)
71
+ missing = []
72
+ for name, param in sig.parameters.items():
73
+ if name in ('self', 'cls'):
74
+ continue
75
+ if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
76
+ continue
77
+ if param.annotation is inspect.Parameter.empty:
78
+ missing.append(name)
79
+ return missing
80
+
81
+
82
+ def _has_return_annotation(func) -> bool:
83
+ return inspect.signature(func).return_annotation is not inspect.Signature.empty
84
+
85
+
86
+ class TestPyTypedMarker(unittest.TestCase):
87
+ """PEP 561: a ``py.typed`` marker must ship inside the package directory."""
88
+
89
+ def test_marker_file_present(self):
90
+ marker = _package_dir() / 'py.typed'
91
+ self.assertTrue(marker.is_file(), f'py.typed marker missing at {marker}')
92
+
93
+ def test_marker_adjacent_to_init(self):
94
+ # The marker must sit next to __init__.py so type checkers discover it.
95
+ pkg = _package_dir()
96
+ self.assertTrue((pkg / '__init__.py').is_file())
97
+ self.assertTrue((pkg / 'py.typed').is_file())
98
+
99
+ def test_pyproject_declares_marker(self):
100
+ # Only present in a source checkout, not an installed wheel.
101
+ pyproject = _package_dir().parent / 'pyproject.toml'
102
+ if not pyproject.is_file():
103
+ self.skipTest('pyproject.toml not available (installed distribution)')
104
+ config = tomllib.loads(pyproject.read_text(encoding='utf-8'))
105
+ package_data = config['tool']['setuptools'].get('package-data', {})
106
+ self.assertIn('py.typed', package_data.get('braintools', []))
107
+
108
+
109
+ class TestPublicApiAnnotations(unittest.TestCase):
110
+ """The public API surface must carry resolvable type annotations."""
111
+
112
+ def test_all_exports_resolvable(self):
113
+ for name in braintools.__all__:
114
+ self.assertTrue(
115
+ hasattr(braintools, name),
116
+ f'braintools.__all__ advertises {name!r} but it is not importable',
117
+ )
118
+
119
+ def test_spike_operations_fully_annotated(self):
120
+ for name in SPIKE_OPERATIONS:
121
+ func = getattr(braintools, name)
122
+ missing = _unannotated_params(func)
123
+ self.assertEqual(missing, [], f'{name} has unannotated params: {missing}')
124
+ self.assertTrue(_has_return_annotation(func), f'{name} lacks a return annotation')
125
+
126
+ def test_tree_functions_fully_annotated(self):
127
+ for name in braintools.tree.__all__:
128
+ func = getattr(braintools.tree, name)
129
+ missing = _unannotated_params(func)
130
+ self.assertEqual(missing, [], f'tree.{name} has unannotated params: {missing}')
131
+ self.assertTrue(_has_return_annotation(func), f'tree.{name} lacks a return annotation')
132
+
133
+ def test_encoder_call_annotated(self):
134
+ for name in ENCODERS:
135
+ cls = getattr(braintools, name)
136
+ call = cls.__call__
137
+ self.assertTrue(_has_return_annotation(call), f'{name}.__call__ lacks a return annotation')
138
+ self.assertNotIn('data', _unannotated_params(call), f'{name}.__call__ data param unannotated')
139
+
140
+ def test_annotations_resolve_to_real_types(self):
141
+ # get_type_hints evaluates the (possibly stringized) annotations against
142
+ # the defining module globals; failure means a typo/undefined name.
143
+ targets = [getattr(braintools, n) for n in SPIKE_OPERATIONS]
144
+ targets += [getattr(braintools.tree, n) for n in braintools.tree.__all__]
145
+ for func in targets:
146
+ try:
147
+ hints = typing.get_type_hints(func)
148
+ except Exception as exc: # pragma: no cover - surfaced as failure
149
+ self.fail(f'Could not resolve annotations for {func.__name__}: {exc}')
150
+ self.assertIn('return', hints, f'{func.__name__} missing resolved return type')
151
+
152
+
153
+ class TestStaticTypeChecker(unittest.TestCase):
154
+ """Run mypy on the maintained public surface when it is installed."""
155
+
156
+ def test_mypy_clean_public_surface(self):
157
+ if importlib.util.find_spec('mypy') is None:
158
+ self.skipTest('mypy is not installed')
159
+ from mypy import api
160
+
161
+ pkg = _package_dir()
162
+ files = [str(pkg / name) for name in TYPED_PUBLIC_MODULES]
163
+ stdout, stderr, exit_status = api.run(
164
+ files + ['--follow-imports=skip', '--ignore-missing-imports', '--no-error-summary']
165
+ )
166
+ self.assertEqual(
167
+ exit_status, 0,
168
+ f'mypy reported issues on the public surface:\n{stdout}\n{stderr}',
169
+ )
170
+
171
+
172
+ if __name__ == '__main__':
173
+ sys.exit(unittest.main())
@@ -13,5 +13,5 @@
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
15
 
16
- __version__ = "0.1.9"
16
+ __version__ = "0.2.0"
17
17
  __version_info__ = tuple(map(int, __version__.split(".")))
@@ -29,6 +29,24 @@ __all__ = [
29
29
  ]
30
30
 
31
31
 
32
+ def _coerce_concrete_key(key: Any) -> Any:
33
+ """Normalize a Switch selector result to a hashable key.
34
+
35
+ ``ctx.rng.choice(...)`` (the natural way to pick a random rule in
36
+ ``trial_init``) returns a 0-d JAX array. In eager ``sample_trial`` that
37
+ value is *concrete but not a* :class:`jax.core.Tracer`, and it is
38
+ unhashable — so ``key in cases`` raises ``TypeError``. Coerce such
39
+ concrete 0-d arrays to a Python scalar so dict lookup works, while
40
+ leaving tracers (the ``jit``/``vmap`` path) and already-hashable keys
41
+ (``int``, ``str``) untouched.
42
+ """
43
+ if isinstance(key, jax.core.Tracer):
44
+ return key
45
+ if hasattr(key, 'ndim') and getattr(key, 'ndim', None) == 0:
46
+ return key.item()
47
+ return key
48
+
49
+
32
50
  class _CompoundCond(Phase):
33
51
  """Marker base — these phases manage their own children via ``execute``."""
34
52
  IS_COMPOUND = True
@@ -41,6 +59,16 @@ class If(_CompoundCond):
41
59
  Evaluates the condition at runtime and executes either the `then` phase
42
60
  or the `else_` phase (if provided).
43
61
 
62
+ Note
63
+ ----
64
+ Under ``batch_sample`` (jit/vmap) the branch is selected with
65
+ ``jax.lax.cond``, so both branches are traced. The output buffers
66
+ (``X``/``Y``/``mask``) are correct, but Python-side ``ctx`` state written
67
+ inside a branch (and ``phase_history``) reflects whichever branch traced
68
+ last, not the one actually taken. Do not read branch-written ``ctx[...]``
69
+ values in ``get_trial_meta`` or downstream phases when batching; gate such
70
+ state on the same condition at the top level instead.
71
+
44
72
  Examples
45
73
  --------
46
74
  >>> # Match vs non-match response
@@ -231,7 +259,7 @@ class Switch(_CompoundCond):
231
259
 
232
260
  def get_duration(self, ctx: Context) -> int:
233
261
  """Duration depends on which case is selected."""
234
- key = self.selector(ctx)
262
+ key = _coerce_concrete_key(self.selector(ctx))
235
263
  if key in self.cases:
236
264
  return self.cases[key].get_duration(ctx)
237
265
  elif self.default:
@@ -251,7 +279,7 @@ class Switch(_CompoundCond):
251
279
  # which builds a lax.switch over ordered branches; until that path
252
280
  # lands we fall back to the default branch (or zero) so the value is
253
281
  # still well-typed.
254
- key = self.selector(ctx)
282
+ key = _coerce_concrete_key(self.selector(ctx))
255
283
  try:
256
284
  phase = self.cases.get(key)
257
285
  except TypeError:
@@ -270,7 +298,7 @@ class Switch(_CompoundCond):
270
298
 
271
299
  def execute(self, ctx: Context) -> None:
272
300
  """Execute the phase corresponding to the selector's key."""
273
- key = self.selector(ctx)
301
+ key = _coerce_concrete_key(self.selector(ctx))
274
302
  ctx['switch_key'] = key # Store for debugging/analysis
275
303
  if key in self.cases:
276
304
  execute_phase(self.cases[key], ctx)
@@ -280,19 +308,69 @@ class Switch(_CompoundCond):
280
308
  def execute_packed(self, ctx: Context) -> None:
281
309
  """Packed-mode dispatch.
282
310
 
283
- Selects a branch using ``self.selector(ctx)`` and runs it via
284
- :func:`execute_phase_packed`. The selector must return a hashable
285
- Python value (string, int, …) — traced selectors would require a
286
- ``lax.switch`` based dispatch, which is not currently implemented.
311
+ When the selector returns a concrete Python value (eager
312
+ ``sample_trial``, or a selector that ignores trial state) we dispatch
313
+ with an ordinary ``key in cases`` lookup, which supports arbitrary
314
+ hashable keys (e.g. strings).
315
+
316
+ When the selector returns a *tracer* (under ``jit``/``vmap``, i.e.
317
+ ``batch_sample``) we dispatch with :func:`jax.lax.switch` over an
318
+ ordered list of branches. In this path the case keys must be integers
319
+ — a traced value cannot be a string. Keys not present in ``cases`` (or
320
+ any value when there is no matching integer key) route to ``default``,
321
+ or to a no-op when there is no default.
322
+
323
+ Note
324
+ ----
325
+ Like :meth:`If.execute_packed`, the tensor buffers are threaded through
326
+ the dispatch and are correct, but Python-side ``ctx`` state written
327
+ inside a branch is not reliable under tracing (every branch is traced).
328
+ Do not rely on branch-written ``ctx[...]`` values in
329
+ ``get_trial_meta``/downstream phases when using ``batch_sample``.
287
330
  """
288
- key = self.selector(ctx)
331
+ key = _coerce_concrete_key(self.selector(ctx))
289
332
  ctx['switch_key'] = key
290
- if key in self.cases:
291
- execute_phase_packed(self.cases[key], ctx)
292
- elif self.default is not None:
293
- execute_phase_packed(self.default, ctx)
294
- # Otherwise: no-op. The parent reserved ``max_steps`` worth of
295
- # buffer space; we simply don't advance ``t_cursor``.
333
+
334
+ if not isinstance(key, jax.core.Tracer):
335
+ # Concrete dispatch: supports arbitrary hashable keys.
336
+ if key in self.cases:
337
+ execute_phase_packed(self.cases[key], ctx)
338
+ elif self.default is not None:
339
+ execute_phase_packed(self.default, ctx)
340
+ # Otherwise: no-op. The parent reserved ``max_steps`` worth of
341
+ # buffer space; we simply don't advance ``t_cursor``.
342
+ return
343
+
344
+ # Traced dispatch via lax.switch over ordered branches.
345
+ keys = list(self.cases.keys())
346
+ phases = list(self.cases.values())
347
+ state_snapshot = dict(ctx._state)
348
+
349
+ def make_branch(phase: Phase):
350
+ def run(state):
351
+ ctx._state = dict(state_snapshot)
352
+ ctx.inputs, ctx.outputs, ctx.mask, ctx.t_cursor = state
353
+ execute_phase_packed(phase, ctx)
354
+ return (ctx.inputs, ctx.outputs, ctx.mask, ctx.t_cursor)
355
+ return run
356
+
357
+ branches = [make_branch(p) for p in phases]
358
+ # Fallback branch (last position): default phase, or an identity no-op.
359
+ if self.default is not None:
360
+ branches.append(make_branch(self.default))
361
+ else:
362
+ branches.append(lambda state: state)
363
+ fallback = len(branches) - 1
364
+
365
+ # Map the (possibly non-contiguous) integer key to a branch position.
366
+ index = jnp.asarray(fallback, dtype=jnp.int32)
367
+ for i, k in enumerate(keys):
368
+ if isinstance(k, int): # non-int keys can never match a traced int
369
+ index = jnp.where(jnp.asarray(key) == k, jnp.int32(i), index)
370
+
371
+ state = (ctx.inputs, ctx.outputs, ctx.mask, ctx.t_cursor)
372
+ new_state = jax.lax.switch(index, branches, state)
373
+ ctx.inputs, ctx.outputs, ctx.mask, ctx.t_cursor = new_state
296
374
 
297
375
  def children(self):
298
376
  out = list(self.cases.values())
@@ -395,12 +473,30 @@ class While(_CompoundCond):
395
473
  ctx['while_total_iterations'] = iteration
396
474
 
397
475
  def execute_packed(self, ctx: Context) -> None:
398
- """Packed-mode loop. The condition must return a Python ``bool``;
399
- tracer-valued conditions are not supported here (would require
400
- ``lax.while_loop`` with a state-as-pytree wrapper).
476
+ """Packed-mode loop (eager-only).
477
+
478
+ The loop is unrolled in Python, so the condition must evaluate to a
479
+ concrete ``bool``. This works for eager ``sample_trial`` but NOT under
480
+ ``jit``/``vmap`` (``batch_sample``) when the condition depends on a
481
+ traced value: we detect that case and raise a clear
482
+ :class:`NotImplementedError` instead of a cryptic
483
+ ``TracerBoolConversionError``. Full traced support would require a
484
+ ``jax.lax.while_loop`` with the buffers + trial state threaded as a
485
+ pytree, which is not yet implemented.
401
486
  """
402
487
  iteration = 0
403
- while self.condition(ctx) and iteration < self.max_iterations:
488
+ while iteration < self.max_iterations:
489
+ pred = self.condition(ctx)
490
+ if isinstance(pred, jax.core.Tracer):
491
+ raise NotImplementedError(
492
+ "While with a data-dependent (traced) condition is not "
493
+ "supported under jit/vmap (e.g. batch_sample). Evaluate it "
494
+ "eagerly via sample_trial, or replace the While with a "
495
+ "bounded Repeat / VariableDuration. (Full lax.while_loop "
496
+ "support is not yet implemented.)"
497
+ )
498
+ if not pred:
499
+ break
404
500
  ctx['while_iteration'] = iteration
405
501
  execute_phase_packed(self.body, ctx)
406
502
  iteration += 1