def main():
        pa_nd = BayesNode(0, "pa_nd", size=4)
        pa_nd.state_names = [str(k) for k in range(4)]

        p_sh = PhaseShifter(1, "pshifter", pa_nd, 30, occ_nums=True)

        print("pa_nd state names: ", pa_nd.state_names)
        print("phase shifter state names: ", p_sh.state_names)
        print(p_sh.potential)
        print(p_sh.potential.get_total_probs())
Example #2
0
    def main():
        pa_nd = BayesNode(0, "pa_nd", size=2)
        pa_nd.state_names = ['0', '1']

        thetas_degs = [20, 30, 40, 60]
        qr = QubitRot(1, "rot", pa_nd, thetas_degs)

        print("pa_nd state names: ", pa_nd.state_names)
        print("qubit rot state names: ", qr.state_names)
        print(qr.potential)
        print(qr.potential.get_total_probs())
Example #3
0
    def read_bif(path, is_quantum):
        """
        Reads a bif file using our stand-alone class BifTool and returns a
        BayesNet. bif and dot files complement each other. bif: graphical
        info No, pot info Yes. dot: graphical info Yes, pot info No. By pots
        I mean potentials, the transition matrices of the nodes. (aka CPTs,
        etc.)

        Parameters
        ----------
        path : str
        is_quantum : bool

        Returns
        -------
        BayesNet

        """

        bt = BifTool(is_quantum)
        bt.read_bif(path)
        nodes = set()
        name_to_nd = {}
        for k, nd_name in enumerate(bt.nd_sizes.keys()):
            node = BayesNode(k, nd_name)
            node.state_names = bt.states[nd_name]
            node.size = len(node.state_names)
            node.forget_all_evidence()
            nodes |= {node}
            name_to_nd[nd_name] = node
        for nd_name, pa_name_list in bt.parents.items():
            node = name_to_nd[nd_name]
            for pa_name in pa_name_list:
                pa = name_to_nd[pa_name]
                node.add_parent(pa)

        for nd_name, parent_names in bt.parents.items():
            node = name_to_nd[nd_name]
            num_pa = len(parent_names)
            parents = [name_to_nd[pa_name] for pa_name in parent_names]
            if num_pa == 0:
                node.potential = DiscreteUniPot(is_quantum, node)
            else:
                node.potential = DiscreteCondPot(
                    is_quantum, parents + [node])
            node.potential.pot_arr = bt.pot_arrays[nd_name]

        return BayesNet(nodes)
Example #4
0
    def __deepcopy__(self, memo):
        """
        Creates deep copy of self.

        Parameters
        ----------
        memo : dict

        Returns
        -------
        BayesNet

        """
        nd_to_new_nd = {}
        for nd in self.nodes:
            nd_to_new_nd[nd] = BayesNode(nd.id_num, nd.name)
        for nd, new_nd in nd_to_new_nd.items():
            new_nd.neighbors = set([nd_to_new_nd[nd1] for nd1 in nd.neighbors])
            new_nd.topo_index = nd.topo_index
            new_nd.visited = nd.visited
            new_nd.children = set([nd_to_new_nd[nd1] for nd1 in nd.children])
            new_nd.parents = set([nd_to_new_nd[nd1] for nd1 in nd.parents])
            # not in Dag:
            new_nd.active_states = [x for x in nd.active_states]
            new_pot_arr = cp.deepcopy(nd.potential.pot_arr)
            new_ord_nodes = [
                nd_to_new_nd[nd1] for nd1 in nd.potential.ord_nodes
            ]
            new_nd.potential = Potential(nd.potential.is_quantum,
                                         ord_nodes=new_ord_nodes,
                                         pot_arr=new_pot_arr)
            new_nd.size = nd.size
            new_nd.state_names = [x for x in nd.state_names]

        return BayesNet(set(nd_to_new_nd.values()))
Example #5
0
    def main():

        theta_degs = 35
        max_n_sum = 3

        in_nd = BayesNode(0, "parent1", size=6)

        in_nd.set_state_names_to_product([range(2), range(3)], trim=False)

        pr = PolarizationRot(1, "pol_rot", in_nd, theta_degs, max_n_sum)

        print("in_nd state names: ", in_nd.state_names)
        print("pol rot state names: ", pr.state_names)
        print(pr.potential)
        print("full dict of total probs: ", pr.potential.get_total_probs())
        print("brief dict of total probs: ",
              pr.potential.get_total_probs(brief=True))
    def main():
        pa_nd = BayesNode(0, "pa_nd", size=24)
        # has_commas = True
        has_commas = False
        pa_nd.set_state_names_to_product(
            [range(2), range(3), range(4)], trim=not has_commas)
        marg = Marginalizer(1,
                            "marg",
                            False,
                            pa_nd,
                            projected_axis=1,
                            has_commas=has_commas)

        print("pa state names: ", pa_nd.state_names)
        print("marg state names: ", marg.state_names)
        print(marg.potential)
        print(marg.potential.get_total_probs())
Example #7
0
    def main():
        a = BayesNode(0, name="a")
        b = BayesNode(1, name="b")
        c = BayesNode(2, name="c")

        a.add_neighbor(b)
        a.add_neighbor(c)

        assert Star.get_missing_edges_of_node(a) == [{b, c}]
