brainstate 0.1.0.post20250211__py2.py3-none-any.whl → 0.1.0.post20250212__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
brainstate/_state.py CHANGED
@@ -30,7 +30,7 @@ from jax.api_util import shaped_abstractify
30
30
  from jax.extend import source_info_util
31
31
 
32
32
  from brainstate.typing import ArrayLike, PyTree, Missing
33
- from brainstate.util import DictManager, PrettyReprTree
33
+ from brainstate.util import DictManager, PrettyObject
34
34
 
35
35
  __all__ = [
36
36
  'State', 'ShortTermState', 'LongTermState', 'HiddenState', 'ParamState', 'TreefyState',
@@ -186,7 +186,7 @@ def _get_trace_stack_level() -> int:
186
186
  return len(TRACE_CONTEXT.state_stack)
187
187
 
188
188
 
189
- class State(Generic[A], PrettyReprTree):
189
+ class State(Generic[A], PrettyObject):
190
190
  """
191
191
  The pointer to specify the dynamical data.
192
192
 
@@ -465,6 +465,25 @@ class State(Generic[A], PrettyReprTree):
465
465
  """
466
466
  return hash(id(self))
467
467
 
468
+ def numel(self) -> int:
469
+ """
470
+ Calculate the total number of elements in the state value.
471
+
472
+ This method traverses the state's value, which may be a nested structure (PyTree),
473
+ and computes the sum of sizes of all leaf nodes.
474
+
475
+ Returns:
476
+ int: The total number of elements across all arrays in the state value.
477
+ For scalar values, this will be 1. For arrays or nested structures,
478
+ it will be the sum of the sizes of all contained arrays.
479
+
480
+ Note:
481
+ This method uses jax.tree.leaves to flatten any nested structure in the state value,
482
+ and jax.numpy.size to compute the size of each leaf node.
483
+ """
484
+ sizes = [jax.numpy.size(val) for val in jax.tree.leaves(self._value)]
485
+ return sum(sizes)
486
+
468
487
 
469
488
  def record_state_init(st: State[A]):
470
489
  trace: Catcher
@@ -791,7 +810,7 @@ class StateTraceStack(Generic[A]):
791
810
  return StateTraceStack().merge(self, other)
792
811
 
793
812
 
794
- class TreefyState(Generic[A], PrettyReprTree):
813
+ class TreefyState(Generic[A], PrettyObject):
795
814
  """
796
815
  The state as a pytree.
797
816
  """
brainstate/surrogate.py CHANGED
@@ -21,6 +21,8 @@ import jax.numpy as jnp
21
21
  import jax.scipy as sci
22
22
  from jax.interpreters import batching, ad, mlir
23
23
 
24
+ from brainstate.util._dict import PrettyObject
25
+
24
26
  if jax.__version_info__ < (0, 4, 38):
25
27
  from jax.core import Primitive
26
28
  else:
@@ -77,7 +79,7 @@ def _heaviside_imp(x, dx):
77
79
 
78
80
 
79
81
  def _heaviside_batching(args, axes):
80
- return heaviside_p.bind(*args), [axes[0]]
82
+ return heaviside_p.bind(*args), tuple(axes)
81
83
 
82
84
 
83
85
  def _heaviside_jvp(primals, tangents):
@@ -97,7 +99,7 @@ ad.primitive_jvps[heaviside_p] = _heaviside_jvp
97
99
  mlir.register_lowering(heaviside_p, mlir.lower_fun(_heaviside_imp, multiple_results=True))
98
100
 
99
101
 
100
- class Surrogate(object):
102
+ class Surrogate(PrettyObject):
101
103
  """The base surrograte gradient function.
102
104
 
103
105
  To customize a surrogate gradient function, you can inherit this class and
@@ -142,9 +144,20 @@ class Surrogate(object):
142
144
  class Sigmoid(Surrogate):
143
145
  """Spike function with the sigmoid-shaped surrogate gradient.
144
146
 
147
+ This class implements a spiking neuron activation with a sigmoid-shaped
148
+ surrogate gradient for backpropagation. It can be used in spiking neural
149
+ networks to approximate the non-differentiable step function during training.
150
+
151
+ Parameters
152
+ ----------
153
+ alpha : float, optional
154
+ A parameter controlling the steepness of the sigmoid curve in the
155
+ surrogate gradient. Higher values make the transition sharper.
156
+ Default is 4.0.
157
+
145
158
  See Also
146
159
  --------
147
- sigmoid
160
+ sigmoid : Function version of this class.
148
161
 
149
162
  """
150
163
 
@@ -153,9 +166,33 @@ class Sigmoid(Surrogate):
153
166
  self.alpha = alpha
154
167
 
155
168
  def surrogate_fun(self, x):
169
+ """Compute the surrogate function.
170
+
171
+ Parameters
172
+ ----------
173
+ x : jax.Array
174
+ The input array.
175
+
176
+ Returns
177
+ -------
178
+ jax.Array
179
+ The output of the surrogate function.
180
+ """
156
181
  return sci.special.expit(self.alpha * x)
157
182
 
158
183
  def surrogate_grad(self, x):
184
+ """Compute the gradient of the surrogate function.
185
+
186
+ Parameters
187
+ ----------
188
+ x : jax.Array
189
+ The input array.
190
+
191
+ Returns
192
+ -------
193
+ jax.Array
194
+ The gradient of the surrogate function.
195
+ """
159
196
  sgax = sci.special.expit(x * self.alpha)
160
197
  dx = (1. - sgax) * sgax * self.alpha
161
198
  return dx
@@ -171,7 +208,12 @@ def sigmoid(
171
208
  x: jax.Array,
172
209
  alpha: float = 4.,
173
210
  ):
174
- r"""Spike function with the sigmoid-shaped surrogate gradient.
211
+ r"""
212
+ Compute a spike function with a sigmoid-shaped surrogate gradient.
213
+
214
+ This function implements a spiking neuron activation with a sigmoid-shaped
215
+ surrogate gradient for backpropagation. It can be used in spiking neural
216
+ networks to approximate the non-differentiable step function during training.
175
217
 
176
218
  If `origin=False`, return the forward function:
177
219
 
@@ -210,16 +252,28 @@ def sigmoid(
210
252
 
211
253
  Parameters
212
254
  ----------
213
- x: jax.Array, Array
214
- The input data.
215
- alpha: float
216
- Parameter to control smoothness of gradient
217
-
255
+ x : jax.Array
256
+ The input array representing the neuron's membrane potential.
257
+ alpha : float, optional
258
+ A parameter controlling the steepness of the sigmoid curve in the
259
+ surrogate gradient. Higher values make the transition sharper.
260
+ Default is 4.0.
218
261
 
219
262
  Returns
220
263
  -------
221
- out: jax.Array
222
- The spiking state.
264
+ jax.Array
265
+ An array of the same shape as the input, containing binary values (0 or 1)
266
+ representing the spiking state of each neuron.
267
+
268
+ Notes
269
+ -----
270
+ The forward pass uses a step function (1 for x >= 0, 0 for x < 0),
271
+ while the backward pass uses a sigmoid-shaped surrogate gradient for
272
+ smooth optimization.
273
+
274
+ The surrogate gradient is defined as:
275
+ g'(x) = alpha * (1 - sigmoid(alpha * x)) * sigmoid(alpha * x)
276
+
223
277
  """
224
278
  return Sigmoid(alpha=alpha)(x)
225
279
 
@@ -238,11 +292,15 @@ class PiecewiseQuadratic(Surrogate):
238
292
  self.alpha = alpha
239
293
 
240
294
  def surrogate_fun(self, x):
241
- z = jnp.where(x < -1 / self.alpha,
242
- 0.,
243
- jnp.where(x > 1 / self.alpha,
244
- 1.,
245
- (-self.alpha * jnp.abs(x) / 2 + 1) * self.alpha * x + 0.5))
295
+ z = jnp.where(
296
+ x < -1 / self.alpha,
297
+ 0.,
298
+ jnp.where(
299
+ x > 1 / self.alpha,
300
+ 1.,
301
+ (-self.alpha * jnp.abs(x) / 2 + 1) * self.alpha * x + 0.5
302
+ )
303
+ )
246
304
  return z
247
305
 
248
306
  def surrogate_grad(self, x):
@@ -260,7 +318,12 @@ def piecewise_quadratic(
260
318
  x: jax.Array,
261
319
  alpha: float = 1.,
262
320
  ):
263
- r"""Judge spiking state with a piecewise quadratic function [1]_ [2]_ [3]_ [4]_ [5]_.
321
+ r"""
322
+ Judge spiking state with a piecewise quadratic function [1]_ [2]_ [3]_ [4]_ [5]_.
323
+
324
+ This function implements a surrogate gradient method for spiking neural networks
325
+ using a piecewise quadratic function. It provides a differentiable approximation
326
+ of the step function used in the forward pass of spiking neurons.
264
327
 
265
328
  If `origin=False`, computes the forward function:
266
329
 
@@ -306,18 +369,29 @@ def piecewise_quadratic(
306
369
  >>> plt.legend()
307
370
  >>> plt.show()
308
371
 
309
- Parameters
372
+ Parameters
310
373
  ----------
311
- x: jax.Array, Array
312
- The input data.
313
- alpha: float
314
- Parameter to control smoothness of gradient
315
-
374
+ x : jax.Array
375
+ The input array representing the neuron's membrane potential.
376
+ alpha : float, optional
377
+ A parameter controlling the steepness of the surrogate gradient.
378
+ Higher values result in a steeper gradient. Default is 1.0.
316
379
 
317
380
  Returns
318
381
  -------
319
- out: jax.Array
320
- The spiking state.
382
+ jax.Array
383
+ An array of the same shape as the input, containing binary values (0 or 1)
384
+ representing the spiking state of each neuron.
385
+
386
+ Notes
387
+ -----
388
+ The function uses different computations for forward and backward passes:
389
+ - Forward: Step function (1 for x >= 0, 0 for x < 0)
390
+ - Backward: Piecewise quadratic function for smooth gradient
391
+
392
+ The surrogate gradient is defined as:
393
+ g'(x) = 0 if |x| > 1/alpha
394
+ -alpha^2|x| + alpha if |x| <= 1/alpha
321
395
 
322
396
  References
323
397
  ----------
@@ -331,11 +405,22 @@ def piecewise_quadratic(
331
405
 
332
406
 
333
407
  class PiecewiseExp(Surrogate):
334
- """Judge spiking state with a piecewise exponential function.
408
+ """
409
+ Judge spiking state with a piecewise exponential function.
410
+
411
+ This class implements a surrogate gradient method for spiking neural networks
412
+ using a piecewise exponential function. It provides a differentiable approximation
413
+ of the step function used in the forward pass of spiking neurons.
414
+
415
+ Parameters
416
+ ----------
417
+ alpha : float, optional
418
+ A parameter controlling the steepness of the surrogate gradient.
419
+ Higher values result in a steeper gradient. Default is 1.0.
335
420
 
336
421
  See Also
337
422
  --------
338
- piecewise_exp
423
+ piecewise_exp : Function version of this class.
339
424
  """
340
425
 
341
426
  def __init__(self, alpha: float = 1.):
@@ -343,16 +428,62 @@ class PiecewiseExp(Surrogate):
343
428
  self.alpha = alpha
344
429
 
345
430
  def surrogate_grad(self, x):
431
+ """
432
+ Compute the surrogate gradient.
433
+
434
+ Parameters
435
+ ----------
436
+ x : jax.Array
437
+ The input array.
438
+
439
+ Returns
440
+ -------
441
+ jax.Array
442
+ The surrogate gradient.
443
+ """
346
444
  dx = (self.alpha / 2) * jnp.exp(-self.alpha * jnp.abs(x))
347
445
  return dx
348
446
 
349
447
  def surrogate_fun(self, x):
350
- return jnp.where(x < 0, jnp.exp(self.alpha * x) / 2, 1 - jnp.exp(-self.alpha * x) / 2)
448
+ """
449
+ Compute the surrogate function.
450
+
451
+ Parameters
452
+ ----------
453
+ x : jax.Array
454
+ The input array.
455
+
456
+ Returns
457
+ -------
458
+ jax.Array
459
+ The output of the surrogate function.
460
+ """
461
+ return jnp.where(
462
+ x < 0,
463
+ jnp.exp(self.alpha * x) / 2,
464
+ 1 - jnp.exp(-self.alpha * x) / 2
465
+ )
351
466
 
352
467
  def __repr__(self):
468
+ """
469
+ Return a string representation of the PiecewiseExp instance.
470
+
471
+ Returns
472
+ -------
473
+ str
474
+ A string representation of the instance.
475
+ """
353
476
  return f'{self.__class__.__name__}(alpha={self.alpha})'
354
477
 
355
478
  def __hash__(self):
479
+ """
480
+ Compute a hash value for the PiecewiseExp instance.
481
+
482
+ Returns
483
+ -------
484
+ int
485
+ A hash value for the instance.
486
+ """
356
487
  return hash((self.__class__, self.alpha))
357
488
 
358
489
 
@@ -363,6 +494,10 @@ def piecewise_exp(
363
494
  ):
364
495
  r"""Judge spiking state with a piecewise exponential function [1]_.
365
496
 
497
+ This function implements a surrogate gradient method for spiking neural networks
498
+ using a piecewise exponential function. It provides a differentiable approximation
499
+ of the step function used in the forward pass of spiking neurons.
500
+
366
501
  If `origin=False`, computes the forward function:
367
502
 
368
503
  .. math::
@@ -403,16 +538,26 @@ def piecewise_exp(
403
538
 
404
539
  Parameters
405
540
  ----------
406
- x: jax.Array, Array
407
- The input data.
408
- alpha: float
409
- Parameter to control smoothness of gradient
410
-
541
+ x : jax.Array
542
+ The input array representing the neuron's membrane potential.
543
+ alpha : float, optional
544
+ A parameter controlling the steepness of the surrogate gradient.
545
+ Higher values result in a steeper gradient. Default is 1.0.
411
546
 
412
547
  Returns
413
548
  -------
414
- out: jax.Array
415
- The spiking state.
549
+ jax.Array
550
+ An array of the same shape as the input, containing binary values (0 or 1)
551
+ representing the spiking state of each neuron.
552
+
553
+ Notes
554
+ -----
555
+ The function uses different computations for forward and backward passes:
556
+ - Forward: Step function (1 for x >= 0, 0 for x < 0)
557
+ - Backward: Piecewise exponential function for smooth gradient
558
+
559
+ The surrogate gradient is defined as:
560
+ g'(x) = (alpha / 2) * exp(-alpha * |x|)
416
561
 
417
562
  References
418
563
  ----------
brainstate/util/_dict.py CHANGED
@@ -24,12 +24,17 @@ import jax
24
24
 
25
25
  from brainstate.typing import Filter, PathParts
26
26
  from ._filter import to_predicate
27
- from ._pretty_repr import PrettyRepr, PrettyType, PrettyAttr, yield_unique_pretty_repr_items, pretty_repr
27
+ from ._pretty_repr import PrettyRepr, PrettyType, PrettyAttr, yield_unique_pretty_repr_items, pretty_repr_object
28
28
  from ._struct import dataclass
29
29
 
30
30
  __all__ = [
31
- 'PrettyDict', 'NestedDict', 'FlattedDict', 'flat_mapping', 'nest_mapping',
32
- 'PrettyList', 'PrettyReprTree',
31
+ 'PrettyDict',
32
+ 'NestedDict',
33
+ 'FlattedDict',
34
+ 'flat_mapping',
35
+ 'nest_mapping',
36
+ 'PrettyList',
37
+ 'PrettyObject',
33
38
  ]
34
39
 
35
40
  A = TypeVar('A')
@@ -41,42 +46,117 @@ ExtractValueFn = abc.Callable[[Any], Any]
41
46
  SetValueFn = abc.Callable[[V, Any], V]
42
47
 
43
48
 
49
+ def _repr_object_general(node: PrettyDict):
50
+ """
51
+ Generate a general representation of a PrettyDict object.
52
+
53
+ This function is used to create a pretty representation of a PrettyDict
54
+ object, which includes the type of the object and its value separator.
44
55
 
56
+ Args:
57
+ node (PrettyDict): The PrettyDict object to be represented.
45
58
 
46
- class PrettyReprTree(PrettyRepr):
59
+ Yields:
60
+ PrettyType: A PrettyType object representing the type of the node,
61
+ with specified value separator, start, and end characters.
47
62
  """
48
- Pretty representation of a tree.
63
+ yield PrettyType(type(node), value_sep='=', start='(', end=')')
64
+
65
+
66
+ def _repr_attribute_general(node):
67
+ """
68
+ Generate a pretty representation of the attributes of a node.
69
+
70
+ This function iterates over the attributes of a given node and attempts
71
+ to generate a pretty representation for each attribute. It handles
72
+ conversion of lists and dictionaries to their pretty representation
73
+ counterparts and yields a PrettyAttr object for each attribute.
74
+
75
+ Args:
76
+ node: The object whose attributes are to be represented.
77
+
78
+ Yields:
79
+ PrettyAttr: A PrettyAttr object representing the key and value of
80
+ each attribute in a pretty format.
81
+ """
82
+ for k, v in vars(node).items():
83
+ try:
84
+ res = node.__pretty_repr_item__(k, v)
85
+ if res is None:
86
+ continue
87
+ k, v = res
88
+ except AttributeError:
89
+ pass
90
+
91
+ if k is None:
92
+ continue
93
+
94
+ # convert list to PrettyList
95
+ if isinstance(v, list):
96
+ v = PrettyList(v)
97
+
98
+ # convert dict to PrettyDict
99
+ if isinstance(v, dict):
100
+ v = PrettyDict(v)
101
+
102
+ # convert PrettyDict to NestedStateRepr
103
+ if isinstance(v, PrettyDict):
104
+ v = NestedStateRepr(v)
105
+
106
+ yield PrettyAttr(k, v)
107
+
108
+
109
+ class PrettyObject(PrettyRepr):
110
+ """
111
+ A class for generating a pretty representation of a tree-like structure.
112
+
113
+ This class extends the PrettyRepr class to provide a mechanism for
114
+ generating a human-readable, pretty representation of tree-like data
115
+ structures. It utilizes custom functions to represent the object and
116
+ its attributes in a structured and visually appealing format.
117
+
118
+ Methods
119
+ -------
120
+ __pretty_repr__: Generates a sequence of pretty representation items
121
+ for the object.
122
+ __pretty_repr_item__: Returns a tuple of the key and value for pretty
123
+ representation of an item in the data structure.
49
124
  """
50
125
 
51
126
  def __pretty_repr__(self):
52
- return yield_unique_pretty_repr_items(
127
+ """
128
+ Generates a pretty representation of the object.
129
+
130
+ This method yields a sequence of pretty representation items for the object,
131
+ using specified functions to represent the object and its attributes.
132
+
133
+ Yields:
134
+ Pretty representation items generated by `yield_unique_pretty_repr_items`.
135
+ """
136
+ yield from yield_unique_pretty_repr_items(
53
137
  self,
54
- repr_object=self._repr_object,
55
- repr_attr=self._repr_attr,
138
+ repr_object=_repr_object_general,
139
+ repr_attr=_repr_attribute_general,
56
140
  )
57
141
 
58
142
  def __pretty_repr_item__(self, k, v):
59
- return k, v
60
-
61
- def _repr_object(self, node: PrettyDict):
62
- yield PrettyType(type(node), value_sep=': ', start='({', end='})')
143
+ """
144
+ Returns a tuple of the key and value for pretty representation.
63
145
 
64
- def _repr_attr(self, node):
65
- for k, v in vars(node).items():
66
- k, v = self.__pretty_repr_item__(k, v)
67
- if k is None:
68
- continue
146
+ This method is used to generate a pretty representation of an item
147
+ in a data structure, typically for debugging or logging purposes.
69
148
 
70
- if isinstance(v, list):
71
- v = PrettyList(v)
149
+ Args:
150
+ k: The key of the item.
151
+ v: The value of the item.
72
152
 
73
- if isinstance(v, dict):
74
- v = PrettyDict(v)
153
+ Returns:
154
+ A tuple containing the key and value.
155
+ """
156
+ return k, v
75
157
 
76
- if isinstance(v, PrettyDict):
77
- v = NestedStateRepr(v)
78
158
 
79
- yield PrettyAttr(repr(k), v)
159
+ PrettyReprTree = PrettyObject
80
160
 
81
161
 
82
162
  # the empty node is a struct.dataclass to be compatible with JAX.
@@ -252,7 +332,7 @@ class PrettyDict(dict, PrettyRepr):
252
332
 
253
333
  def __repr__(self) -> str:
254
334
  # repr the individual object with the pretty representation
255
- return pretty_repr(self)
335
+ return pretty_repr_object(self)
256
336
 
257
337
  def __pretty_repr__(self):
258
338
  yield from yield_unique_pretty_repr_items(self, _default_repr_object, _default_repr_attr)
@@ -789,7 +869,7 @@ class PrettyList(list, PrettyRepr):
789
869
  yield from yield_unique_pretty_repr_items(self, _list_repr_object, _list_repr_attr)
790
870
 
791
871
  def __repr__(self):
792
- return pretty_repr(self)
872
+ return pretty_repr_object(self)
793
873
 
794
874
  def tree_flatten(self):
795
875
  return list(self), ()
@@ -812,4 +892,3 @@ def _list_repr_attr(node: PrettyList):
812
892
 
813
893
  def _list_repr_object(node: PrettyDict):
814
894
  yield PrettyType('', value_sep='', start='[', end=']')
815
-
@@ -25,7 +25,6 @@ from typing import Any, Iterator, Mapping, TypeVar, Union, Callable, Optional, S
25
25
 
26
26
  __all__ = [
27
27
  'yield_unique_pretty_repr_items',
28
- 'pretty_repr',
29
28
  'PrettyType',
30
29
  'PrettyAttr',
31
30
  'PrettyRepr',
@@ -82,10 +81,37 @@ class PrettyRepr(ABC):
82
81
 
83
82
  def __repr__(self) -> str:
84
83
  # repr the individual object with the pretty representation
85
- return pretty_repr(self)
84
+ return pretty_repr_object(self)
86
85
 
87
86
 
88
- def _repr_elem(obj: PrettyType, elem: Any) -> str:
87
+ def pretty_repr_elem(obj: PrettyType, elem: Any) -> str:
88
+ """
89
+ Constructs a string representation of a single element within a pretty representation.
90
+
91
+ This function takes a `PrettyType` object and an element, which must be an instance
92
+ of `PrettyAttr`, and generates a formatted string that represents the element. The
93
+ formatting is based on the configuration provided by the `PrettyType` object.
94
+
95
+ Parameters
96
+ ----------
97
+ obj : PrettyType
98
+ The configuration object that defines how the element should be formatted.
99
+ It includes details such as indentation, separators, and surrounding characters.
100
+ elem : Any
101
+ The element to be represented. It must be an instance of `PrettyAttr`, which
102
+ contains the key and value to be formatted.
103
+
104
+ Returns
105
+ -------
106
+ str
107
+ A string that represents the element in a formatted manner, adhering to the
108
+ configuration specified by the `PrettyType` object.
109
+
110
+ Raises
111
+ ------
112
+ TypeError
113
+ If the provided element is not an instance of `PrettyAttr`.
114
+ """
89
115
  if not isinstance(elem, PrettyAttr):
90
116
  raise TypeError(f'Item must be Elem, got {type(elem).__name__}')
91
117
 
@@ -95,9 +121,32 @@ def _repr_elem(obj: PrettyType, elem: Any) -> str:
95
121
  return f'{obj.elem_indent}{elem.start}{elem.key}{obj.value_sep}{value}{elem.end}'
96
122
 
97
123
 
98
- def pretty_repr(obj: PrettyRepr) -> str:
124
+ def pretty_repr_object(obj: PrettyRepr) -> str:
99
125
  """
100
- Get the pretty representation of an object.
126
+ Generates a pretty string representation of an object that implements the PrettyRepr interface.
127
+
128
+ This function utilizes the __pretty_repr__ method of the PrettyRepr interface to obtain
129
+ a structured representation of the object, which includes both the type and attributes
130
+ of the object in a human-readable format.
131
+
132
+ Parameters
133
+ ----------
134
+ obj : PrettyRepr
135
+ The object for which the pretty representation is to be generated. The object must
136
+ implement the PrettyRepr interface.
137
+
138
+ Returns
139
+ -------
140
+ str
141
+ A string that represents the object in a pretty format, including its type and attributes.
142
+ The format is determined by the PrettyType and PrettyAttr instances yielded by the
143
+ __pretty_repr__ method of the object.
144
+
145
+ Raises
146
+ ------
147
+ TypeError
148
+ If the provided object does not implement the PrettyRepr interface or if the first item
149
+ yielded by the __pretty_repr__ method is not an instance of PrettyType.
101
150
  """
102
151
  if not isinstance(obj, PrettyRepr):
103
152
  raise TypeError(f'Object {obj!r} is not representable')
@@ -110,7 +159,7 @@ def pretty_repr(obj: PrettyRepr) -> str:
110
159
  raise TypeError(f'First item must be PrettyType, got {type(obj_repr).__name__}')
111
160
 
112
161
  # repr attributes
113
- elem_reprs = tuple(map(partial(_repr_elem, obj_repr), iterator))
162
+ elem_reprs = tuple(map(partial(pretty_repr_elem, obj_repr), iterator))
114
163
  elems = ',\n'.join(elem_reprs)
115
164
  if elems:
116
165
  elems = '\n' + elems + '\n'
@@ -153,7 +202,20 @@ class PrettyMapping(PrettyRepr):
153
202
 
154
203
  @dataclasses.dataclass
155
204
  class PrettyReprContext(threading.local):
156
- # seen_modules_repr: set[int] | None = None
205
+ """
206
+ A thread-local context for managing the state of pretty representation.
207
+
208
+ This class is used to keep track of objects that have been seen during
209
+ the generation of pretty representations, preventing infinite recursion
210
+ in cases of circular references.
211
+
212
+ Attributes
213
+ ----------
214
+ seen_modules_repr : dict[int, Any] | None
215
+ A dictionary mapping object IDs to objects that have been seen
216
+ during the pretty representation process. This is used to avoid
217
+ representing the same object multiple times.
218
+ """
157
219
  seen_modules_repr: dict[int, Any] | None = None
158
220
 
159
221
 
@@ -161,10 +223,47 @@ CONTEXT = PrettyReprContext()
161
223
 
162
224
 
163
225
  def _default_repr_object(node):
226
+ """
227
+ Generates a default pretty representation for an object.
228
+
229
+ This function yields a `PrettyType` instance that represents the type
230
+ of the given object. It is used as a default method for representing
231
+ objects when no custom representation function is provided.
232
+
233
+ Parameters
234
+ ----------
235
+ node : Any
236
+ The object for which the pretty representation is to be generated.
237
+
238
+ Yields
239
+ ------
240
+ PrettyType
241
+ An instance of `PrettyType` that contains the type information of
242
+ the object.
243
+ """
164
244
  yield PrettyType(type=type(node))
165
245
 
166
246
 
167
247
  def _default_repr_attr(node):
248
+ """
249
+ Generates a default pretty representation for the attributes of an object.
250
+
251
+ This function iterates over the attributes of the given object and yields
252
+ a `PrettyAttr` instance for each attribute that does not start with an
253
+ underscore. The `PrettyAttr` instances contain the attribute name and its
254
+ string representation.
255
+
256
+ Parameters
257
+ ----------
258
+ node : Any
259
+ The object whose attributes are to be represented.
260
+
261
+ Yields
262
+ ------
263
+ PrettyAttr
264
+ An instance of `PrettyAttr` for each non-private attribute of the object,
265
+ containing the attribute name and its string representation.
266
+ """
168
267
  for name, value in vars(node).items():
169
268
  if name.startswith('_'):
170
269
  continue
@@ -177,7 +276,27 @@ def yield_unique_pretty_repr_items(
177
276
  repr_attr: Optional[Callable] = None
178
277
  ):
179
278
  """
180
- Pretty representation of an object avoiding duplicate representations.
279
+ Generates a pretty representation of an object while avoiding duplicate representations.
280
+
281
+ This function is designed to yield a structured representation of an object,
282
+ using custom or default methods for representing the object itself and its attributes.
283
+ It ensures that each object is only represented once to prevent infinite recursion
284
+ in cases of circular references.
285
+
286
+ Parameters:
287
+ node : Any
288
+ The object to be represented.
289
+ repr_object : Optional[Callable], optional
290
+ A callable that yields the representation of the object itself.
291
+ If not provided, a default representation function is used.
292
+ repr_attr : Optional[Callable], optional
293
+ A callable that yields the representation of the object's attributes.
294
+ If not provided, a default attribute representation function is used.
295
+
296
+ Yields:
297
+ Union[PrettyType, PrettyAttr]
298
+ The pretty representation of the object and its attributes,
299
+ avoiding duplicates by tracking seen objects.
181
300
  """
182
301
  if repr_object is None:
183
302
  repr_object = _default_repr_object
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: brainstate
3
- Version: 0.1.0.post20250211
3
+ Version: 0.1.0.post20250212
4
4
  Summary: A ``State``-based Transformation System for Program Compilation and Augmentation.
5
5
  Home-page: https://github.com/chaobrain/brainstate
6
6
  Author: BrainState Developers
@@ -1,12 +1,12 @@
1
1
  brainstate/__init__.py,sha256=AkZyyFkn4fB8g2aT6Rc2MO1xICPpUZuDtdze-eUQNc0,1496
2
- brainstate/_state.py,sha256=TrlgaX_Hu3aSdkOUqw88HZMKUKM_PgnE9YGp595nfi0,27761
2
+ brainstate/_state.py,sha256=aM2UTfFGvfXfM-pCLvufhgyuuLBGfogBYsz7ZCU8P7Q,28588
3
3
  brainstate/_state_test.py,sha256=rJUFRSXEqrrl4qANRewY9mnDlzSbtHwBIGeZ0ku-8Dg,1650
4
4
  brainstate/_utils.py,sha256=uJ6WWKq3yb05ZdktCQGLWOXsOJveL1H9pR7eev70Jes,1693
5
5
  brainstate/environ.py,sha256=PZnVFWPioUBuWmwCO8wwCKrHQfP3BR-5lYPRl5i5GDA,17698
6
6
  brainstate/environ_test.py,sha256=QD6sPCKNtqemVCGwkdImjMazatrvvLr6YeAVcfUnVVY,2045
7
7
  brainstate/mixin.py,sha256=g7uVUwZphZWsNs9pb48ozG2cDGaj0hs0g3lq8tDk-Sg,11310
8
8
  brainstate/mixin_test.py,sha256=Oq_0fwC9vpXDN4t4dTBhWzLdFDNlcYsrcip14F1yECI,3079
9
- brainstate/surrogate.py,sha256=t4SzVwUVMAPtC-O1vFbuE9F4265wgAv7ud77ufIJsuk,48464
9
+ brainstate/surrogate.py,sha256=xS4UG4LHKUJdHqwZ5-p-9Y2jWXMa-ssdZJCMiW9zi5k,53540
10
10
  brainstate/transform.py,sha256=cxbymTlJ6uHvJWEEYXzFUkAySs_TbUTHakt0NQgWJ3s,808
11
11
  brainstate/typing.py,sha256=Qh-LBzm6oG4rSXv4V5qB8SNYcoOR7bASoK_iQxnlafk,10467
12
12
  brainstate/augment/__init__.py,sha256=zGPq1eTB_56GRCNC9TiPLKTw07PA2O0OCi7bgjYIrY4,1193
@@ -109,16 +109,16 @@ brainstate/random/_rand_state.py,sha256=nuoQ8GU1MfJPRNN-ZmRQsggVjoyPhaEdZmwM7_4-
109
109
  brainstate/random/_random_for_unit.py,sha256=kGp4EUX19MXJ9Govoivbg8N0bddqOldKEI2h_TbdONY,2057
110
110
  brainstate/util/__init__.py,sha256=-FWEuSKXG3mWxYphGFAy3UEuVe39lFs1GruluzdXDoI,1502
111
111
  brainstate/util/_caller.py,sha256=T3bzu7-09r-6EOrU6Muca_aMXSQua_X2lXjEqb-w39w,2782
112
- brainstate/util/_dict.py,sha256=tb5nPrTKJe4G_BDv33XYTUaYQDz6od-5psG4TKemc7A,28111
112
+ brainstate/util/_dict.py,sha256=qPUbqjRVHUvVHhSWBPojx_srsh6-iy1k5oPMn1DdrnQ,30880
113
113
  brainstate/util/_dict_test.py,sha256=Dn0TdjX6wLBXaTD4jfYTu6cKfFHwKSxi4_3bX7kB_IA,5621
114
114
  brainstate/util/_error.py,sha256=eyZ8PGFixqe2K5OEfjSDzI-2tU0ieYQoUpBP7yStlPQ,878
115
115
  brainstate/util/_filter.py,sha256=1-bvFHdjeehvXeHTrCEp8xr25lopKe8d3XZGCNegq0s,4970
116
116
  brainstate/util/_others.py,sha256=jsPZwP-v_5HRV-LB5F0NUsiqr04y8bmGIsu_JMyVcbQ,14762
117
- brainstate/util/_pretty_repr.py,sha256=vNwRlj4sI4QJ_koyIs7eKdUMeB_QWwzRYsE8PpAWN3g,5833
117
+ brainstate/util/_pretty_repr.py,sha256=-TZPIgfTLB-Eg7rgT7KAkV1r-HX0q6nCgKDKA7Qdsw4,10577
118
118
  brainstate/util/_scaling.py,sha256=pc_eM_SZVwkY65I4tJh1ODiHNCoEhsfFXl2zBK0PLAg,7562
119
119
  brainstate/util/_struct.py,sha256=KMMHcshOM20gYhSahNzWLxsTt-Rt3AeX3Uz26-rP9vI,17619
120
- brainstate-0.1.0.post20250211.dist-info/LICENSE,sha256=VZe9u1jgUL2eCY6ZPOYgdb8KCblCHt8ECdbtJid6e1s,11550
121
- brainstate-0.1.0.post20250211.dist-info/METADATA,sha256=werv_oEsECW5xLgvO__Yjth5vLfz-YARh442Q6E6FIk,3585
122
- brainstate-0.1.0.post20250211.dist-info/WHEEL,sha256=bb2Ot9scclHKMOLDEHY6B2sicWOgugjFKaJsT7vwMQo,110
123
- brainstate-0.1.0.post20250211.dist-info/top_level.txt,sha256=eQbGgKn0ptx7FDWuua0V0wr4K1VHi2iOUCYo3fUQBRA,11
124
- brainstate-0.1.0.post20250211.dist-info/RECORD,,
120
+ brainstate-0.1.0.post20250212.dist-info/LICENSE,sha256=VZe9u1jgUL2eCY6ZPOYgdb8KCblCHt8ECdbtJid6e1s,11550
121
+ brainstate-0.1.0.post20250212.dist-info/METADATA,sha256=OVPO4wr0e0j_Lvk_OQKTpTdNUbOGsFt_BW_qKakO8xE,3585
122
+ brainstate-0.1.0.post20250212.dist-info/WHEEL,sha256=bb2Ot9scclHKMOLDEHY6B2sicWOgugjFKaJsT7vwMQo,110
123
+ brainstate-0.1.0.post20250212.dist-info/top_level.txt,sha256=eQbGgKn0ptx7FDWuua0V0wr4K1VHi2iOUCYo3fUQBRA,11
124
+ brainstate-0.1.0.post20250212.dist-info/RECORD,,