brainpy / BrainPy

Brain Dynamics Programming in Python
https://brainpy.readthedocs.io/
GNU General Public License v3.0
531 stars 94 forks source link

Support tracing ``Variable`` during computation and compilation by using ``tracing_variable()`` function #472

Closed chaoming0625 closed 1 year ago

chaoming0625 commented 1 year ago

Flax and other libraries support object-oriented (OO) programming by providing variable tracing during computation and transformations. On the contrary, BrainPy is designed to be Pythonic, and its OO interface supports tracing variables before transformations. Now, we are excited that BrainPy also supports tracing variables during transformations.

Particularly, we provide .tracing_variable().

Here is the usage example::

      class Example(bm.BrainPyObject):
         def fun(self):
           # The first time of calling `.fun()`, this line will create a Variable instance.
           # If users repeatedly call `.fun()` function, this line will not initialize variables again.
           # Instead, it will return the variable has been created.
           self.tracing_variable('a', bm.zeros, (10,))

           # The created variable can be accessed with self.xxx
           self.a.value = bm.ones(10)

           # Calling this function again will not reinitialize the
           # variable again, Instead, it will return the variable
           # that has been created.
           a = self.tracing_variable('a', bm.zeros, (10,))
chaoming0625 commented 1 year ago

@ztqakita This functionality will resolve the problem in STDP models.

chaoming0625 commented 1 year ago

To solve issue #471