Example #8
0
    def main():
        pa1 = BayesNode(0, "parent1", size=2)
        pa2 = BayesNode(1, "parent2", size=2)

        pa1.state_names = ['0', '1']
        pa2.state_names = ['0', '1']

        cn = CNot(2, "a_cnot", False, pa1, pa2, True, True)

        print("pa1 state names: ", pa1.state_names)
        print("pa2 state names: ", pa2.state_names)
        print("cnot state names: ", cn.state_names)
        print(cn.potential)
        print(cn.potential.get_total_probs())
Example #9
0
    def new_from_nx_graph(nx_graph):
        """
        Returns a BayesNet constructed from nx_graph.

        Parameters
        ----------
        nx_graph : networkx DiGraph

        Returns
        -------
        BayesNet

        """
        new_g = BayesNet(set())
        for k, name in enumerate(nx_graph.nodes()):
            new_g.add_nodes({BayesNode(k, name=name)})

        node_list = list(new_g.nodes)
        for nd in node_list:
            for ch_name in nx_graph.successors(nd.name):
                nd.add_child(new_g.get_node_named(ch_name))
        return new_g
Example #10
0
    def build_bnet():
        """
        Builds CBnet called WetGrass with diamond shape
                Cloudy
                /    \
             Rain    Sprinkler
               \      /
               WetGrass
        All arrows pointing down
        """

        cl = BayesNode(0, name="Cloudy")
        sp = BayesNode(1, name="Sprinkler")
        ra = BayesNode(2, name="Rain")
        we = BayesNode(3, name="WetGrass")

        we.add_parent(sp)
        we.add_parent(ra)
        sp.add_parent(cl)
        ra.add_parent(cl)

        nodes = {cl, ra, sp, we}

        cl.potential = DiscreteUniPot(False, cl)  # P(a)
        sp.potential = DiscreteCondPot(False, [cl, sp])  # P(b| a)
        ra.potential = DiscreteCondPot(False, [cl, ra])
        we.potential = DiscreteCondPot(False, [sp, ra, we])

        # in general
        # DiscreteCondPot(False, [y1, y2, y3, x]) refers to P(x| y1, y2, y3)
        # off = 0
        # on = 1

        cl.potential.pot_arr[:] = [.5, .5]

        ra.potential.pot_arr[1, :] = [.5, .5]
        ra.potential.pot_arr[0, :] = [.4, .6]

        sp.potential.pot_arr[1, :] = [.7, .3]
        sp.potential.pot_arr[0, :] = [.2, .8]

        we.potential.pot_arr[1, 1, :] = [.01, .99]
        we.potential.pot_arr[1, 0, :] = [.01, .99]
        we.potential.pot_arr[0, 1, :] = [.01, .99]
        we.potential.pot_arr[0, 0, :] = [.99, .01]

        return BayesNet(nodes)
Example #11
0
        self.occ_nums = occ_nums

        BayesNode.__init__(self, id_num, name, size=pa_nd.size)
        self.add_parent(pa_nd)

        self.state_names = pa_nd.state_names

        pot = DiscreteCondPot(True, [pa_nd, self], bias=0)
        self.potential = pot

        theta_rads = theta_degs * math.pi / 180
        for k in range(pa_nd.size):
            if not occ_nums:
                phase = theta_rads
            else:
                num = int(pa_nd.state_names[k])
                phase = num * theta_rads
            self.potential[k, k] = cmath.exp(1j * phase)


if __name__ == "__main__":
    pa_nd = BayesNode(0, "pa_nd", size=4)
    pa_nd.state_names = [str(k) for k in range(4)]

    p_sh = PhaseShifter(1, "pshifter", pa_nd, 30, occ_nums=True)

    print("pa_nd state names: ", pa_nd.state_names)
    print("phase shifter state names: ", p_sh.state_names)
    print(p_sh.potential)
    print(p_sh.potential.get_total_probs())
Example #12
0
    def build_bnet():
        """
        Builds simple 7 node binary tree
                     a0
                   /    \
                  b0    b1
                 /  \  /  \
                c0  c1,c2 c3

        All arrows pointing down
        """

        a0 = BayesNode(0, name="a0")

        b0 = BayesNode(1, name="b0")
        b1 = BayesNode(2, name="b1")

        c0 = BayesNode(3, name="c0")
        c1 = BayesNode(4, name="c1")
        c2 = BayesNode(5, name="c2")
        c3 = BayesNode(6, name="c3")

        a0.add_children([b0, b1])
        b0.add_children([c0, c1])
        b1.add_children([c2, c3])

        nodes = {a0, b0, b1, c0, c1, c2, c3}

        a0.potential = DiscreteUniPot(False, a0)  # P(a)

        b0.potential = DiscreteCondPot(False, [a0, b0])  # P(b| a)
        b1.potential = DiscreteCondPot(False, [a0, b1])

        c0.potential = DiscreteCondPot(False, [b0, c0])
        c1.potential = DiscreteCondPot(False, [b0, c1])
        c2.potential = DiscreteCondPot(False, [b1, c2])
        c3.potential = DiscreteCondPot(False, [b1, c3])

        # in general
        # DiscreteCondPot(False, [y1, y2, y3, x]) refers to P(x| y1, y2, y3)
        # off = 0
        # on = 1

        a0.potential.pot_arr = np.array([.7, .3])

        b0.potential.pot_arr = np.array([[.5, .5], [.4, .6]])
        b1.potential.pot_arr = np.array([[.2, .8], [.4, .6]])

        c0.potential.pot_arr = np.array([[.3, .7], [.4, .6]])
        c1.potential.pot_arr = np.array([[.5, .5], [.9, .1]])
        c2.potential.pot_arr = np.array([[.8, .2], [.4, .6]])
        c3.potential.pot_arr = np.array([[.5, .5], [.6, .4]])

        return BayesNet(nodes)
