├── .idlerc ├── breakpoints.lst └── recent-files.lst ├── README.md ├── brml ├── .idlerc │ ├── breakpoints.lst │ └── recent-files.lst ├── AssignmentToIndex.py ├── AssignmentToIndex.pyc ├── IndexToAssignment.py ├── IndexToAssignment.pyc ├── __init__.py ├── __init__.pyc ├── condpot.py ├── condpot.pyc ├── dag.py ├── dag.pyc ├── intersect.py ├── intersect.pyc ├── ismember.py ├── ismember.pyc ├── multpots.py ├── multpots.pyc ├── myzeros.py ├── myzeros.pyc ├── orderpot.py ├── orderpot.pyc ├── potential │ ├── .idlerc │ │ ├── breakpoints.lst │ │ └── recent-files.lst │ ├── __init__.py │ ├── __init__.pyc │ ├── potential.py │ ├── potential.py_bak │ └── potential.pyc ├── potvariables.py ├── potvariables.pyc ├── setminus.py ├── setminus.pyc ├── setpot.py ├── setpot.pyc ├── setstate.py ├── setstate.pyc ├── subv2ind.py ├── subv2ind.pyc └── variable │ ├── __init__.py │ ├── __init__.pyc │ ├── variable.py │ └── variable.pyc ├── demo ├── demoBurglar.py ├── demoBurglar.pyc ├── demoClouseau.py └── demoClouseau.pyc ├── proposal ├── 10.1.1.66.8598.pdf ├── SOCIS2013proposal.docx ├── datastructure.jpg ├── datastructure.png └── proposal ├── test ├── orderpotTest.py ├── potentialTest.py └── potvariablesTest.py └── test_class.py /.idlerc/breakpoints.lst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/.idlerc/breakpoints.lst -------------------------------------------------------------------------------- /.idlerc/recent-files.lst: -------------------------------------------------------------------------------- 1 | E:\Github\PyBRML\demoClouseau.py 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SOCIS 2013 Proposal 2 | ====== 3 | Framework construction and application to real-world inference problem 4 | ------- 5 | 6 | The goal of this project would be to implement an efficient and object-oriented framework for Python version of BRML toolbox. BRML toolbox is developed under MATLAB and offered various demos related to Bayesian Reasoning and Machine Learning. The toolbox is affiliated to a recent well-designed book by David Barber, Reader from Computer Science Department in University College London(UCL). 7 | 8 | The significance for our PyBRML work can be emphasized in two ways: 9 | 10 | * Bayesian reasoning and probabilistic graphical model is a unified framework for building expert system in order to solve real-world problems. 11 | * Currently, no actively-developing toolbox for bayesian reasoning and probabilistic graphical model under Python exists. Our PyBRML would benefits both the book readers, engineers and researchers who prefer Python as well. 12 | 13 | The BRML toolbox offered algorithms for various topics, such as Bayesian reasoning, machine learning, dynamic systems and approximate inference etc. The current framework in BRML is summarized below: 14 | 15 | https://github.com/pythonroar/PyBRML/blob/master/proposal/datastructure.png 16 | 17 | In SOCIS 2013, most importantly, we will focus on the Bayesian reasoning and probabilistic graphical model section since it provides probabilistic modeling which is fundamental for probabilistic machine learning and dynamical models and further approximate inference. 18 | 19 | Roadmap 20 | ------- 21 | The First Step of this project is to create a framework for BRML toolbox in Python corresponding to MATLAB version. On the Bayesian reasoning and probabilistic graphical model part, there are about 10 standalone functions for graph theory, 30 for potential manipulation and 20 for inference. Thanks to the demos(ie. demoClouseau, demoBurglar, demoMRFclean, demoMostProbablePath, demoShortestPath, demoSumprod, demoMaxprod, demoBucketElim etc.) offered by BRMLtoolbox, we will conduct our implementation based on the demos one by one. Finally make the inference algorithms such as factor graph and junction tree accessible for solving problems. 22 | 23 | Further Steps of the project would then consists two directions: 24 | 25 | * Develop visualization library for Bayesian reasoning and probabilistic graphical model based on matplotlib library, corresponding to miscellaneous functions in BRML toolbox. 26 | * Follow the AAAI’00 paper on Bayesian Fault Detection and Diagnosis in Dynamic System, make a throughout tutorial on solving real-world problems such as engine monitoring and diagnosis. 27 | 28 | Basic Requirements: 29 | ------- 30 | 31 | * Basic background in machine learning and probabilistic graphical model. 32 | * Former experience with both MATLAB and Python. 33 | * Familiar with basic software engineering techniques such as version control and doctest. 34 | 35 | References: 36 | ------- 37 | 38 | * The BRML Matlab package manual 39 | http://web4.cs.ucl.ac.uk/staff/D.Barber/textbook/brml_package.pdf 40 | * Engine Diagnosis paper 41 | U. Lerner, R. Parr, D. Koller, and G. Biswas. Bayesian Fault Detection and Diagnosis in Dynamic Systems. In Proceedings of the Seventeenth National Conference on Artificial Intelligence (AIII-00), pages 531-537, 2000. 42 | * NASA funding research on diagnostics 43 | http://ti.arc.nasa.gov/tech/dash/diagnostics-and-prognostics/ 44 | 45 | 46 | PyBRML Toolbox 47 | ====== 48 | 49 | PyBRML is a Python version of BRML toolbox for Bayesian Reasoning and Machine Learning 50 | 51 | Thanks to Dr. David Barber's book Bayesian Reasoning and Machine Learning and his original design of the toolbox as an accompanying code for the book. 52 | 53 | 54 | Book 55 | ------- 56 | ![Bayesian Reasoning and Machine Learning](http://web4.cs.ucl.ac.uk/staff/D.Barber/textbook/jacket.gif) 57 | 58 | @BOOK{barberBRML2012, 59 | author = {Barber, D.}, 60 | title= {{Bayesian Reasoning and Machine Learning}}, 61 | publisher = {{Cambridge University Press}}, 62 | year = 2012} 63 | 64 | website for the book: 65 | 66 | http://www.cs.ucl.ac.uk/staff/d.barber/brml/ 67 | 68 | Motivation from David: 69 | 70 | The BRMLtoolbox is provided to help readers see how mathematical models translate into actual MAT- 71 | LAB code. There are a large number of demos that a lecturer may wish to use or adapt to help illustrate 72 | the material. In addition many of the exercises make use of the code, helping the reader gain confidence 73 | in the concepts and their application. Along with complete routines for many Machine Learning methods, 74 | the philosophy is to provide low level routines whose composition intuitively follows the mathematical description 75 | of the algorithm. In this way students may easily match the mathematics with the corresponding 76 | algorithmic implementation. 77 | 78 | 79 | History 80 | ------- 81 | 82 | Former MATLAB implementation of BRML Toolbox include: 83 | 84 | * Object Oriented Version (OO) 85 | * Older (non-OO) 86 | 87 | Check these two version from Dr. David Barber's Homepage: 88 | 89 | http://web4.cs.ucl.ac.uk/staff/D.Barber/pmwiki/pmwiki.php?n=Brml.Software 90 | 91 | Contribution 92 | ------- 93 | The source code is hosted on GitHub and comments, suggestions and contributions are welcomed. 94 | If you use BRML toolbox in your work, please cite the reference book. 95 | 96 | License 97 | ------- 98 | The Python version of BRML toolbox library is available under a GNU license. 99 | 100 | Bundled dependencies 101 | ------- 102 | * Numpy 103 | * matplotlib 104 | 105 | Documentation 106 | ------- 107 | Under construction 108 | 109 | Community 110 | ------- 111 | Under construction 112 | 113 | Reference 114 | ------- 115 | @BOOK{barberBRML2012, 116 | author = {Barber, D.}, 117 | title= {{Bayesian Reasoning and Machine Learning}}, 118 | publisher = {{Cambridge University Press}}, 119 | year = 2012} 120 | 121 | 122 | 123 | 124 | 125 | 126 | -------------------------------------------------------------------------------- /brml/.idlerc/breakpoints.lst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/.idlerc/breakpoints.lst -------------------------------------------------------------------------------- /brml/.idlerc/recent-files.lst: -------------------------------------------------------------------------------- 1 | E:\Github\PyBRML\brml\setminus.py 2 | E:\Github\PyBRML\brml\ismember.py 3 | E:\Github\PyBRML\brml\setstate.py 4 | E:\Github\PyBRML\brml\myzeros.py 5 | -------------------------------------------------------------------------------- /brml/AssignmentToIndex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Author: Mingjun Zhou 5 | # Licence: BSD 3 clause 6 | 7 | 8 | import numpy as np 9 | 10 | 11 | def AssignmentToIndex(assignment, dim): 12 | I = 0 13 | for i, a in enumerate(assignment): 14 | I += a * int(np.prod(dim[i+1:])) 15 | return I 16 | -------------------------------------------------------------------------------- /brml/AssignmentToIndex.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/AssignmentToIndex.pyc -------------------------------------------------------------------------------- /brml/IndexToAssignment.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Author: Mingjun Zhou 5 | # Licence: BSD 3 clause 6 | 7 | 8 | import numpy as np 9 | 10 | 11 | def IndexToAssignment(index, dim): 12 | A = [] 13 | for i, d in enumerate(dim): 14 | A.append(index / int(np.prod(dim[i+1:]))) 15 | index = index % int(np.prod(dim[i+1:])) 16 | return A 17 | -------------------------------------------------------------------------------- /brml/IndexToAssignment.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/IndexToAssignment.pyc -------------------------------------------------------------------------------- /brml/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # http://stackoverflow.com/questions/5134893/importing-python-classes-from-different-files-in-a-subdirectory 4 | # __all__ = ['MyClass01','MyClass02'] 5 | 6 | from .potential import potential 7 | from .variable import variable 8 | from multpots import multpots 9 | from dag import dag 10 | from intersect import intersect 11 | from setminus import setminus 12 | from myzeros import myzeros 13 | from ismember import ismember 14 | from setstate import setstate 15 | from setpot import setpot 16 | 17 | 18 | __all__ = ['potential', 19 | 'variable', 20 | 'multpots', 21 | 'dag', 22 | 'intersect', 23 | 'setminus', 24 | 'myzeros', 25 | 'ismember', 26 | 'setpot', 27 | 'setstate'] -------------------------------------------------------------------------------- /brml/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/__init__.pyc -------------------------------------------------------------------------------- /brml/condpot.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | %CONDPOT Return a potential conditioned on another variable 5 | % newpot = condpot(pot,x,y) 6 | % condition the potential to return potential with distribution p(x|y), summing over 7 | % remaining variables. If y is empty (or missing), return the marginal p(x) 8 | % If both x and y are missing, just return the normalised table 9 | """ 10 | import numpy as np 11 | from .potential import potential 12 | from intersect import intersect 13 | from setminus import setminus 14 | 15 | def condpot(pot,varargin): 16 | #FIXME: only 1 varargin supported , use *arg in further development 17 | newpot = potential() 18 | y = [] 19 | x = varargin 20 | #print "pot.variables:", pot.variables 21 | #print "pot.table: \n", pot.table 22 | #print "x:", x 23 | #print "pot.variables:", pot.variables 24 | # convert variable to idx (not consistent in Python other than MATLAB) 25 | intersection, ix, ipot = intersect(x, pot.variables) 26 | #print "intersection=", intersection 27 | newpot.variables = intersection 28 | #print "pot.variables:", pot.variables 29 | FULL_axis = np.arange(pot.variables.size) 30 | #print pot.variables 31 | #print intersection 32 | axis_intersection = ipot 33 | #.index(intersection) 34 | other_axis = setminus(FULL_axis,axis_intersection) 35 | #print "axis_intersection=", axis_intersection 36 | #print "other_axis=", other_axis 37 | #print "Full_axis:", FULL_axis 38 | #print "other_axis:", other_axis 39 | newpot.table = np.apply_over_axes(np.sum, pot.table, other_axis) 40 | #print "newpot.variables:", newpot.variables 41 | #print "newpot.table: \n", newpot.table 42 | 43 | SUM = potential() 44 | SUM.variables = np.array([]) 45 | SUM.table = np.sum(newpot.table) 46 | #print "newpot.table:", newpot.table 47 | #print "SUM.table:", SUM.table 48 | newpot = newpot/SUM 49 | 50 | return newpot 51 | -------------------------------------------------------------------------------- /brml/condpot.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/condpot.pyc -------------------------------------------------------------------------------- /brml/dag.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | DAG Return the adjacency matrix (zeros on diagonal) for a Belief Newtork 5 | A=dag(pot) 6 | 7 | Assumes that pot{i} contains the distribution p(i|pa(i)) 8 | """ 9 | import numpy as np 10 | 11 | def dag(pot): 12 | vars = np.array([]) 13 | for p in range(len(pot)): 14 | vars = np.append(vars, pot[p].variables) 15 | print "variables:", vars 16 | #FIX ME in MATLAB version in case the index are not [1,2,....] 17 | N = len(np.unique(vars)) 18 | print "number of variables:", N 19 | A = np.zeros((N,N)) 20 | print "empty DAG matrix: \n", A 21 | for p in range(len(pot)): 22 | A[pot[p].variables,p] = 1 23 | eye = np.identity(N) 24 | A = A - A*eye; 25 | return A -------------------------------------------------------------------------------- /brml/dag.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/dag.pyc -------------------------------------------------------------------------------- /brml/intersect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | same as intersect(a,b) in MATLAB 5 | return the intersect set of set1 and set2 6 | """ 7 | import numpy as np 8 | from ismember import ismember 9 | 10 | 11 | def intersect(a,b): 12 | a = np.array(a) 13 | b = np.array(b) 14 | #print "intersect-a:", a.size 15 | #print "intersect-b:", b.size 16 | #print "intersecting..... \n", 17 | intersect = np.intersect1d(b,a) 18 | dummy, iA = ismember(intersect, a) 19 | dummy, iB = ismember(intersect, b) 20 | #print "intersect", intersect 21 | return intersect, iA, iB 22 | -------------------------------------------------------------------------------- /brml/intersect.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/intersect.pyc -------------------------------------------------------------------------------- /brml/ismember.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | same as ismember() in MATLAB 5 | tf: TRUE or FALSE 6 | index: the index for each A in B 7 | A[tf] == B[index] 8 | """ 9 | import numpy as np 10 | 11 | def ismember(a, b): 12 | #print "judge ismember......" 13 | #FIXME: data format needed to be unified 14 | aa = a 15 | a = np.array(a) 16 | b = np.array(b) 17 | #print "a:", a 18 | #print "b:", b 19 | #print "unifying the format......" 20 | #print "a.ndim =", a.ndim 21 | #print "b.ndim =", b.ndim 22 | if a.ndim != b.ndim: 23 | a = np.array([aa]) 24 | #print "a:", a 25 | #print "b:", b 26 | tf = np.in1d(a,b) # for newer versions of numpy(v1.4+) 27 | # tf = np.array([i in b for i in a]) # for older versions of numpy 28 | u = np.unique(a[tf]) 29 | index = np.array([(np.where(b == i))[0][-1] if t else 0 for i,t in zip(a,tf)]) 30 | return tf, index 31 | -------------------------------------------------------------------------------- /brml/ismember.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/ismember.pyc -------------------------------------------------------------------------------- /brml/multpots.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | MULTPOTS Multiply potentials into a single potential 5 | newpot = multpots(pots) 6 | 7 | multiply potentials : pots is a cell of potentials 8 | potentials with empty tables are ignored 9 | if a table of type 'zero' is encountered, the result is a table of type 10 | 'zero' with table 0, and empty variables. 11 | """ 12 | 13 | 14 | def multpots(pots): 15 | # import copy 16 | newpot = pots[0] 17 | for i in range(1, len(pots)): # loop over all the potentials 18 | #FIX ME: did not check dimension consistency 19 | newpot = newpot*pots[i] 20 | return newpot 21 | -------------------------------------------------------------------------------- /brml/multpots.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/multpots.pyc -------------------------------------------------------------------------------- /brml/myzeros.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | same as myzeros() in MATLAB 5 | MYZEROS same as zeros(x) but if x is a scalar interprets as zeros([x 1]) 6 | """ 7 | import numpy as np 8 | 9 | def myzeros(x): 10 | print "x =", x 11 | x = np.array(x) 12 | if x.size > 1: 13 | out=np.zeros(x) 14 | else: 15 | out=np.zeros((x,1)) 16 | return out 17 | -------------------------------------------------------------------------------- /brml/myzeros.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/myzeros.pyc -------------------------------------------------------------------------------- /brml/orderpot.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Author: Mingjun Zhou 5 | # Licence: BSD 3 clause 6 | 7 | 8 | import numpy as np 9 | import copy 10 | from IndexToAssignment import IndexToAssignment 11 | from potential import potential 12 | 13 | 14 | def orderpot(pot, varargin): 15 | """ 16 | Return potential with variables reordered according to orderpot. If order 17 | is missing or empty, the variables are sorted (low to high). 18 | newpot = orderpot(pot, ) 19 | 20 | Parameters 21 | ---------- 22 | 23 | pot: brml.potential.potential object 24 | An object with fileds variables and table. 25 | pot.variables is a list of integer that indicates variables's name. 26 | pot.table is a np.ndarray of probability distribution. 27 | 28 | varargin: array_like (optional) 29 | An array_like of new orders. 30 | If varagin is missing or empty, the variables are sorted (low to high) 31 | 32 | Returns 33 | ------- 34 | 35 | newpot: brml.potential.potential 36 | the new potential object 37 | """ 38 | if not pot: 39 | return 40 | 41 | oldvs = list(pot.variables) 42 | oldta = pot.table 43 | oldns = list(oldta.shape) 44 | 45 | if not varargin: # varargin is empty or missing 46 | varargin = copy.deepcopy(oldvs) 47 | varargin.sort() 48 | 49 | newvs = list(varargin) 50 | newta = copy.deepcopy(oldta) 51 | newta.resize(np.prod(oldns)) 52 | newns = copy.deepcopy(oldns) 53 | 54 | newInold_idx = [] 55 | oldInnew_idx = [] 56 | for i, v in enumerate(newvs): 57 | idx = oldvs.index(v) 58 | newInold_idx.append(idx) 59 | oldInnew_idx.append(newvs.index(oldvs[i])) 60 | newns[i] = oldns[idx] 61 | 62 | for i in range(np.prod(oldns)): 63 | newass = IndexToAssignment(i, newns) 64 | 65 | oldass = [newass[j] for j in oldInnew_idx] 66 | newta[i] = oldta[tuple(oldass)] 67 | 68 | newta.resize(newns) 69 | newpot = potential(None, None) 70 | newpot.variables = newvs 71 | newpot.table = newta 72 | 73 | return newpot 74 | -------------------------------------------------------------------------------- /brml/orderpot.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/orderpot.pyc -------------------------------------------------------------------------------- /brml/potential/.idlerc/breakpoints.lst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/potential/.idlerc/breakpoints.lst -------------------------------------------------------------------------------- /brml/potential/.idlerc/recent-files.lst: -------------------------------------------------------------------------------- 1 | E:\Github\PyBRML\brml\potential\potential.py 2 | -------------------------------------------------------------------------------- /brml/potential/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # http://stackoverflow.com/questions/5134893/importing-python-classes-from-different-files-in-a-subdirectory 4 | # __all__ = ['MyClass01','MyClass02'] 5 | 6 | from .potential import potential 7 | 8 | __all__ = ['potential'] -------------------------------------------------------------------------------- /brml/potential/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/potential/__init__.pyc -------------------------------------------------------------------------------- /brml/potential/potential.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | "Basic Class: potential" 4 | if __name__ == '__main__': 5 | print 'PotentialClass is running by itself' 6 | else: 7 | print 'PotentialClass is imported as module' 8 | 9 | import numpy as np 10 | import copy 11 | from brml.intersect import intersect 12 | from brml.ismember import ismember 13 | from brml.IndexToAssignment import IndexToAssignment 14 | 15 | 16 | class potential: 17 | def __init__(self, variables=np.array([]), card=np.array([]), 18 | table=np.array([])): 19 | self.variables = variables 20 | self.card = card 21 | self.table = table 22 | 23 | def __mul__(self, other): 24 | # check for empty potential 25 | if self.variables.size == 0: 26 | return other 27 | if other.variables.size == 0: 28 | return self 29 | 30 | commonitem = np.intersect1d(self.variables, other.variables) 31 | idx1 = np.in1d(self.variables, commonitem).nonzero() 32 | idx2 = np.in1d(other.variables, commonitem).nonzero() 33 | if commonitem.size > 0: 34 | assert np.allclose(self.card[idx1], other.card[idx2]) 35 | 36 | newpot = potential() 37 | #FIX ME: dimension consistency not checked 38 | #FIX ME: only 1-D multiply considered 39 | 40 | newpot.variables = np.union1d(self.variables, other.variables) 41 | # sorted union of input arrays 42 | dummy, mapA = ismember(self.variables, newpot.variables) 43 | dummy, mapB = ismember(other.variables, newpot.variables) 44 | 45 | newpot.card = np.zeros(newpot.variables.size, 'int8') 46 | newpot.card[mapA] = list(self.card) 47 | newpot.card[mapB] = list(other.card) 48 | 49 | newpot.table = np.zeros(tuple(newpot.card)) 50 | for i in range(np.prod(newpot.card)): 51 | assignment = IndexToAssignment(i, newpot.card) 52 | assign1 = np.array(assignment)[mapA] 53 | assign2 = np.array(assignment)[mapB] 54 | newpot.table[tuple(assignment)] = self.table[tuple(assign1)] *\ 55 | other.table[tuple(assign2)] 56 | 57 | return newpot 58 | 59 | def __div__(self, other): 60 | #FIXME: works only 1-D considered, not completed 61 | newpot = copy.copy(self) 62 | newpot.variables = intersect(self.variables, other.variables) 63 | print "current divided newpot.variables=", newpot.variables 64 | newpot.table = self.table/other.table 65 | print "current divided table: \n", newpot.table 66 | return newpot 67 | 68 | def size(self): 69 | var = self.variables 70 | table = np.array(self.table) 71 | dim = table.ndim 72 | if dim == 0: 73 | print "ERRRRRRRRRRRRRRRRRR" 74 | elif dim > len(var): 75 | size = np.array(table.shape).size 76 | print "adjusted!!!!!!" 77 | 78 | return size # np.array format 79 | -------------------------------------------------------------------------------- /brml/potential/potential.py_bak: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | "Basic Class: potential" 4 | if __name__ == '__main__': 5 | print 'PotentialClass is running by itself' 6 | else: 7 | print 'PotentialClass is imported as module' 8 | 9 | import numpy as np 10 | import copy 11 | from brml.intersect import intersect 12 | 13 | class potential: 14 | def __init__(self, variables = [], table = []): 15 | self.variables = variables 16 | self.table = table 17 | 18 | def __mul__(self, other): 19 | 20 | newpot = copy.copy(self) 21 | #FIX ME: dimension consistency not checked 22 | #FIX ME: only 1-D multiply considered 23 | print "NOT-SWAPED table: \n", newpot.table 24 | commonitem = np.intersect1d(np.int8(self.variables),np.int8(other.variables)) 25 | commonindex = np.int8(np.in1d(self.variables,commonitem).nonzero()) 26 | commonshape = np.array(self.table.shape)[commonindex] 27 | newpot.variables[0],newpot.variables[commonindex] = newpot.variables[commonindex],newpot.variables[0] 28 | print "current commonindex:", commonindex 29 | print "current commonitem:", commonitem 30 | print "current commonshape:", commonshape 31 | print "current variable index:", newpot.variables 32 | newpot.table=newpot.table.swapaxes(commonindex,0) 33 | print "SWAPED table: \n", newpot.table 34 | for i in range(commonshape): 35 | #FIX ME: only swap (1-D case) the axes1=commonindex and axes2=0 36 | newpot.table[i,...] = newpot.table[i,...] * other.table[i] 37 | #newpot.table[i,...] = table * other.table 38 | print "current multipled table: \n", newpot.table 39 | return newpot 40 | 41 | def __div__(self, other): 42 | #FIXME: works only 1-D considered, not completed 43 | newpot = copy.copy(self) 44 | newpot.variables = intersect(self.variables, other.variables) 45 | print "current divided newpot.variables=", newpot.variables 46 | newpot.table = self.table/other.table 47 | print "current divided table: \n", newpot.table 48 | return newpot 49 | 50 | def size(self): 51 | var = self.variables 52 | table = np.array(self.table) 53 | dim = table.ndim 54 | if dim == 0: 55 | print "ERRRRRRRRRRRRRRRRRR" 56 | elif dim > len(var): 57 | size = np.array(table.shape).size 58 | print "adjusted!!!!!!" 59 | return size # np.array format 60 | 61 | -------------------------------------------------------------------------------- /brml/potential/potential.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/potential/potential.pyc -------------------------------------------------------------------------------- /brml/potvariables.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Author: Mingjun Zhou 5 | # Licence: BSD 3 clause 6 | 7 | 8 | import numpy as np 9 | 10 | 11 | def potvariables(pots): 12 | """Returns information about all variables in a set of potentials 13 | 14 | Return the variables and their number of states. 15 | If there is a dimension mismatch in the table then return con = 0. 16 | convec(i)=0 reports that variable i has conflicting dimension. 17 | 18 | Args: 19 | pots: a set of potentials 20 | 21 | Returns: 22 | variables: A list of all variables in pots 23 | nstates: A list of integers. nstates[idx] = number of dimension of 24 | variables[idx] 25 | con: con = 0 if there is a dimension mismatch in the table; 26 | con = 1 otherwise 27 | convect: convec(i) = 0 reports that variable i has conflicting 28 | dimensions 29 | 30 | Raises: 31 | NameError: An error occured accessing a None set of potentials 32 | ValueError: An error occurred accessing pots with None field or 33 | deffernt size in table and variables field 34 | """ 35 | if not pots: 36 | raise NameError('potentials should not be None') 37 | 38 | """if not isinstance(pots, list): 39 | raise TypeError('pots should be list Type') 40 | """ 41 | 42 | for i, pot in enumerate(pots): 43 | #if not isinstance(pot.variables, list): 44 | # raise TypeError('No.%d field of variables should be list type') 45 | if pot.variables.size == 0: 46 | raise ValueError('No.%d field of variables should not be None', i) 47 | #if not isinstance(pot.table, np.ndarray): 48 | # raise TypeError('No.%d field of variables shoud be np.ndarray\ 49 | # type', i) 50 | if len(pot.table) is 0: 51 | raise ValueError('No.%d field of table should not be None', i) 52 | if len(pot.variables) != len(pot.table.shape): 53 | raise ValueError('No.%d field of table and variables should not\ 54 | be different size', i) 55 | 56 | variables = list(pots[0].variables) 57 | nstates = list(pots[0].table.shape) 58 | con = 1 59 | convec = list(np.ones(len(variables), 'int8')) 60 | 61 | for pot in pots[1:]: 62 | vs = pot.variables 63 | ns = list(pot.table.shape) 64 | for i, v in enumerate(vs): 65 | if v in variables: 66 | idx_va = variables.index(v) 67 | if ns[i] != nstates[idx_va]: 68 | convec[idx_va] = 0 69 | con = 0 70 | else: 71 | variables.append(v) 72 | nstates.append(ns[i]) 73 | convec.append(1) 74 | 75 | return variables, nstates, con, convec 76 | -------------------------------------------------------------------------------- /brml/potvariables.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/potvariables.pyc -------------------------------------------------------------------------------- /brml/setminus.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | C=SETMINUS(A,B) 5 | C is the set A, without the elements B. C preserves the ordering of A 6 | 7 | Python: 8 | diff is the set in A without the elemnts B. 9 | """ 10 | import numpy as np 11 | 12 | def setminus(a,b): 13 | a = np.array(a) 14 | b = np.array(b) 15 | intersect = np.intersect1d(a,b) 16 | diff = np.setxor1d(a,intersect) 17 | return diff -------------------------------------------------------------------------------- /brml/setminus.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/setminus.pyc -------------------------------------------------------------------------------- /brml/setpot.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | %SETPOT sets array potential variables to specified states 5 | % newpot = setpot(pot,variables,evidstates) 6 | % 7 | % set variables in potential to evidential states in evidstates 8 | % Note that the new potential does not contain the evidential variables 9 | """ 10 | import numpy as np 11 | import copy as copy 12 | from .potential import potential 13 | from ismember import ismember 14 | from setstate import setstate 15 | from intersect import intersect 16 | from setstate import setstate 17 | from setminus import setminus 18 | from myzeros import myzeros 19 | from multpots import multpots 20 | from IndexToAssignment import IndexToAssignment 21 | from AssignmentToIndex import AssignmentToIndex 22 | 23 | 24 | def setpot(pot, evvariables, evidstates): 25 | #FIXME: data format needed to be unified 26 | vars = pot.variables 27 | #vars = np.array(pot.variables) # convert to ndarray format 28 | #evariables = np.array(evvariables) 29 | # convert to ndarray format 30 | #evidstates = np.array(evidstates) # convert to ndarray format 31 | #print "variables:", vars 32 | table = pot.table 33 | nstates = pot.card 34 | #print "number of states:", nstates 35 | #print "vars:", vars 36 | #print "evvariables:", evvariables 37 | intersection, iv, iev = intersect(vars, evvariables) 38 | #iv = np.array(iv) 39 | #iev = np.array(iev) 40 | #print "intersection:", intersection 41 | #print "iv:", iv 42 | #print "iev:", iev 43 | #print "iv type:", type(iv) 44 | #print "number of intersection:", intersection.size 45 | if intersection.size == 0: 46 | newpot = copy.copy(pot) 47 | else: 48 | newvar = setminus(vars, intersection) 49 | dummy, idx = ismember(newvar, vars) 50 | newns = nstates[idx] 51 | newpot = potential() 52 | newpot.variables = newvar 53 | newpot.card = newns 54 | newpot.table = np.zeros(newns) 55 | #print "idx:", idx 56 | #print "iv:", iv 57 | for i in range(np.prod(newns)): 58 | newassign = IndexToAssignment(i, newns) 59 | oldassign = np.zeros(nstates.size, 'int8') 60 | oldassign[idx] = newassign 61 | oldassign[iv] = evidstates 62 | #print "newpot.table.shape:", newpot.table.shape 63 | #print "newassign:", newassign 64 | #print "newassign type:", type(newassign) 65 | newpot.table[tuple(newassign)] = pot.table[tuple(oldassign)] 66 | 67 | return newpot 68 | -------------------------------------------------------------------------------- /brml/setpot.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/setpot.pyc -------------------------------------------------------------------------------- /brml/setstate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | %SETSTATE set a potential's specified joint state to a specified value 5 | p = setstate(pot,vars,states,val) 6 | All states of the potential that match the given (sub)state are set to val 7 | eg: pot=array([1 2],rand(2,2); 8 | newpot=setstate(pot,1,2,0.5) 9 | then for newpot.table all table entries matching variable 1 in state 2 will be set to value 0.5 10 | """ 11 | import numpy as np 12 | import copy as copy 13 | from ismember import ismember 14 | from subv2ind import subv2ind 15 | #from brml import * 16 | 17 | def setstate(pot,vars,state,val): 18 | #FIXME: data format needed to be unified 19 | #FIXME: works only for 1-D 20 | vars = np.array([vars]) 21 | state = np.array([state]) 22 | print type(vars) 23 | print "original vars:", vars 24 | print "input state:", state 25 | p = copy.copy(pot) 26 | a,tmp = ismember(vars,pot.variables) 27 | print "tmp=", tmp 28 | vars = vars[tmp] 29 | state = state[tmp] 30 | print "effective vars:", vars 31 | dum,iperm = ismember(vars,pot.variables) 32 | print "original vars item in pot:", pot.variables 33 | print "original table in pot", pot.table 34 | print "effective vars' index in pot:", iperm 35 | #FIXME: not consistent with former definition (need fn_size) 36 | nstates = pot.table.shape 37 | #FIXME: arbitrary setting 38 | nstates = np.array([2]) 39 | print "effective vars in pot NSTATES:", nstates 40 | #NOTE: use NAN as initial state in Python instead of 0. (Different from MATLAB) 41 | permstates = np.empty((1,np.size(nstates))) 42 | #FIXME: arbitrary setting 43 | permstates = np.empty(1) 44 | permstates[:] = np.nan 45 | print "initial effective vars states: \n", permstates 46 | permstates[iperm] = state 47 | print "set effective vars states: \n", permstates 48 | # set effective var-states to val 49 | print "permstates=", permstates 50 | print "permstates.all()=", permstates.all() 51 | # MATLAB: if all(permstates>0) % if the state is unique 52 | allcondition = np.logical_not(np.isnan(permstates)).all() 53 | print "allcondition=", allcondition 54 | if allcondition: # if the state is unique 55 | print "Before setstate: p.table= \n", p.table 56 | watch_ndx = np.asarray([subv2ind(nstates,permstates)]) 57 | watch_ndx = np.int8(watch_ndx) 58 | print "Callback watch_ndx = subv2ind(nstates,permstates)=", watch_ndx 59 | #FIXME: data format need unified 60 | #p.table[subv2ind(nstates,permstates)] = val 61 | #p.table = p.table.reshape(1,2) 62 | #print "reshaped p.table: \n", p.table 63 | print "val= ", val 64 | p.table[watch_ndx] = val 65 | #p.table = p.table.reshape(2,1) 66 | print "After setstate: p.table= \n", p.table 67 | #FIXME: not implemented ELSE case 68 | # else : # set all states that match the given substate to the given value 69 | # sub=find(permstates>0); 70 | # st=ind2subv(nstates,1:prod(nstates)); 71 | # p.table(all(st(:,sub)==repmat(permstates(sub),prod(nstates),1),2))=val; 72 | 73 | return p -------------------------------------------------------------------------------- /brml/setstate.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/setstate.pyc -------------------------------------------------------------------------------- /brml/subv2ind.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | % ndx = subv2ind(siz,sub) 5 | % 6 | % state to index : return the linear index of a state vector sub based on an array of size siz 7 | % If sub is a matrix, each row is taken as a state vector and the linear index returned in the 8 | % corresponding row of ndx. 9 | % This function is the inverse of ind2subv.m 10 | """ 11 | import numpy as np 12 | #FIXME: not quite clear about this function 13 | def subv2ind(siz,sub): 14 | print "siz=", siz 15 | print "sub=", sub 16 | k = np.array([0]) 17 | print "k=", k 18 | k = np.append(k, np.cumprod(siz[0:-1])) 19 | print "k=", k 20 | # MATLAB: ndx=sub*k.T-k.sum()+1 21 | ndx=sub*k.T-k.sum() 22 | print "ndx=", ndx 23 | 24 | return ndx -------------------------------------------------------------------------------- /brml/subv2ind.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/subv2ind.pyc -------------------------------------------------------------------------------- /brml/variable/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # http://stackoverflow.com/questions/5134893/importing-python-classes-from-different-files-in-a-subdirectory 4 | # __all__ = ['MyClass01','MyClass02'] 5 | 6 | from .variable import variable 7 | 8 | __all__ = ['variable'] -------------------------------------------------------------------------------- /brml/variable/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/variable/__init__.pyc -------------------------------------------------------------------------------- /brml/variable/variable.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | "Basic Class: variable" 4 | if __name__ == '__main__': 5 | print 'VariableClass is running by itself' 6 | else: 7 | print 'VariableClass is imported as module' 8 | 9 | class variable: 10 | def __init__(self, name = [], domain= []): 11 | self.name = name 12 | self.domain = domain -------------------------------------------------------------------------------- /brml/variable/variable.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/brml/variable/variable.pyc -------------------------------------------------------------------------------- /demo/demoBurglar.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Python implementation of BRMLtoolbox 4 | # Author: Mingjun Zhou 5 | # License: GNU License 6 | 7 | """ 8 | DEMOBURGLAR DEMO: was it the burglar example? 9 | """ 10 | print __doc__ 11 | 12 | import numpy as np 13 | import sys 14 | sys.path.append("..") 15 | from brml.variable import variable 16 | from brml.potential import potential 17 | from brml.multpots import multpots 18 | from brml.potvariables import potvariables 19 | from brml.setpot import setpot 20 | from brml.condpot import condpot 21 | from brml.dag import dag 22 | 23 | 24 | burglar, earthquake, alarm, radio = range(4) # Variable order is arbitary 25 | yes = 0 26 | no = 1 27 | 28 | variable = [variable(None, None) for i in range(4)] 29 | 30 | variable[burglar].name = 'burglar' 31 | variable[burglar].domain = ['yes', 'no'] 32 | 33 | variable[earthquake].name = 'earthquake' 34 | variable[earthquake].domain = ['yes', 'no'] 35 | 36 | variable[alarm].name = 'alarm' 37 | variable[alarm].domain = ['yes', 'no'] 38 | 39 | variable[radio].name = 'radio' 40 | variable[radio].domain = ['yes', 'no'] 41 | 42 | pot = [potential() for i in range(4)] 43 | 44 | pot[burglar].variables = np.array([burglar]) 45 | pot[burglar].card = np.array([2]) 46 | table = np.zeros(2) 47 | table[yes] = 0.01 48 | table[no] = 0.99 49 | pot[burglar].table = table 50 | 51 | pot[earthquake].variables = np.array([earthquake]) 52 | pot[earthquake].card = np.array([2]) 53 | table = np.zeros(2) 54 | table[yes] = 0.000001 55 | table[no] = 1 - table[yes] 56 | pot[earthquake].table = table 57 | 58 | pot[alarm].variables = np.array([alarm, burglar, earthquake]) 59 | pot[alarm].card = np.array([2, 2, 2]) 60 | table = np.zeros((2, 2, 2)) 61 | table[yes, yes, yes] = 0.9999 62 | table[yes, yes, no] = 0.99 63 | table[yes, no, yes] = 0.99 64 | table[yes, no, no] = 0.0001 65 | table[no][:][:] = 1 - table[yes][:][:] 66 | pot[alarm].table = table 67 | 68 | pot[radio].variables = np.array([radio, earthquake]) 69 | pot[radio].card = np.array([2, 2]) 70 | table = np.zeros((2, 2)) 71 | table[yes, yes] = 1 72 | table[no, yes] = 0 73 | table[yes, no] = 0 74 | table[no, no] = 1 75 | pot[radio].table = table 76 | 77 | #va = potvariables(pot) 78 | jointpot = multpots(pot) 79 | #print "jointpot.variables:", jointpot.variables 80 | #print "jointpot.card:", jointpot.card 81 | #print "jointpot.table:", jointpot.table 82 | 83 | #print jointpot.variables 84 | DAG = dag(pot) # Generate the DAG adjacency matrix 85 | print "DAG adjacency matrix: \n", DAG 86 | 87 | evidencedpot = setpot(jointpot, alarm, yes) 88 | #FIXME: arbitrary setting 89 | #evidencedpot.variables = evidencedpot.variables[1:] 90 | #print "................................................" 91 | #print "evidencedpot.variables:", evidencedpot.variables 92 | #print "evidencedpot.table: \n", evidencedpot.table 93 | 94 | #print "evidencepot.variables:", evidencedpot.table 95 | conditionedpot = condpot(evidencedpot, burglar) 96 | print "p(burglar|alarm=yes)" 97 | print "conditionedpot.variables:", conditionedpot.variables 98 | print "conditionedpot.table: \n", conditionedpot.table 99 | # jointpot = multpots(pot); % joint distribution 100 | 101 | evidencedpot = setpot(jointpot, [alarm, radio], [yes, yes]) 102 | conditionedpot = condpot(evidencedpot, burglar) 103 | print "p(burglar|alarm=yes, radio=yes):" 104 | print "conditionedpot.variables:", conditionedpot.variables 105 | print "conditionedpot.table: \n", conditionedpot.table 106 | #print "type:", (conditionedpot.table).dtype 107 | -------------------------------------------------------------------------------- /demo/demoBurglar.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/demo/demoBurglar.pyc -------------------------------------------------------------------------------- /demo/demoClouseau.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Python implementation of BRMLtoolbox 4 | # Author: Jiuding Duan 5 | # License: GNU license 6 | # def demoClouseau(): 7 | """ 8 | DEMOCLOUSEAU inspector clouseau example 9 | """ 10 | print __doc__ 11 | 12 | import numpy as np 13 | import sys 14 | sys.path.append("..") 15 | from brml.potential import potential 16 | from brml.variable import variable 17 | # from brml import * 18 | from brml.multpots import multpots 19 | from brml.dag import dag 20 | from brml.setpot import setpot 21 | from brml.condpot import condpot 22 | 23 | 24 | # Define number of variables(nodes) 25 | N = 3 26 | butler=2; maid=1; knife=0 # Variable order is arbitary (3,2,1 for MATLAB) 27 | # Define states, starting from 0. (from 1 for MATLAB) 28 | murderer=0; notmurderer=1 29 | used=0; notused=1 30 | 31 | """ 32 | The following definitions of variable are not necessary for computation, 33 | but are useful for displaying table entries: 34 | """ 35 | # Create empty list for variable, len(variable) = N 36 | variable = [ variable(None, None) for i in range(N)] 37 | print "variable list created as variable[knife, maid, butler] \n" 38 | variable[butler].name='butler'; variable[butler].domain = ['murderer','not murderer'] 39 | variable[maid].name='maid'; variable[maid].domain =['murderer','not murderer'] 40 | variable[knife].name='knife'; variable[knife].domain=['used','not used'] 41 | 42 | """ 43 | Three potential since p(butler,maid,knife)=p(knife|butler,maid)p(butler)p(maid). 44 | potential numbering is arbitary 45 | """ 46 | # Create empty list for potential, len(variable) = N 47 | pot = [potential() for i in range(N)] 48 | print "pot list created as pot[knife, maid, butler] \n" 49 | 50 | pot[butler].variables = np.array([butler]) 51 | pot[butler].card = np.array([2]) 52 | table = np.zeros((2)) 53 | table[murderer] =0.6 54 | table[notmurderer] =0.4 55 | pot[butler].table = table 56 | print "butler created at:", pot[butler] 57 | 58 | pot[maid].variables=np.array([maid]) 59 | pot[maid].card = np.array([2]) 60 | table = np.zeros((2)) 61 | table[murderer] =0.2 62 | table[notmurderer] =0.8 63 | pot[maid].table = table 64 | print "maid created at:", pot[maid] 65 | 66 | pot[knife].variables=np.array([knife,butler,maid]) # define array below using this variable order 67 | pot[knife].card = np.array([2, 2, 2]) 68 | table = np.zeros((2,2,2)) 69 | table[used, notmurderer, notmurderer]=0.3 70 | table[used, notmurderer, murderer] =0.2 71 | table[used, murderer, notmurderer]=0.6 72 | table[used, murderer, murderer] =0.1 73 | pot[knife].table = table 74 | pot[knife].table[notused][:][:]=1-pot[knife].table[used][:][:] # due to normalisation 75 | print "knife created at:", pot[knife] 76 | 77 | jointpot = multpots(pot) # joint distribution 78 | #FIXME: arbitrary set order and swaped 79 | #jointpot.variables = [0,1,2] 80 | #jointpot.table = np.swapaxes(jointpot.table,0,2) 81 | print "jointpot.variables:", jointpot.variables 82 | print "joint distribution generated as: jointpot \n", jointpot.table 83 | 84 | sum = jointpot.table.sum() 85 | print "knife = ", variable[knife].domain[used], "maid = ", variable[maid].domain[murderer], "butler = ", variable[butler].domain[murderer] 86 | 87 | DAG = dag(pot) # Generate the DAG adjacency matrix 88 | print "DAG adjacency matrix: \n", DAG 89 | 90 | evidencedpot = setpot(jointpot,knife,used) 91 | #FIXME: arbitrary setting 92 | #evidencedpot.variables = evidencedpot.variables[1:] 93 | print "................................................" 94 | print "evidencedpot.variables:", evidencedpot.variables 95 | print "evidencedpot.table: \n", evidencedpot.table 96 | 97 | conditionedpot = condpot(evidencedpot,butler) 98 | print "conditionedpot.variables:", conditionedpot.variables 99 | print "conditionedpot.table: \n", conditionedpot.table 100 | # jointpot = multpots(pot); % joint distribution 101 | 102 | #drawNet(dag(pot),variable); 103 | #disp('p(butler|knife=used):') 104 | #disptable(condpot(setpot(jointpot,knife,used),butler),variable); 105 | -------------------------------------------------------------------------------- /demo/demoClouseau.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/demo/demoClouseau.pyc -------------------------------------------------------------------------------- /proposal/10.1.1.66.8598.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/proposal/10.1.1.66.8598.pdf -------------------------------------------------------------------------------- /proposal/SOCIS2013proposal.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/proposal/SOCIS2013proposal.docx -------------------------------------------------------------------------------- /proposal/datastructure.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/proposal/datastructure.jpg -------------------------------------------------------------------------------- /proposal/datastructure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/proposal/datastructure.png -------------------------------------------------------------------------------- /proposal/proposal: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/djour/PyBRML/42fa70f17c303943447816234a87b3c5815f12bb/proposal/proposal -------------------------------------------------------------------------------- /test/orderpotTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Author: Mingjun Zhou 5 | # Licence: BSD 3 clause 6 | 7 | 8 | import unittest 9 | import sys 10 | sys.path.append("..") 11 | from brml.orderpot import orderpot 12 | from brml.potential import potential 13 | import numpy as np 14 | 15 | 16 | class orderpotTestCase(unittest.TestCase): 17 | def setUp(self): 18 | self.pot = potential() 19 | self.pot.variables = np.array([3, 2, 1]) 20 | self.card = np.array([2, 3, 4]) 21 | self.pot.table = np.arange(0, 24).reshape(2, 3, 4) 22 | 23 | def tearDown(self): 24 | self.pot = None 25 | 26 | def assertTwoPot(self, pa, pb): 27 | assert np.allclose(pa.variables, pb.variables) 28 | assert np.allclose(pa.card, pb.card) 29 | assert np.allclose(pa.table, pb.table) 30 | 31 | def testNewOrder(self): 32 | neworder = [2, 1, 3] 33 | newpot = orderpot(self.pot, neworder) 34 | newtable = np.array([[[0, 12], [1, 13], [2, 14], [3, 15]], 35 | [[4, 16], [5, 17], [6, 18], [7, 19]], 36 | [[8, 20], [9, 21], [10, 22], [11, 23]]]) 37 | assert np.allclose(newpot.variables, np.array(neworder)) 38 | assert not (newpot.table - newtable).any() 39 | 40 | def testSortedOrder(self): 41 | neworder = [1, 2, 3] 42 | newtable = np.array([[[0, 12], [4, 16], [8, 20]], 43 | [[1, 13], [5, 17], [9, 21]], 44 | [[2, 14], [6, 18], [10, 22]], 45 | [[3, 15], [7, 19], [11, 23]]]) 46 | newpot = orderpot(self.pot, []) 47 | assert np.allclose(newpot.variables, np.array(neworder)) 48 | assert not (newpot.table - newtable).any() 49 | 50 | if __name__ == "__main__": 51 | suite = unittest.TestSuite() 52 | suite.addTest(orderpotTestCase("testNewOrder")) 53 | suite.addTest(orderpotTestCase("testSortedOrder")) 54 | 55 | runner = unittest.TextTestRunner() 56 | runner.run(suite) 57 | -------------------------------------------------------------------------------- /test/potentialTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Author: Mingjun Zhou 5 | # Licence: BSD 3 clause 6 | 7 | 8 | import unittest 9 | import sys 10 | sys.path.append("..") 11 | from brml.potential import potential 12 | import numpy as np 13 | 14 | 15 | class potentialTestCase(unittest.TestCase): 16 | def setUp(self): 17 | self.pot = potential() 18 | self.pot.variables = np.array([2, 1]) 19 | self.pot.card = np.array([2, 2]) 20 | self.pot.table = np.array([[0.2, 0.6], [0.8, 0.4]]) 21 | 22 | def tearDown(self): 23 | self.pot = None 24 | 25 | def assertTwoPot(self, pa, pb): 26 | assert np.allclose(pa.variables, pb.variables) 27 | assert np.allclose(pa.card, pb.card) 28 | assert np.allclose(pa.table, pb.table) 29 | 30 | def testMultEmpty(self): 31 | newpot = self.pot * potential() 32 | self.assertTwoPot(newpot, self.pot) 33 | newpot = None 34 | 35 | newpot = potential() * self.pot 36 | self.assertTwoPot(newpot, self.pot) 37 | 38 | def testMult(self): 39 | otherpot = potential() 40 | otherpot.variables = np.array([3]) 41 | otherpot.card = np.array([3]) 42 | otherpot.table = np.array([0.1, 0.4, 0.5]) 43 | answerpot = potential() 44 | answerpot.variables = np.array([1, 2, 3]) 45 | answerpot.card = np.array([2, 2, 3]) 46 | answerpot.table = np.array([[[0.02, 0.08, 0.1], 47 | [0.08, 0.32, 0.4]], 48 | [[0.06, 0.24, 0.3], 49 | [0.04, 0.16, 0.2]]]) 50 | self.assertTwoPot(self.pot * otherpot, answerpot) 51 | 52 | otherpot = potential() 53 | otherpot.variables = np.array([3, 1]) 54 | otherpot.card = np.array([3, 2]) 55 | otherpot.table = np.array([[0.2, 0.3], [0.2, 0.2], [0.6, 0.5]]) 56 | answerpot = potential() 57 | answerpot.variables = np.array([1, 2, 3]) 58 | answerpot.card = np.array([2, 2, 3]) 59 | answerpot.table = np.array([[[0.04, 0.04, 0.12], 60 | [0.16, 0.16, 0.48]], 61 | [[0.18, 0.12, 0.3], 62 | [0.12, 0.08, 0.2]]]) 63 | self.assertTwoPot(self.pot * otherpot, answerpot) 64 | 65 | if __name__ == "__main__": 66 | suite = unittest.TestSuite() 67 | suite.addTest(potentialTestCase("testMultEmpty")) 68 | suite.addTest(potentialTestCase("testMult")) 69 | 70 | runner = unittest.TextTestRunner() 71 | runner.run(suite) 72 | -------------------------------------------------------------------------------- /test/potvariablesTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Author: Mingjun Zhou 5 | # Licence: BSD 3 clause 6 | 7 | 8 | import unittest 9 | import sys 10 | sys.path.append("..") 11 | from brml.potvariables import potvariables 12 | from brml.potential import potential 13 | import numpy as np 14 | 15 | 16 | class potvariablesTestCase(unittest.TestCase): 17 | #def setUp(self): 18 | # return 19 | 20 | #def tearDown(self): 21 | # return 22 | 23 | def testEmptyPot(self): 24 | pot = [] 25 | self.assertRaises(NameError, potvariables, pot) 26 | 27 | """def testNoneTable(self): 28 | pot = [potential([1], np.zeros(0))] 29 | self.assertRaises(ValueError, potvariables, pot) 30 | """ 31 | 32 | def testNoneVariables(self): 33 | pot = [potential(np.array([]), np.zeros(3))] 34 | self.assertRaises(ValueError, potvariables, pot) 35 | 36 | def testDiffVaTa(self): 37 | pot = [potential(np.array([1, 2]), np.zeros((3, 2, 2)))] 38 | self.assertRaises(ValueError, potvariables, pot) 39 | 40 | def testMismatchPot(self): 41 | """mismatch dimension in pot""" 42 | pot = [potential() for i in range(4)] 43 | pot[0].variables = np.array([0]) 44 | pot[0].card = np.array([2]) 45 | pot[0].table = np.zeros(2) 46 | 47 | pot[1].variables = np.array([1]) 48 | pot[1].card = np.array([3]) 49 | pot[1].table = np.zeros(3) 50 | 51 | pot[2].variables = np.array([2, 0, 1]) 52 | pot[2].card = np.array([4, 3, 3]) 53 | pot[2].table = np.zeros((4, 3, 3)) 54 | 55 | pot[3].variables = np.array([3, 1]) 56 | pot[3].card = np.array([3, 1]) 57 | pot[3].table = np.zeros((2, 2)) 58 | 59 | v, ns, con, convec = potvariables(pot) 60 | #pot.dispose() 61 | pot = None 62 | self.assertEqual(v, [0, 1, 2, 3]) 63 | self.assertEqual(ns, [2, 3, 4, 2]) 64 | self.assertEqual(con, 0) 65 | self.assertEqual(convec, [0, 0, 1, 1]) 66 | 67 | def testMatchPot(self): 68 | """all variables's dimensions are match in pot""" 69 | pot = [potential() for i in range(4)] 70 | pot[0].variables = np.array([0]) 71 | pot[0].card = np.array([2]) 72 | pot[0].table = np.zeros(2) 73 | 74 | pot[1].variables = np.array([1]) 75 | pot[1].card = np.array([3]) 76 | pot[1].table = np.zeros(3) 77 | 78 | pot[2].variables = np.array([2, 0, 1]) 79 | pot[2].card = np.array([4, 2, 3]) 80 | pot[2].table = np.zeros((4, 2, 3)) 81 | 82 | pot[3].variables = np.array([3, 1]) 83 | pot[3].card = np.array([3]) 84 | pot[3].table = np.zeros((2, 3)) 85 | 86 | v, ns, con, convec = potvariables(pot) 87 | #pot.dispose() 88 | pot = None 89 | self.assertEqual(v, [0, 1, 2, 3]) 90 | self.assertEqual(ns, [2, 3, 4, 2]) 91 | self.assertEqual(con, 1) 92 | self.assertEqual(convec, [1, 1, 1, 1]) 93 | 94 | 95 | if __name__ == "__main__": 96 | suite = unittest.TestSuite() 97 | suite.addTest(potvariablesTestCase("testEmptyPot")) 98 | #suite.addTest(potvariablesTestCase("testNoneTable")) 99 | suite.addTest(potvariablesTestCase("testNoneVariables")) 100 | suite.addTest(potvariablesTestCase("testDiffVaTa")) 101 | suite.addTest(potvariablesTestCase("testMismatchPot")) 102 | suite.addTest(potvariablesTestCase("testMatchPot")) 103 | 104 | runner = unittest.TextTestRunner() 105 | runner.run(suite) 106 | -------------------------------------------------------------------------------- /test_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # this is a test case for sample codes 4 | 5 | from brml.potential import potential 6 | from brml.variable import variable 7 | 8 | 9 | p = potential(1,1) 10 | print "var POTENTIAL.p created" 11 | print "p.variable = ", p.variables 12 | print "p.table = ", p.table 13 | 14 | v = variable('butler',['hehe', 'heihei']) 15 | # v = variable('butler',['murderer','not murderer']) 16 | print "var VARIABLE.v created" 17 | print "v.name = ", v.name 18 | print "v.domain = ", v.domain --------------------------------------------------------------------------------