fvutils/pyvsc

constraint for one hot encoding.

Opened this issue · 1 comments

I have a class with variables a,b,c,d,e,f and want to set a constraint that anyone can be 1 at a given time.
I tried

@vsc_constraint
def abc(self):                                                                                                                                                                    
   expt=[self.a.val,self.b.val,self.c.val,self.d.val,self.e.val,self.f.val]                                                                                                  
   s=   sum(expt)                                                                                                                                                                  
   print(s,expt)                                                                                                                                                                   
   return s<2    

This did not work and multiple bits were set.
test.zip

is there a pythonic way of achieving the required constraint?
MWE attached.

Yeah, I think the @vsc_constraint decorator tries to override as many operators as possible to give you SV-like constraints, but just b/c you can put things in that function doesn't mean the decorator will handle it or execute as a normal function.

There aren't any examples in the docs for rand_list_t or randsz_list_t, but there is a sum property you can use to get the desired effect. Edit: My bad, there are examples. I was misreading the docs search bar results.
https://fvutils.github.io/pyvsc/reference.html#vsc.types.list_t

To give each element in rand_list_t a name like a,b,c,... I just assigned it in post_randomize. Maybe there's a clearer way to do it in the init, but I don't think the rand_list_t elements exist before calling randomize. The unit tests have more examples than the docs, so it can be a good to peruse.
https://github.com/fvutils/pyvsc/tree/master/ve/unit

Here's my take on your example. I left debug=True on the randomize since it can be helpful knowing what constraints were actually generated.

import vsc

@vsc.randobj
class bist_constraints:

    def __init__(self):
        self.vars = vsc.rand_list_t(vsc.rand_bit_t(1), 6)

    @vsc.constraint
    def abc(self):
        self.vars.sum < 2

    def post_randomize(self):
        self.a = self.vars[0]
        self.b = self.vars[1]
        self.c = self.vars[2]
        self.d = self.vars[3]
        self.e = self.vars[4]
        self.f = self.vars[5]

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        return f'{[self.a,self.b,self.c,self.d,self.e,self.f]}'

if __name__ == "__main__":
    cfg=bist_constraints()
    cfg.randomize(debug=True)
    print(str(cfg))
    print(cfg.a)