Example #13
0
        """
        if self.flipped_by_0:
            x = 1 - pa1_st
        else:  # flipped by 1
            x = pa1_st
        if self.pa1_is_control:
            bit0 = pa1_st
            bit1 = (x + pa2_st) // 2
        else:  # pa2 is control
            bit0 = (x + pa2_st) // 2
            bit1 = pa2_st
        foc_st = bit0 + 2 * bit1
        return foc_st


if __name__ == "__main__":
    pa1 = BayesNode(0, "parent1", size=2)
    pa2 = BayesNode(1, "parent2", size=2)

    pa1.state_names = ['0', '1']
    pa2.state_names = ['0', '1']

    cn = CNot(2, "a_cnot", False, pa1, pa2, True, True)

    print("pa1 state names: ", pa1.state_names)
    print("pa2 state names: ", pa2.state_names)
    print("cnot state names: ", cn.state_names)
    print(cn.potential)
    print(cn.potential.get_total_probs())
Example #14
0
        mx : list[int]
        my : list[int]

        Returns
        -------
        int

        """
        return self.fill_trans_mat_and_st_names_of_nd(
            mx, my, dry_run=True)

if __name__ == "__main__":

    theta_degs = 35
    max_n_sum = 3

    in_nd = BayesNode(0, "parent1", size=6)

    in_nd.set_state_names_to_product(
        [range(2), range(3)], trim=False)

    pr = PolarizationRot(1, "pol_rot", in_nd, theta_degs, max_n_sum)

    print("in_nd state names: ", in_nd.state_names)
    print("pol rot state names: ", pr.state_names)
    print(pr.potential)
    print("full dict of total probs: ",
          pr.potential.get_total_probs())
    print("brief dict of total probs: ",
          pr.potential.get_total_probs(brief=True))
Example #15
0
    def build_bnet():
        """
        Builds CBnet in accompanying gif : bnet_HuangDarwiche.gif

        From "Inference Belief Networks: A Procedural Guide", by C.Huang and
        A. Darwiche

        """

        a_node = BayesNode(0, name="A")
        b_node = BayesNode(1, name="B")
        c_node = BayesNode(2, name="C")
        d_node = BayesNode(3, name="D")
        e_node = BayesNode(4, name="E")
        f_node = BayesNode(5, name="F")
        g_node = BayesNode(6, name="G")
        h_node = BayesNode(7, name="H")

        b_node.add_parent(a_node)
        c_node.add_parent(a_node)
        d_node.add_parent(b_node)
        e_node.add_parent(c_node)
        f_node.add_parent(d_node)
        f_node.add_parent(e_node)
        g_node.add_parent(c_node)
        h_node.add_parent(e_node)
        h_node.add_parent(g_node)

        nodes = {
            a_node, b_node, c_node, d_node, e_node, f_node, g_node, h_node
        }

        a_node.potential = DiscreteUniPot(False, a_node)  # P(a)
        b_node.potential = DiscreteCondPot(False, [a_node, b_node])  # P(b| a)
        c_node.potential = DiscreteCondPot(False, [a_node, c_node])
        d_node.potential = DiscreteCondPot(False, [b_node, d_node])
        e_node.potential = DiscreteCondPot(False, [c_node, e_node])

        # P(f|d, e)
        f_node.potential = DiscreteCondPot(False, [d_node, e_node, f_node])

        g_node.potential = DiscreteCondPot(False, [c_node, g_node])
        h_node.potential = DiscreteCondPot(False, [e_node, g_node, h_node])

        # in general
        # DiscreteCondPot(False, [y1, y2, y3, x]) refers to P(x| y1, y2, y3)
        # off = 0
        # on = 1

        a_node.potential.pot_arr[:] = [.5, .5]

        b_node.potential.pot_arr[1, :] = [.5, .5]
        b_node.potential.pot_arr[0, :] = [.4, .6]

        c_node.potential.pot_arr[1, :] = [.7, .3]
        c_node.potential.pot_arr[0, :] = [.2, .8]

        d_node.potential.pot_arr[1, :] = [.9, .1]
        d_node.potential.pot_arr[0, :] = [.5, .5]

        e_node.potential.pot_arr[1, :] = [.3, .7]
        e_node.potential.pot_arr[0, :] = [.6, .4]

        f_node.potential.pot_arr[1, 1, :] = [.01, .99]
        f_node.potential.pot_arr[1, 0, :] = [.01, .99]
        f_node.potential.pot_arr[0, 1, :] = [.01, .99]
        f_node.potential.pot_arr[0, 0, :] = [.99, .01]

        g_node.potential.pot_arr[1, :] = [.8, .2]
        g_node.potential.pot_arr[0, :] = [.1, .9]

        h_node.potential.pot_arr[1, 1, :] = [.05, .95]
        h_node.potential.pot_arr[1, 0, :] = [.95, .05]
        h_node.potential.pot_arr[0, 1, :] = [.95, .05]
        h_node.potential.pot_arr[0, 0, :] = [.95, .05]

        return BayesNet(nodes)
