I look for an efficient way to implement a Pairwise Markov Random Field.
I have implemented a homogeneous (i.e., unary potential is a similar function in all nodes, and pairwise potential is a similar function too) binary Markov Random Field.
For an example probability calculation on the line graph with ten nodes.
nodes = 10;
nodesDomain = {1, -1};
numOfObservation = 4;
g1 = GridGraph[{1, nodes}, VertexLabels -> "Name"];
possibleGraphAssignment = Tuples[nodesDomain, nodes];
weights =
ParallelMap[graphPotentialCalculation[#] &, possibleGraphAssignment];
\[ScriptCapitalD]= EmpiricalDistribution[weights -> possibleGraphAssignment]/. {b -> 0.3, a -> 0.7, q -> 0.1, p -> 0.9};
listOfRV = Parallelize[Array[RV, nodes]];
With this function I calculate the potential of each possible configuration:
graphPotentialCalculation[vertC_] :=
Module[{edgeList = EdgeList[g1], vertexList = VertexList[g1], nodeP,
edgeP},
nodeP = nodePotential[#] & /@ vertC;
edgeP = edgePotential[First[#], Last[#], vertC] & /@ edgeList;
Times @@ nodeP*Times @@ edgeP
]
edgePotential[v_, u_, graphCh_] := Module[{},
Piecewise[{{p, graphCh[[v]] == graphCh[[u]]}, {q,
graphCh[[v]] != graphCh[[u]]}}]]
nodePotential[v_] := Module[{},
Piecewise[{{a, v == 1}, {b, v == -1}}]]
I have a bottleneck in my code : calculation of the empirical distribution - to do it, I calculate the truth table, and this takes a lot of time
Any suggestion on how to speed-up code.
Probability[RV[9] == 1 && RV[5] == 1, listOfRV \[Distributed] \[ScriptCapitalD]]
$\endgroup$