Python Representation of RVs
I wanted to use Python to define a random variable in a pythonic way. That way, I could intuitively work with random variables from within python and potentially even use some of Python's more powerful language features in conjunction with these random variables.
x[1]
x[1, {'y':2, 'z':3}]
- rv.py
def rv(distFunc): class RV(object): def __init__(self, obj): self.obj = obj; def __hash__(self): return distFunc.__hash__(); def __eq__(self, other): return self.__hash__() == other.__hash__(); def __getitem__(self, key): # Case: x[1] ==> P(X=1) if key.__class__ is int: return distFunc(self.obj, key); # Case: x[1, {'y':2, 'z':3}] ==> P(X=1 | Y=2, Z=3) elif key[1].__class__ is dict: return distFunc(self.obj, key[0], key[1]); else: raise TypeError, """Invalid arguments.\n Valid format: x[1] ==> P(X=1) x[1, {'y':2, 'z':3}] ==> P(X=1 | Y=2, Z=3)"""; return property(RV);
- rv_example.py
class C(object): @rv def y(self, _y, *_cond): return .4; @rv def x(self, _x, *_cond): if len(_cond) <= 0: return .5; else: return .5*self.y[_cond[0][self.y]];
You could leave a comment if you were logged in.