Example #16
0
    def main():
        num_of_comps = 1

        tau_mag = .5
        tau_degs = 35
        rho_degs = 45

        if num_of_comps == 1:
            size1 = 3
            size2 = 4
            max_n_sum = 5
            pa1 = BayesNode(0, "parent1", size=size1)
            pa2 = BayesNode(1, "parent2", size=size2)

            pa1.state_names = [str(k) for k in range(size1)]
            pa2.state_names = [str(k) for k in range(size2)]

            bs = BeamSplitter(2, "a_bs", pa1, pa2,
                    tau_mag, tau_degs, rho_degs, num_of_comps, max_n_sum)

            print("pa1 state names: ", pa1.state_names)
            print("pa2 state names: ", pa2.state_names)
            print("bs state names: ", bs.state_names)
            print(bs.potential)
            print("full dict of total probs: ",
                  bs.potential.get_total_probs())
            print("brief dict of total probs: ",
                  bs.potential.get_total_probs(brief=True))
        elif num_of_comps == 2:
            size1 = 6
            size2 = 8
            max_n_sum = 7
            pa1 = BayesNode(0, "parent1", size=size1)
            pa2 = BayesNode(1, "parent2", size=size2)

            pa1.set_state_names_to_product(
                [range(2), range(3)], trim=False)
            pa2.set_state_names_to_product(
                [range(2), range(4)], trim=False)

            bs = BeamSplitter(2, "a_bs", pa1, pa2,
                    tau_mag, tau_degs, rho_degs, num_of_comps, max_n_sum)

            print("pa1 state names: ", pa1.state_names)
            print("pa2 state names: ", pa2.state_names)
            print("bs state names: ", bs.state_names)
            print(bs.potential)
            print("full dict of total probs: ",
                  bs.potential.get_total_probs())
            print("brief dict of total probs: ",
                  bs.potential.get_total_probs(brief=True))
Example #17
0
    def build_bnet():
        """
        Builds simple 7 node binary tree
                     a0
                   /    \
                  b0    b1
                 /  \  /  \
                c0  c1,c2 c3

        All arrows pointing down
        """

        a0 = BayesNode(0, name="a0")

        b0 = BayesNode(1, name="b0")
        b1 = BayesNode(2, name="b1")

        c0 = BayesNode(3, name="c0")
        c1 = BayesNode(4, name="c1")
        c2 = BayesNode(5, name="c2")
        c3 = BayesNode(6, name="c3")

        a0.add_children([b0, b1])
        b0.add_children([c0, c1])
        b1.add_children([c2, c3])

        nodes = {a0, b0, b1, c0, c1, c2, c3}

        a0.potential = DiscreteUniPot(False, a0)  # P(a)

        b0.potential = DiscreteCondPot(False, [a0, b0])  # P(b| a)
        b1.potential = DiscreteCondPot(False, [a0, b1])

        c0.potential = DiscreteCondPot(False, [b0, c0])
        c1.potential = DiscreteCondPot(False, [b0, c1])
        c2.potential = DiscreteCondPot(False, [b1, c2])
        c3.potential = DiscreteCondPot(False, [b1, c3])

        # in general
        # DiscreteCondPot(False, [y1, y2, y3, x]) refers to P(x| y1, y2, y3)
        # off = 0
        # on = 1

        a0.potential.pot_arr = np.array([.7, .3])

        b0.potential.pot_arr = np.array([[.5, .5], [.4, .6]])
        b1.potential.pot_arr = np.array([[.2, .8], [.4, .6]])

        c0.potential.pot_arr = np.array([[.3, .7], [.4, .6]])
        c1.potential.pot_arr = np.array([[.5, .5], [.9, .1]])
        c2.potential.pot_arr = np.array([[.8, .2], [.4, .6]])
        c3.potential.pot_arr = np.array([[.5, .5], [.6, .4]])

        return BayesNet(nodes)
Example #18
0
        self.theta_degs = theta_degs
        self.occ_nums = occ_nums

        BayesNode.__init__(self, id_num, name, size=pa_nd.size)
        self.add_parent(pa_nd)

        self.state_names = pa_nd.state_names

        pot = DiscreteCondPot(True, [pa_nd, self], bias=0)
        self.potential = pot

        theta_rads = theta_degs*math.pi/180
        for k in range(pa_nd.size):
            if not occ_nums:
                phase = theta_rads
            else:
                num = int(pa_nd.state_names[k])
                phase = num*theta_rads
            self.potential[k, k] = cmath.exp(1j*phase)

if __name__ == "__main__":
    pa_nd = BayesNode(0, "pa_nd", size=4)
    pa_nd.state_names = [str(k) for k in range(4)]

    p_sh = PhaseShifter(1, "pshifter", pa_nd, 30, occ_nums=True)

    print("pa_nd state names: ", pa_nd.state_names)
    print("phase shifter state names: ", p_sh.state_names)
    print(p_sh.potential)
    print(p_sh.potential.get_total_probs())
Example #19
0
        BayesNode.__init__(self, id_num, name, size=size)
        self.add_parent(pa_nd)

        self.state_names = non_rep_name_list

        pot = DiscreteCondPot(is_quantum, [pa_nd, self], bias=0)
        self.potential = pot

        for k, name in enumerate(self.state_names):
            for r, pa_name in enumerate(rep_name_list):
                if name == pa_name:
                    # remember, focus node is last topo_index
                    self.potential[r, k] = 1

if __name__ == "__main__":
    pa_nd = BayesNode(0, "pa_nd", size=24)
    # has_commas = True
    has_commas = False
    pa_nd.set_state_names_to_product(
        [range(2), range(3), range(4)], trim=not has_commas)
    marg = Marginalizer(1, "marg",
        False, pa_nd, projected_axis=1, has_commas=has_commas)

    print("pa state names: ", pa_nd.state_names)
    print("marg state names: ", marg.state_names)
    print(marg.potential)
    print(marg.potential.get_total_probs())



