Esempio n. 1
0
    def testInsertion(self):
        mn = gum.MarkovNet()
        self._fill(mn)

        with self.assertRaises(gum.InvalidArgument):
            mn.addFactor(gum.Potential())  # no empty factor

        with self.assertRaises(gum.InvalidArgument):
            mn.addFactor({"11", "31"})  # already exist

        mn1 = gum.MarkovNet()
        self._fill(mn1)
        pot = gum.Potential().add(mn1.variable("11")).add(mn1.variable("21"))
        pot.randomDistribution()
        mn1.addFactor(pot)
        self.assertEqual(pot.__str__(), mn1.factor({"11", "21"}).__str__())

        mn1 = gum.MarkovNet()
        self._fill(mn1)
        pot = gum.Potential().add(mn1.variable("21")).add(mn1.variable("11"))
        pot.randomDistribution()
        mn1.addFactor(pot)

        # should be equal : does not depend of the order of vars in the MarkonNet
        self.assertEqual(pot.__str__(), mn1.factor({"11", "21"}).__str__())

        # but the data should be the same
        I = gum.Instantiation(pot)
        factor = mn1.factor({"21", "11"})
        I.setFirst()
        while not I.end():
            self.assertAlmostEqual(pot.get(I), factor.get(I), places=7)
            I.inc()
Esempio n. 2
0
 def testEqualityOperators(self):
     mn1 = gum.MarkovNet()
     self._fill(mn1)
     mn2 = gum.MarkovNet()
     self.assertNotEqual(mn1, mn2)
     self._fill(mn2)
     self.assertEqual(mn1, mn2)
     mn2.generateFactors()
     self.assertNotEqual(mn1, mn2)
Esempio n. 3
0
 def testCopyOperator(self):
     mn = gum.MarkovNet()
     mn2 = gum.MarkovNet()
     self._fill(mn)
     mn2 = mn
     self.assertEqual(mn2.__str__(),
                      "MN{nodes: 5, edges: 6, domainSize: 567, dim: 102}")
     for n in mn.nodes():
         self.assertEqual(mn.variable(n).name(), mn2.variable(n).name())
         self.assertEqual(mn.neighbours(n), mn2.neighbours(n))
def undiGraphToMarkovNetwork(graph, variables=dict(), domainSize=2):
    """
    Build a markov network from an UndiGraph
    Variables can be either given in parameters or can be created if they are not defined

    Parameters
    ----------
    graph : pyAgrum.UndiGraph
            the graph
    variables : dict<str:pyAgrum.DiscreteVariable>
            already defined variables, keys are variables name
    domainSize : int
            the domain of variables that are not defined
            
    Returns
    -------
    pyAgrum.MarkovNet
            the resulting Markov network
    """
    nodes = graph.nodes()
    cliques = getAllMaximalCliquesUndiGraph(graph)
    definedVariables = variables.keys()
    mn = gum.MarkovNet()
    for node in nodes:
        if node in definedVariables:
            mn.add(variables[node])
        else:
            mn.add(gum.LabelizedVariable(str(node), "", domainSize))
    for clique in cliques:
        mn.addFactor(clique)
    return mn
def createRandomMNTree(nodeNumber, minDomainSize=2, maxDomainSize=2):
    """
    Build a random markov network and return it, the returned markov network is a tree

    Examples
    --------
    >>> import markovNetworkLearning as mnl
    >>> mn=mnl.createRandomMNTree(15,2,4)

    Parameters
    ----------
    nodeNumber : int
            the number of variables of the markov network
    minDomainSize : int
            2 or above, default value : 2, each variable will have a random domain size randomly selected between minDomainSize and maxDomainSize
    maxDomainSize : int
            2 or above, and more than minDomainSize, default value : 2,  each variable will have a random domain size randomly selected between minDomainSize and maxDomainSize
        
    Returns
    -------
    pyAgrum.MarkovNet
            the resulting Markov network 
    """
    variablesDomainSize = np.random.randint(minDomainSize,
                                            maxDomainSize + 1,
                                            size=nodeNumber)
    tree = gum.MarkovNet()
    if nodeNumber > 0:
        tree.add(gum.LabelizedVariable("0", "", int(variablesDomainSize[0])))
    for i in range(1, nodeNumber):
        otherNode = random.choice(list(tree.nodes()))
        tree.add(gum.LabelizedVariable(str(i), "",
                                       int(variablesDomainSize[i])))
        tree.addFactor({otherNode, str(i)})
    return tree
