PageRenderTime 26ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/python/bashwork/statistics/distribution/truthtable.py

https://github.com/bashwork/common
Python | 43 lines | 39 code | 1 blank | 3 comment | 0 complexity | ec174cd79e955d4d2a5d710fe3d3a935 MD5 | raw file
Possible License(s): GPL-2.0
  1. import pandas as pd
  2. class TruthTable(object):
  3. ''' A simple implementation of a truth table
  4. that can be used as follows::
  5. table = TruthTable([[0,0,0],[0,1,0],[1,0,0], [1,1,1]], ['a', 'b', 'y'])
  6. table(a=1, b=1) # True
  7. table(a=1, b=0) # False
  8. table(a=0, b=0) # False
  9. '''
  10. def __init__(self, table, labels):
  11. ''' Initialize a new instance of a TruthTable.
  12. The supplied table can be an array like value or
  13. a pandas DataFrame which will be used directly.
  14. :param table: The table of values to map to a frame
  15. :param labels: The labels to assign to the table
  16. '''
  17. if not isinstance(table, pd.DataFrame)
  18. self.table = pd.DataFrame(table, columns=labels)
  19. else: self.table = table
  20. def get(self, *args, **kwargs):
  21. ''' Retrieve the probability of the specified conditions::
  22. dist.get(A=1, B=1) # probability that X is 1
  23. dist.get(1,2,3) # probability that X is 1, 2, or 3
  24. dist.get(X=3) # probability that X is 3
  25. :param args: The variables to test
  26. :param kwargs: The named variable to test (only matching name)
  27. :returns: The joint probability of the variables
  28. '''
  29. method = lambda B, n: B[B[n[0]] == n[1]].drop(n[0], axis=1)
  30. values = reduce(method, kwargs.items(), self.table)
  31. return bool(values.irow(0)) if len(values) == 1 else TruthTable(values)
  32. def __str__(self): return str(self.table)
  33. __repr__ = __str__
  34. __call__ = get