Example #20
0
        """
        return str([node.name for node in self.ord_nodes]) \
            + "\n" + str(self.pot_arr)


from nodes.BayesNode import *
if __name__ == "__main__":
    with np.errstate(all='ignore'):
        x = np.array([2, 0]) / np.array([1, 0])
        x[x == np.inf] = 0
        x = np.nan_to_num(x)
    print("[2, 0]/[1, 0]=", x)

    # define some nodes
    a_node = BayesNode(0, name="A")
    b_node = BayesNode(1, name="B")
    c_node = BayesNode(2, name="C")
    d_node = BayesNode(3, name="D")
    e_node = BayesNode(4, name="E")
    f_node = BayesNode(5, name="F")
    g_node = BayesNode(6, name="G")

    print("\ndefine some pots")

    # Make sure if entries of numpy array are integers, to specify
    # dtype=float64 or numpy will cast them as integers and this will lead
    # to type casting errors

    ar_ab = np.arange(4, dtype=np.float64).reshape(2, 2)
    pot_ab = Potential(False, [a_node, b_node], ar_ab)
Example #21
0
        """
        if self.flipped_by_0:
            x = 1 - pa1_st
        else:  # flipped by 1
            x = pa1_st
        if self.pa1_is_control:
            bit0 = pa1_st
            bit1 = (x + pa2_st)//2
        else:  # pa2 is control
            bit0 = (x + pa2_st)//2
            bit1 = pa2_st
        foc_st = bit0 + 2*bit1
        return foc_st


if __name__ == "__main__":
    pa1 = BayesNode(0, "parent1", size=2)
    pa2 = BayesNode(1, "parent2", size=2)

    pa1.state_names = ['0', '1']
    pa2.state_names = ['0', '1']

    cn = CNot(2, "a_cnot",
        False, pa1, pa2, True, True)

    print("pa1 state names: ", pa1.state_names)
    print("pa2 state names: ", pa2.state_names)
    print("cnot state names: ", cn.state_names)
    print(cn.potential)
    print(cn.potential.get_total_probs())
Example #22
0
        return self.fill_trans_mat_and_st_names_of_nd(
            m1x, m2x, m1y, m2y, dry_run=True)

