EvenNumberGen.rst 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. Hierarchical Even Number Generator
  2. ==================================
  3. Assuming you have seen the basics from the :doc:`SinGen`, this
  4. section will describe a simplistic even number generator, using
  5. hierarchical CBD modelling.
  6. At every timestep in the model, the generator is required to
  7. output its double. We can split it up into two components: a
  8. :class:`CBD.lib.std.TimeBlock` and a :code:`Double` CBD class,
  9. which computes the double of its input. The generator block
  10. can be constructed just like the :code:`SinGen` block was created
  11. in the :doc:`SinGen` example:
  12. .. code-block:: python
  13. from CBD.Core import CBD
  14. from CBD.lib.std import TimeBlock
  15. class EvenNumberGen(CBD):
  16. def __init__(self, name="EvenNumberGen"):
  17. CBD.__init__(self, name, input_ports=[], output_ports=["OUT1"])
  18. self.addBlock(TimeBlock("time"))
  19. self.addBlock(Double("double"))
  20. self.addConnection("time", "double", output_port_name='OUT1',
  21. input_port_name='IN1')
  22. self.addConnection("double", "OUT1", output_port_name='OUT1')
  23. numGen = EvenNumberGen("NumGen")
  24. Now, we're left with the construction of the :code:`Double` block, which basically
  25. multiplies its input with 2:
  26. .. code-block:: python
  27. from CBD.lib.std import ProductBlock, ConstantBlock
  28. class Double(CBD):
  29. def __init__(self, name="Double"):
  30. CBD.__init__(self, name, input_ports=["IN1"], output_ports=["OUT1"])
  31. # Create the blocks
  32. self.addBlock(ConstantBlock("two", 2))
  33. self.addBlock(ProductBlock("mult"))
  34. # Connect the blocks
  35. # Default ports are "INx" and "OUT1", with 'x' the index of the connection
  36. self.addConnection("two", "mult")
  37. self.addConnection("IN1", "mult")
  38. self.addConnection("mult", "OUT1")
  39. And that's it. Now your models can have hierarchy!
  40. Flattening
  41. ----------
  42. Of course, when building highly hierarchical models, it may be useful to be able to
  43. create a full model, ignoring all hierarchical model conceptions. Flattening is the
  44. reverse of hierarchical composition. By calling the :func:`CBD.Core.CBD.flatten`
  45. method, the CBD model will be transformed into a single CBD model without hierarchy.