mciepluc / cocotb-coverage

Functional Coverage and Constrained Randomization Extensions for Cocotb
BSD 2-Clause "Simplified" License
100 stars 15 forks source link

Using randomize() or randomize_with() in list comprehension doesn't work #77

Closed shareefj closed 9 months ago

shareefj commented 2 years ago

Any idea why I can't generate a list of randomized transactions using the following?

from cocotb_coverage.crv import Randomized

class Test(Randomized):
    def __init__(self):
        Randomized.__init__(self)
        self.x = 0
        self.y = 0

        self.add_rand("x", list(range(10)))
        self.add_rand("y", list(range(20)))

        def c_constraint(x):
            return x == 4

        self.add_constraint(c_constraint)

    def __repr__(self):
        return f"x={self.x} y={self.y}"

if __name__ == "__main__":

    print("this works")
    tests = []
    for _ in range(10):
        t = Test()
        t.randomize_with(lambda x: 1 <= x <= 4)
        tests.append(t)
    print(tests)

    print("\nthis doesn't")
    tests = [Test().randomize_with(lambda x: 1 <= x <= 4) for _ in range(10)]
    print(tests)

    print("\nnor this")
    tests = [t.randomize_with(lambda x: 1 <= x <= 4) for t in [Test() for _ in range(10)]]
    print(tests)

results in:

this works
[x=1 y=15, x=1 y=19, x=4 y=4, x=3 y=4, x=4 y=5, x=4 y=16, x=1 y=19, x=2 y=19, x=1 y=18, x=2 y=6]

this doesn't
[None, None, None, None, None, None, None, None, None, None]

nor this
[None, None, None, None, None, None, None, None, None, None]
mciepluc commented 2 years ago

@shareefj This is because you need to run randomize_with on the object you are randomizing. What is in the examples that does not work, is that you basically override the "tests" list. With the copy. In a different code that's what you are doing:

tests = [Test() for _ in range(10)]
tests = list(map(Test.randomize_with, tests))

What you should do:

tests = [Test() for _ in range(10)]
map(Test.randomize_with, tests)
mciepluc commented 9 months ago

@shareefj Please let me know if the issue is resolved. I added a testcase describing your problem. https://github.com/mciepluc/cocotb-coverage/blob/cf465b592da6af92f75bd38ebc75b80cb05cc0be/tests/test_crv/crv_test.py#L489-L523

shareefj commented 9 months ago

Sorry, been a long time since I looked at this. I'll accept your answer. Cheers.