Esempio n. 6
0
 def testEraseWithNames(self):
     mn = gum.MarkovNet()
     self._fill(mn)
     with self.assertRaises(gum.NotFound):
         mn.erase("36")
     mn.erase("41")
     self.assertEqual(mn.size(), 4)
     self.assertEqual(mn.sizeEdges(), 3)
     self.assertEqual(mn.dim(), (3 * 3 + 3 * 7 + 3 * 7))
     self.assertEqual(mn.__str__(),
                      "MN{nodes: 4, edges: 3, domainSize: 189, dim: 51}")
Esempio n. 7
0
 def testErase(self):
     mn = gum.MarkovNet()
     self._fill(mn)
     with self.assertRaises(gum.InvalidArgument):
         mn.erase(36)
     mn.erase(3)
     self.assertEqual(mn.size(), 4)
     self.assertEqual(mn.sizeEdges(), 3)
     self.assertEqual(mn.dim(), (3 * 3 + 3 * 7 + 3 * 7))
     self.assertEqual(mn.__str__(),
                      "MN{nodes: 4, edges: 3, domainSize: 189, dim: 51}")
Esempio n. 8
0
    def testEraseFactorWithNames(self):
        mn = gum.MarkovNet()
        self._fill(mn)
        with self.assertRaises(gum.InvalidArgument):
            mn.eraseFactor({"31", "21"})
        mn.eraseFactor({"31", "51"})

        self.assertEqual(mn.size(), 5)
        self.assertEqual(mn.sizeEdges(), 5)
        self.assertEqual(mn.dim(), (3 * 3 + 3 * 3 + 3 * 3 * 7))
        self.assertEqual(mn.__str__(),
                         "MN{nodes: 5, edges: 5, domainSize: 567, dim: 81}")
Esempio n. 9
0
    def testIterations(self):
        mn = gum.MarkovNet()
        self._fill(mn)

        cpt = 0
        for node in mn.nodes():
            cpt += 1
        self.assertEqual(cpt, mn.size())

        cpt = 0
        for edg in mn.edges():
            cpt += 1
        self.assertEqual(cpt, mn.sizeEdges())
Esempio n. 10
0
    def testConstructor(self):
        mn = gum.MarkovNet()
        self._fill(mn)

        self.assertEqual(mn.size(), 5)
        self.assertEqual(mn.sizeEdges(), 6)
        self.assertEqual(mn.dim(), (3 * 3 + 3 * 3 + 3 * 7 + 3 * 3 * 7))
        self.assertEqual(mn.__str__(),
                         "MN{nodes: 5, edges: 6, domainSize: 567, dim: 102}")
        self.assertEqual(mn.neighbours("41"), {0, 1, 4})
        self.assertEqual(mn.neighbours(3), {0, 1, 4})

        self.assertEqual(mn.variable(1).name(), "21")
        self.assertEqual(mn.nodeId(mn.variable(2)), 2)
        self.assertEqual(mn.idFromName("31"), 2)
        self.assertEqual(mn.variableFromName("41").name(), "41")

        self.assertEqual(mn.maxVarDomainSize(), 7)
        self.assertEqual(mn.minParam(), 0.0)
        self.assertEqual(mn.minNonZeroParam(), 0.03)
        self.assertEqual(mn.maxParam(), 1.0)
        self.assertEqual(mn.maxNonOneParam(), 0.97)
def dictToMarkovNetwork(graph, variables=dict(), domainSize=2):
    """
    Build a markov network from an adjacency list
    Variables can be either given in parameters or can be created if they are not defined

    Parameters
    ----------
    graph : dict
            the graph, as an adjacency list
    variables : dict<str:pyAgrum.DiscreteVariable>
            already defined variables, keys are variables name
    domainSize : int
            the domain of variables that are not defined
            
    Returns
    -------
    pyAgrum.MarkovNet
            the resulting Markov network
    """
    for var1 in graph.keys():
        for var2 in graph[var1]:
            if var1 not in graph[var2]:
                raise ValueError(
                    'Can only convert an adjacency list into a markov network : as "'
                    + str(var2) + '" is a neighbor of "' + str(var1) +
                    '", then "' + str(var1) + '" must be a neighbor of "' +
                    str(var2) + '".')
    nodes = graph.keys()
    cliques = getAllMaximalCliquesDict(graph)
    definedVariables = variables.keys()
    mn = gum.MarkovNet()
    for node in nodes:
        if node in definedVariables:
            mn.add(variables[node])
        else:
            mn.add(gum.LabelizedVariable(str(node), "", domainSize))
    for clique in cliques:
        mn.addFactor(clique)
    return mn