if __name__ == "__main__":

    num_of_comps = 1

    tau_mag = .5
    tau_degs = 35
    rho_degs = 45

    if num_of_comps == 1:
        size1 = 3
        size2 = 4
        max_n_sum = 5
        pa1 = BayesNode(0, "parent1", size=size1)
        pa2 = BayesNode(1, "parent2", size=size2)

        pa1.state_names = [str(k) for k in range(size1)]
        pa2.state_names = [str(k) for k in range(size2)]

        bs = BeamSplitter(2, "a_bs", pa1, pa2,
                tau_mag, tau_degs, rho_degs, num_of_comps, max_n_sum)

        print("pa1 state names: ", pa1.state_names)
        print("pa2 state names: ", pa2.state_names)
        print("bs state names: ", bs.state_names)
        print(bs.potential)
        print("full dict of total probs: ",
              bs.potential.get_total_probs())
        print("brief dict of total probs: ",
Example #23
0
        Parameters
        ----------
        nd : BayesNode

        Returns
        -------
        list[set[BayesNode]]

        """
        edges = list()
        neig_list = list(nd.neighbors)
        for k in range(len(neig_list)):
            n1 = neig_list[k]
            for n2 in neig_list[k + 1:]:
                if not n2.has_neighbor(n1):
                    edges.append({n1, n2})
        return edges


from nodes.Node import *
if __name__ == "__main__":
    a = BayesNode(0, name="a")
    b = BayesNode(1, name="b")
    c = BayesNode(2, name="c")

    a.add_neighbor(b)
    a.add_neighbor(c)

    assert (Star.get_missing_edges_of_node(a) == [{b, c}])
Example #24
0
    def main():
        with np.errstate(all='ignore'):
            x = np.array([2, 0 + 0j]) / np.array([1, 0])
            x[~np.isfinite(x)] = 0
        print("[2, 0+0j]/[1, 0]=", x)

        with np.errstate(all='ignore'):
            x = np.array([2, 5]) / np.array([1, 0])
            x[~np.isfinite(x)] = 0
        print("[2, 5]/[1, 0]=", x)

        # define some nodes
        a_node = BayesNode(0, name="A")
        b_node = BayesNode(1, name="B")
        c_node = BayesNode(2, name="C")
        d_node = BayesNode(3, name="D")
        e_node = BayesNode(4, name="E")
        f_node = BayesNode(5, name="F")
        g_node = BayesNode(6, name="G")

        print("\n-----------------define some pots")

        # Make sure if entries of numpy array are integers, to specify
        # dtype=float64 or numpy will cast them as integers and this will lead
        # to type casting errors

        ar_ab = np.arange(4, dtype=np.float64).reshape(2, 2)
        pot_ab = Potential(False, [a_node, b_node], ar_ab)
        print("pot_ab:", pot_ab)

        ar_ab2 = np.arange(0, 40, 10, dtype=np.float64).reshape(2, 2)
        pot_ab2 = Potential(False, [a_node, b_node], ar_ab2)
        print("pot_ab2:", pot_ab2)

        ar_bc = np.arange(0, 40, 10, dtype=np.float64).reshape(2, 2)
        pot_bc = Potential(False, [b_node, c_node], ar_bc)
        print("pot_bc:", pot_bc)

        ar_abc = np.arange(8, dtype=np.float64).reshape((2, 2, 2))
        pot_abc = Potential(False, [a_node, b_node, c_node], ar_abc)
        print("pot_abc:", pot_abc)

        ar_bcd = np.arange(0, 80, 10, dtype=np.float64).reshape((2, 2, 2))
        pot_bcd = Potential(False, [b_node, c_node, d_node], ar_bcd)
        print("pot_bcd:", pot_bcd)

        # no need to specify dtype here because using decimal points
        ar_ecg = np.array([[[0., 0.60000002], [0., 0.30000001]],
                           [[0., 0.40000001], [0., 0.69999999]]])
        pot_ecg = Potential(False, [e_node, c_node, g_node], ar_ecg)
        print("pot_ecg:", pot_ecg)

        print("\n-----------------try transpose, distance and ==")

        new_abc = cp.deepcopy(pot_abc)
        new_abc.set_to_transpose([b_node, a_node, c_node])
        print("pot_abc:", pot_abc)
        print("new_abc:", new_abc)
        assert pot_abc == new_abc
        assert pot_abc != (new_abc + 5)

        print("distance(pot_abc, new_abc)=",
              Potential.distance(new_abc, pot_abc))
        print("pot_abc == new_abc?", pot_abc == new_abc)

        print("distance(pot_abc, pot_bc)=",
              Potential.distance(pot_abc, pot_bc))
        print("pot_abc == pot_bc?", pot_abc == pot_bc)

        print("\n-----------------try add, sub, mult")

        print('pot_ab:', pot_ab)
        print('pot_ab2:', pot_ab2)
        print("pot_ab + 5:", pot_ab + 5)
        print("pot_ab - 5:", pot_ab - 5)
        print("pot_ab * 5:", pot_ab * 5)
        print("pot_ab + pot_ab2:", pot_ab + pot_ab2)
        print("pot_ab - pot_ab2:", pot_ab - pot_ab2)
        print("pot_ab * pot_ab2:", pot_ab * pot_ab2)
        print("pot_ab + pot_bc:", pot_ab + pot_bc)
        print("pot_ab - pot_bc:", pot_ab - pot_bc)
        print("pot_ab * pot_bc:", pot_ab * pot_bc)

        print("\n-----------------try iadd, isub, and imul")

        new_abc = cp.deepcopy(pot_abc)
        new_abc.set_to_transpose([b_node, a_node, c_node])
        new_abc += 5
        assert new_abc == pot_abc + 5

        new_abc = cp.deepcopy(pot_abc)
        new_abc.set_to_transpose([b_node, a_node, c_node])
        new_abc += pot_bc
        assert new_abc == pot_abc + pot_bc

        new_abc = cp.deepcopy(pot_abc)
        new_abc.set_to_transpose([b_node, a_node, c_node])
        new_abc -= pot_bc
        assert new_abc == pot_abc - pot_bc

        new_abc = cp.deepcopy(pot_abc)
        new_abc.set_to_transpose([b_node, a_node, c_node])
        new_abc *= pot_bc
        assert new_abc == pot_abc * pot_bc

        print("\n-----------------try truediv")

        print("pot_ab/pot_ab2 =", pot_ab / pot_ab2)

        print("\n-----------------try itruediv")
        new_ab = cp.deepcopy(pot_ab)
        new_ab.set_to_transpose([b_node, a_node])
        new_ab /= pot_ab2
        print("pot_ab/pot_ab2=", new_ab)
        assert new_ab == pot_ab / pot_ab2

        print("\n-----------------try marginalizing")

        new_abc = cp.deepcopy(pot_abc)
        print("new_abc=", new_abc)
        new_ac = new_abc.get_new_marginal([a_node, c_node])
        print("sum_b new_abc=", new_ac)

        print("\nnew_abc=", new_abc)
        new_ab = new_abc.get_new_marginal([a_node, b_node])
        print("sum_c new_abc=", new_ab)

        print("\npot_ecg:", pot_ecg)
        pot_ge = pot_ecg.get_new_marginal([g_node, e_node])
        print("sum_c  pot_ecg=", pot_ge)
Example #25
0
        By an edge we mean a set of two nodes.

        Parameters
        ----------
        nd : BayesNode

        Returns
        -------
        list[set[BayesNode]]

        """
        edges = list()
        neig_list = list(nd.neighbors)
        for k in range(len(neig_list)):
            n1 = neig_list[k]
            for n2 in neig_list[k+1:]:
                if not n2.has_neighbor(n1):
                    edges.append({n1, n2})
        return edges

from nodes.Node import *
if __name__ == "__main__":
    a = BayesNode(0, name="a")
    b = BayesNode(1, name="b")
    c = BayesNode(2, name="c")

    a.add_neighbor(b)
    a.add_neighbor(c)

    assert(Star.get_missing_edges_of_node(a) == [{b, c}])
Example #26
0
    def build_bnet():
        """
        Builds QBnet called QuWetGrass with diamond shape
                Cloudy
                /    \
             Rain    Sprinkler
               \      /
               WetGrass
        All arrows pointing down

        """

        cl = BayesNode(0, name="Cloudy")
        sp = BayesNode(1, name="Sprinkler")
        ra = BayesNode(2, name="Rain")
        we = BayesNode(3, name="WetGrass")

        we.add_parent(sp)
        we.add_parent(ra)
        sp.add_parent(cl)
        ra.add_parent(cl)

        nodes = {cl, ra, sp, we}

        cl.potential = DiscreteUniPot(True, cl)  # P(a)
        sp.potential = DiscreteCondPot(True, [cl, sp])  # P(b| a)
        ra.potential = DiscreteCondPot(True, [cl, ra])
        we.potential = DiscreteCondPot(True, [sp, ra, we])

        # in general
        # DiscreteCondPot(True, [y1, y2, y3, x]) refers to A(x| y1, y2, y3)
        # off = 0
        # on = 1

        cl.potential.pot_arr[:] = [0.5 + 0.1j, 0.5]

        ra.potential.pot_arr[1, :] = [0.5 - 0.1j, 0.5 + 0.3j]
        ra.potential.pot_arr[0, :] = [0.4, 0.6 - 0.7j]

        sp.potential.pot_arr[1, :] = [0.7 + 3.0j, 0.3 - 1.0j]
        sp.potential.pot_arr[0, :] = [0.2 + 0.5j, 0.8]

        we.potential.pot_arr[1, 1, :] = [0.01 + 1j, 0.99]
        we.potential.pot_arr[1, 0, :] = [0.01 - 5.0j, 0.99]
        we.potential.pot_arr[0, 1, :] = [0.01, 0.99 + 2.3j]
        we.potential.pot_arr[0, 0, :] = [0.99, 0.01 - 0.01j]

        cl.potential.normalize_self()
        ra.potential.normalize_self()
        sp.potential.normalize_self()
        we.potential.normalize_self()

        return BayesNet(nodes)
Example #27
0
        elif n == 1 and m == 1:
            x = c
            y = -theta_hat[3] * s
        elif n == 0 and m == 1:
            x = theta_hat[2] * s
            y = theta_hat[1] * s
        elif n == 1 and m == 0:
            x = -theta_hat[2] * s
            y = theta_hat[1] * s
        else:
            x = 0
            y = 0

        s = math.sin(rads[0])
        c = math.cos(rads[0])

        return (c * x - s * y) + 1j * (c * y + s * x)


if __name__ == "__main__":
    pa_nd = BayesNode(0, "pa_nd", size=2)
    pa_nd.state_names = ['0', '1']

    thetas_degs = [20, 30, 40, 60]
    qr = QubitRot(1, "rot", pa_nd, thetas_degs)

    print("pa_nd state names: ", pa_nd.state_names)
    print("qubit rot state names: ", qr.state_names)
    print(qr.potential)
    print(qr.potential.get_total_probs())
Example #28
0
    def build_bnet():
        """
        Builds CBnet called WetGrass with diamond shape
                Cloudy
                /    \
             Rain    Sprinkler
               \      /
               WetGrass
        All arrows pointing down
        """

        cl = BayesNode(0, name="Cloudy")
        sp = BayesNode(1, name="Sprinkler")
        ra = BayesNode(2, name="Rain")
        we = BayesNode(3, name="WetGrass")

        we.add_parent(sp)
        we.add_parent(ra)
        sp.add_parent(cl)
        ra.add_parent(cl)

        nodes = {cl, ra, sp, we}

        cl.potential = DiscreteUniPot(False, cl)  # P(a)
        sp.potential = DiscreteCondPot(False, [cl, sp])  # P(b| a)
        ra.potential = DiscreteCondPot(False, [cl, ra])
        we.potential = DiscreteCondPot(False, [sp, ra, we])

        # in general
        # DiscreteCondPot(False, [y1, y2, y3, x]) refers to P(x| y1, y2, y3)
        # off = 0
        # on = 1

        cl.potential.pot_arr[:] = [.5, .5]

        ra.potential.pot_arr[1, :] = [.5, .5]
        ra.potential.pot_arr[0, :] = [.4, .6]

        sp.potential.pot_arr[1, :] = [.7, .3]
        sp.potential.pot_arr[0, :] = [.2, .8]

        we.potential.pot_arr[1, 1, :] = [.01, .99]
        we.potential.pot_arr[1, 0, :] = [.01, .99]
        we.potential.pot_arr[0, 1, :] = [.01, .99]
        we.potential.pot_arr[0, 0, :] = [.99, .01]

        return BayesNet(nodes)
Example #29
0
        mx : list[int]
        my : list[int]

        Returns
        -------
        int

        """
        return self.fill_trans_mat_and_st_names_of_nd(
            mx, my, dry_run=True)

if __name__ == "__main__":

    theta_degs = 35
    max_n_sum = 3

    in_nd = BayesNode(0, "parent1", size=6)

    in_nd.set_state_names_to_product(
        [range(2), range(3)], trim=False)

    pr = PolarizationRot(1, "pol_rot", in_nd, theta_degs, max_n_sum)

    print("in_nd state names: ", in_nd.state_names)
    print("pol rot state names: ", pr.state_names)
    print(pr.potential)
    print("full dict of total probs: ",
          pr.potential.get_total_probs())
    print("brief dict of total probs: ",
          pr.potential.get_total_probs(brief=True))
Example #30
0
        elif n == 1 and m == 1:
            x = c
            y = -theta_hat[3]*s
        elif n == 0 and m == 1:
            x = theta_hat[2]*s
            y = theta_hat[1]*s
        elif n == 1 and m == 0:
            x = -theta_hat[2]*s
            y = theta_hat[1]*s
        else:
            x = 0
            y = 0

        s = math.sin(rads[0])
        c = math.cos(rads[0])

        return (c*x - s*y) + 1j*(c*y + s*x)


if __name__ == "__main__":
    pa_nd = BayesNode(0, "pa_nd", size=2)
    pa_nd.state_names = ['0', '1']

    thetas_degs = [20, 30, 40, 60]
    qr = QubitRot(1, "rot", pa_nd, thetas_degs)

    print("pa_nd state names: ", pa_nd.state_names)
    print("qubit rot state names: ", qr.state_names)
    print(qr.potential)
    print(qr.potential.get_total_probs())
    def build_bnet():
        """
        Builds QBnet called QuWetGrass with diamond shape
                Cloudy
                /    \
             Rain    Sprinkler
               \      /
               WetGrass
        All arrows pointing down

        """

        cl = BayesNode(0, name="Cloudy")
        sp = BayesNode(1, name="Sprinkler")
        ra = BayesNode(2, name="Rain")
        we = BayesNode(3, name="WetGrass")

        we.add_parent(sp)
        we.add_parent(ra)
        sp.add_parent(cl)
        ra.add_parent(cl)

        nodes = {cl, ra, sp, we}

        cl.potential = DiscreteUniPot(True, cl)  # P(a)
        sp.potential = DiscreteCondPot(True, [cl, sp])  # P(b| a)
        ra.potential = DiscreteCondPot(True, [cl, ra])
        we.potential = DiscreteCondPot(True, [sp, ra, we])

        # in general
        # DiscreteCondPot(True, [y1, y2, y3, x]) refers to A(x| y1, y2, y3)
        # off = 0
        # on = 1

        cl.potential.pot_arr[:] = [.5 + .1j, .5]

        ra.potential.pot_arr[1, :] = [.5 - .1j, .5 + .3j]
        ra.potential.pot_arr[0, :] = [.4, .6 - .7j]

        sp.potential.pot_arr[1, :] = [.7 + 3.j, .3 - 1.j]
        sp.potential.pot_arr[0, :] = [.2 + .5j, .8]

        we.potential.pot_arr[1, 1, :] = [.01 + 1j, .99]
        we.potential.pot_arr[1, 0, :] = [.01 - 5.j, .99]
        we.potential.pot_arr[0, 1, :] = [.01, .99 + 2.3j]
        we.potential.pot_arr[0, 0, :] = [.99, .01 - .01j]

        cl.potential.normalize_self()
        ra.potential.normalize_self()
        sp.potential.normalize_self()
        we.potential.normalize_self()

        return BayesNet(nodes)
Example #32
0
    def build_bnet():
        """
        Builds CBnet in accompanying gif : bnet_HuangDarwiche.gif

        From "Inference Belief Networks: A Procedural Guide", by C.Huang and
        A. Darwiche

        """

        a_node = BayesNode(0, name="A")
        b_node = BayesNode(1, name="B")
        c_node = BayesNode(2, name="C")
        d_node = BayesNode(3, name="D")
        e_node = BayesNode(4, name="E")
        f_node = BayesNode(5, name="F")
        g_node = BayesNode(6, name="G")
        h_node = BayesNode(7, name="H")

        b_node.add_parent(a_node)
        c_node.add_parent(a_node)
        d_node.add_parent(b_node)
        e_node.add_parent(c_node)
        f_node.add_parent(d_node)
        f_node.add_parent(e_node)
        g_node.add_parent(c_node)
        h_node.add_parent(e_node)
        h_node.add_parent(g_node)

        nodes = {a_node, b_node, c_node, d_node, e_node,
                f_node, g_node, h_node}

        a_node.potential = DiscreteUniPot(False, a_node)  # P(a)
        b_node.potential = DiscreteCondPot(False, [a_node, b_node])  # P(b| a)
        c_node.potential = DiscreteCondPot(False, [a_node, c_node])
        d_node.potential = DiscreteCondPot(False, [b_node, d_node])
        e_node.potential = DiscreteCondPot(False, [c_node, e_node])

        # P(f|d, e)
        f_node.potential = DiscreteCondPot(False, [d_node, e_node, f_node])

        g_node.potential = DiscreteCondPot(False, [c_node, g_node])
        h_node.potential = DiscreteCondPot(False, [e_node, g_node, h_node])

        # in general
        # DiscreteCondPot(False, [y1, y2, y3, x]) refers to P(x| y1, y2, y3)
        # off = 0
        # on = 1

        a_node.potential.pot_arr[:] = [.5, .5]

        b_node.potential.pot_arr[1, :] = [.5, .5]
        b_node.potential.pot_arr[0, :] = [.4, .6]

        c_node.potential.pot_arr[1, :] = [.7, .3]
        c_node.potential.pot_arr[0, :] = [.2, .8]

        d_node.potential.pot_arr[1, :] = [.9, .1]
        d_node.potential.pot_arr[0, :] = [.5, .5]

        e_node.potential.pot_arr[1, :] = [.3, .7]
        e_node.potential.pot_arr[0, :] = [.6, .4]

        f_node.potential.pot_arr[1, 1, :] = [.01, .99]
        f_node.potential.pot_arr[1, 0, :] = [.01, .99]
        f_node.potential.pot_arr[0, 1, :] = [.01, .99]
        f_node.potential.pot_arr[0, 0, :] = [.99, .01]

        g_node.potential.pot_arr[1, :] = [.8, .2]
        g_node.potential.pot_arr[0, :] = [.1, .9]

        h_node.potential.pot_arr[1, 1, :] = [.05, .95]
        h_node.potential.pot_arr[1, 0, :] = [.95, .05]
        h_node.potential.pot_arr[0, 1, :] = [.95, .05]
        h_node.potential.pot_arr[0, 0, :] = [.95, .05]

        return BayesNet(nodes)