Exemplo n.º 1
0
    def petersenijk(self, tp='pdf'):
        colored = False
        size = 'normal'
        node = NodeBrush('basic', size=size)
        edge = EdgeBrush('---', lw=2.)
        label_count = [0]

        def assign_label():
            label_count[0] += 1
            return "%c" % (96 + label_count[0])

        with DynamicShow((4, 4), filename='_petersenijk.%s' % tp) as ds:
            x = [0, 1]
            y = [0, 2]
            ys = []
            xs = []
            for i in range(5):
                xi = node >> rotate(x, np.pi / 5 * 2 * i)
                yi = node >> rotate(y, np.pi / 5 * 2 * i)
                xi.text("%d" % (i + 1))
                yi.text("%d" % (i + 6))
                xs.append(xi)
                ys.append(yi)
                c = 'r' if (i == 0 and colored) else 'k'
                withcolor(c, edge, (xi, yi)).text(assign_label())
            for i in range(5):
                c = 'g' if i == 0 else ('b' if i == 4 else 'k')
                if not colored: c = 'k'
                withcolor(c, edge,
                          (xs[i], xs[(i + 2) % 5])).text(assign_label())
                (edge >> (ys[i], ys[(i + 1) % 5])).text(assign_label())
Exemplo n.º 2
0
def visualize_network(network: AcyclicNetwork):
    num_layers = len(network.layer_info)
    nodes_per_layer = [
        (network.layer_info[i + 1][0] - network.layer_info[i][0]) + 1
        for i in range(num_layers - 1)
    ]
    nodes_per_layer = [network.layer_info[0][0]] + nodes_per_layer
    max_num_nodes = max(nodes_per_layer)
    vertical_gap_size = 1.0 / (num_layers + 1)
    radius = 5

    with DynamicShow((10, 10), 'test.png') as d:
        brush = NodeBrush('nn.input', ax=d.ax)
        edge_brush = EdgeBrush('-', ax=d.ax, lw=2)

        nodes = []
        for y in range(num_layers):
            for x in range(nodes_per_layer[y]):
                horizontal_gap = 1.0 / (nodes_per_layer[y] + 1)
                nodes.append(brush >> (
                    (x + 1) * horizontal_gap, vertical_gap_size * (y + 1)))

        conn_idx = 0

        for layer in network.layer_info:
            _, end_connection_idx = layer

            for idx in range(con_idx, end_connection_idx):
                from_id, to_id, _ = network.connections[idx]
                edge_brush >> (nodes[from_id], nodes[to_id])

            con_idx = end_connection_idx
Exemplo n.º 3
0
def tebd():
    with DynamicShow((4, 4), filename='_contract.png') as ds:
        size = 'normal'
        mps = NodeBrush('tn.mps', size=size)
        # invisible node can be used as a placeholder
        invisible = NodeBrush('invisible', ds.ax, size=size)
        left = NodeBrush('box', size=(0.3, 1.3), color='#333333')
        mpo = NodeBrush('tn.mpo', size=size)
        edge = EdgeBrush('---', ds.ax, lw=2.)
        l = left >> (0, 1)
        dn = mps >> (1.2, 0)
        up = mps >> (1.2, 2.0)
        o = mpo >> (1.2, 1)
        dn_ = invisible >> (2.2, 0)
        up_ = invisible >> (2.2, 2.0)
        o_ = invisible >> (2.2, 1)
        for i, r in enumerate([up, o, dn]):
            ei = edge >> (l.pin('right', align=r), r)
            ei.text('%d'%(i+1), 'top', fontsize=16)
        euo = edge >> (up, o)
        edo = edge >> (dn, o)
        euo.text(4, 'right', fontsize=16)
        edo.text(5, 'right', fontsize=16)
        euu = edge >> (up, up_)
        eoo = edge >> (o, o_)
        edd = edge >> (dn, dn_)
        euu.text(6, 'top', fontsize=16)
        eoo.text(7, 'top', fontsize=16)
        edd.text(8, 'top', fontsize=16)
Exemplo n.º 4
0
    def _petersen(self, colored, tp='pdf'):
        size = 'normal'
        node = NodeBrush('basic', size=size)
        edge = EdgeBrush('---', lw=2.)

        with DynamicShow(
            (4, 4),
                filename='%spetersen.%s' % ('c' if colored else '', tp)) as ds:
            x = [0, 1]
            y = [0, 2]
            ys = []
            xs = []
            for i in range(5):
                xi = node >> rotate(x, np.pi / 5 * 2 * i)
                yi = node >> rotate(y, np.pi / 5 * 2 * i)
                xi.text("%d" % (i + 6))
                yi.text("%d" % (i + 1))
                xs.append(xi)
                ys.append(yi)
                c = 'r' if (i == 0 and colored) else 'k'
                withcolor(c, edge, (xi, yi))
            for i in range(5):
                c = 'g' if i == 0 else ('b' if i == 3 else 'k')
                if not colored: c = 'k'
                withcolor(c, edge, (xs[i], xs[(i + 2) % 5]))
                edge >> (ys[i], ys[(i + 1) % 5])
Exemplo n.º 5
0
    def mapping(self, tp="gif"):
        with DynamicShow(figsize=(5, 4), filename="mapping.%s" % tp) as ds:
            xs = [0, 0, -1, 1, -2, 0, 2.0]
            ys = [3, 2, 1, 1, 0, 0, 0.0]
            locs = zip(xs, ys)
            A, B, C, D, E, F, G = [nbrush >> loc for loc in locs]
            for x in ["A", "B", "C", "D", "E", "F", "G"]:
                eval("%s.text('%s')" % (x, x))

            pairs = [(A, B), (B, C), (B, D), (C, E), (C, F), (D, F), (D, G),
                     (E, F), (F, G)]
            edges = [edge >> pair for pair in pairs]

            def share_vertex(pair_i, pair_j):
                return (pair_i[0] in pair_j) or (pair_i[1] in pair_j)

            enodes = []

            def f1():
                enodes[:] = [e2v >> e.position for e in edges]
                return enodes

            def f2():
                Ne = len(pairs)
                els = []
                for i in range(Ne):
                    for j in range(i + 1, Ne):
                        if share_vertex(pairs[i], pairs[j]):
                            els.append(edge2 >> (enodes[i], enodes[j]))
                return els

            ds.steps = [f1, f2]
Exemplo n.º 6
0
def ghz4():
    '''4 bit GHZ circuit, applicable on ibmqx4 circuit.'''
    num_bit = 4
    with DynamicShow((5, 3), '_exact_ghz4_circuit.png') as ds:
        handler = QuantumCircuit(num_bit=4, y0=2.)
        handler.x += 0.5
        handler.gate(_.GATE, 0, 'X')
        for i in range(1, num_bit):
            handler.gate(_.GATE, i, 'H')
        handler.x += 1
        handler.gate((_.C, _.NOT), (1, 0))
        handler.gate((_.C, _.NOT), (3, 2))
        handler.x += 0.7
        handler.gate((_.C, _.NOT), (2, 0))
        handler.x += 0.7
        handler.gate((_.C, _.NOT), (3, 2))
        handler.x += 1
        for i in range(num_bit):
            handler.gate(_.GATE, i, 'H')
        handler.x += 1
        for i in range(num_bit):
            handler.gate(_.MEASURE, i)
        handler.edge.style = '='
        handler.x += 0.8
        for i in range(num_bit):
            handler.gate(_.END, i)

        # text |0>s
        for i in range(num_bit):
            plt.text(*handler.get_position(i, x=-0.5), r'$\left\vert0\right\rangle_{Q_%d}$' %
                     i, va='center', ha='center', fontsize=18)
Exemplo n.º 7
0
def qft():
    num_bit = 5
    with DynamicShow((10, 3.5), '_qft.png') as ds:
        handler = QuantumCircuit(num_bit=num_bit, y0=2.)
        handler.x += 0.7
        for i in range(num_bit):
            if i ==1:
                context = handler.block(slice(i, num_bit-1), pad_y=0.1, pad_x=0.2)
                boxes = context.__enter__()
            for k in range(i, num_bit):
                if i==k:
                    handler.gate(_.GATE, i, 'H')
                else:
                    if i ==0 and k==1+2:
                        context = handler.block(slice(i, k), pad_y=0.1, pad_x = 0.15)
                        boxes = context.__enter__()
                    handler.gate((_.C, _.WIDE), (k, i), ['',r'R${}_%d$'%(k-i+1)])
                    if i ==0 and k==1+2:
                        context.__exit__(None, None, None)
                        boxes[0].text("A", "top")
                if i==1 and k==num_bit-1:
                    context.__exit__(None, None, None)
                    boxes[0].text("B", "top")
                handler.x+=1.0
            handler.x+=0.2
        for i in range(num_bit):
            handler.gate(_.END, i)

        # text |0>s
        for i in range(num_bit):
            plt.text(*handler.get_position(i, x=-0.5), r'$\left\vert ?\right\rangle_{Q_%d}$' %
                     (i+1), va='center', ha='center', fontsize=16)
        plt.text(8.5, -3, "Quantum Fourier Transformation circuit of size 5", ha='center')
Exemplo n.º 8
0
def plot_net(num_node_list, figsize, filename, fontsize=16):
    with DynamicShow(figsize, filename + '.svg') as d:  # 隐藏坐标轴
        seq_list = draw_feed_forward(d.ax, num_node_list=num_node_list)
        for i, layer_nodes in enumerate(seq_list):
            [
                node.text(r'$a_{%i}^{(%i)}$' % (j, i), 'center', fontsize)
                for j, node in enumerate(layer_nodes)
            ]
Exemplo n.º 9
0
def twoqubit():
    INIT = NodeBrush("tn.tri", size=0.36, color="none", rotate=np.pi / 6)
    PIN = NodeBrush("pin")

    handler = QuantumCircuit(num_bit=2, y0=2.)
    handler.x -= 0.5

    itheta = [0]

    def count():
        itheta[0] += 1
        return itheta[0]

    def reset():
        handler.edge.lw = 0
        handler.gate(INIT, 0, "0", fontsize=12)
        handler.edge.lw = 2

    def rxgate(i):
        handler.gate(_.WIDE, i, r'$R_x^{%d}$' % count(), fontsize=14)

    def rzgate(i):
        handler.gate(_.WIDE, i, r'$R_z^{%d}$' % count(), fontsize=14)

    def cphase():
        handler.gate((_.C, _.GATE), (0, 1),
                     ["", r"$\theta^{%d}$" % count()],
                     fontsize=12)

    with DynamicShow((12, 2), 'twoqubit.png') as ds:
        depth = 2
        for i in range(3):
            reset()
            if i == 0:
                handler.gate(INIT, 1, '0', fontsize=12)
                handler.gate(INIT, 0, '0', fontsize=12)
            handler.x += 1
            #for di in range(depth):
            with handler.block(slice(0, 1), pad_x=0.2, pad_y=0.1) as b:
                rxgate(0)
                rxgate(1)
                handler.x += 1.0
                rzgate(0)
                rzgate(1)

                handler.x += 1.0
                cphase()

            b[0].text(r"$\times d$", "top")

            handler.x += 1
            handler.gate(_.MEASURE, 0)
            if i != 2:
                handler.x += 0.7
                handler.gate(_.GATE, 0, r'$\circlearrowleft$', fontsize=16)
                handler.x += 0.5
            else:
                handler.gate(_.MEASURE, 1)
Exemplo n.º 10
0
def tebd():
    # define a grid with grid space dx = 1, and dy = 1.
    grid = Grid((1, 1))

    # define a set of brushes.
    # NodeBrush can place a node at some location, like `node_brush >> (x, y)`,
    # and it will return a Node instance.
    # EdgeBrush can connect two Nodes (or Pin as a special Node),
    # like `edge_brush >> node_a, node_b`, and will return an Edge instance.
    size = 'normal'
    mps = NodeBrush('tn.mps', size=size)
    # invisible node can be used as a placeholder
    invisible_mps = NodeBrush('invisible', size=size)
    # define a two site mpo, which will occupy 1 column, 0 rows.
    mpo21 = NodeBrush('tn.mpo', size=size)
    edge = EdgeBrush('-', lw=2.)

    with DynamicShow((6, 4), filename='_tebd.png') as ds:
        # add a sequence of mps nodes, a store them in a list for future use.
        mps_list = []
        for i in range(8):
            mps_list.append(mps >> grid[i, 0])
            mps_list[-1].text(r'$\sigma_%d$' % i, position='bottom')
        mps_list.append(invisible_mps >> grid[i + 1, 0])

        # add mpo and connect nodes
        for layer in range(4):
            # set brush color, it will overide theme color!
            # You can set brush color to None to restore theme color.
            mpo21.color = theme.RED if layer % 2 == 0 else theme.GREEN
            mpo_list = []
            start = layer % 2
            for i, (mps_l, mps_r) in enumerate(
                    zip(mps_list[start::2], mps_list[start + 1::2])):
                # place an two site mpo slightly above the center of two mps nodes
                y = mps_l.position[1] + layer + 1
                mpo_list.append(
                    mpo21 >> grid[mps_l.position[0]:mps_r.position[0], y:y])
                if layer == 0:
                    # if this is the first mpo layer, connect mps and newly added mpo.
                    pin_l = mps_l
                    pin_r = mps_r
                else:
                    # otherwise, place a pin at the top surface of previous mpo,
                    # we also require it horizontally aligned to some `mps_l` object.
                    # pin is a special node, which is zero sized,
                    # we can use it to connect nodes, add texts.
                    # if you're about to place some pin at `left` or
                    # `right` surface of a node,
                    # align is then intepreted as vertial align.
                    pin_l = mpo_list_pre[i].pin('top', align=mps_l)
                    pin_r = mpo_list_pre[i].pin('top', align=mps_r)
                if layer < 2:
                    edge >> (mps_l, mps_r)
                edge >> (pin_l, mpo_list[-1].pin('bottom', align=mps_l))
                edge >> (pin_r, mpo_list[-1].pin('bottom', align=mps_r))
            mpo_list_pre = mpo_list
Exemplo n.º 11
0
def grover():
    num_bit = 5
    niter = 2
    _.BOX.size = (0.8, 0.3)
    with DynamicShow((10, 3.5), '_grover.png') as ds:
        handler = QuantumCircuit(num_bit=num_bit,
                                 y0=2.,
                                 locs=-0.8 * np.arange(num_bit))
        handler.x -= 0.8
        with handler.block(slice(0, num_bit - 1), pad_x=0.2,
                           pad_y=0.2) as boxes:
            handler.x += 2.0
            handler.gate(_.BOX, slice(0, num_bit), '$U$')
            handler.x += 0.5
        boxes[0].text("A", 'top')
        handler.x += 1.5
        with handler.block(slice(0, num_bit - 1), pad_x=0.2,
                           pad_y=0.2) as boxes:
            handler.x += 0.5
            handler.gate(_.BOX, slice(0, num_bit), r'oracle', fontsize=14)
            handler.x += 1.5
            with handler.block(slice(0, num_bit - 1), pad_x=0.1,
                               pad_y=0.1) as bxs:
                handler.x += 0.5
                handler.gate(_.BOX, slice(0, num_bit), r'$U^\dagger$')
                handler.x += 1.5
                handler.gate([_.NC] * (num_bit - 1) + [_.WIDE], range(num_bit),
                             [''] * (num_bit - 1) + ['-Z'])
                handler.x += 1.5
                handler.gate(_.BOX, slice(0, num_bit), '$U$')
                handler.x += 0.5
            bxs[0].text('B', 'top')
        boxes[0].text('C', 'top')
        handler.x += 2.0
        for i in range(niter - 1):
            handler.gate(_.BOX, slice(0, num_bit), r'oracle', fontsize=14)
            handler.x += 2.0
            handler.gate(_.BOX, slice(0, num_bit), r'$U^\dagger$')
            handler.x += 1.5
            handler.gate([_.NC] * (num_bit - 1) + [_.WIDE], range(num_bit),
                         [''] * (num_bit - 1) + ['-Z'])
            handler.x += 1.5
            handler.gate(_.BOX, slice(0, num_bit), '$U$')
            handler.x += 2.5
        handler.x -= 0.8
        for i in range(num_bit):
            handler.gate(_.END, i)

        # text |0>s
        for i in range(num_bit):
            plt.text(*handler.get_position(i, x=-0.5),
                     r'$\left\vert 0\right\rangle_{Q_%d}$' % (i + 1),
                     va='center',
                     ha='center',
                     fontsize=16)
        plt.text(8.5, -4.2, "Grover Search Circuit", ha='center')
Exemplo n.º 12
0
def real_bp():
    with DynamicShow((6, 6), '_feed_forward.png') as d:  # 隐藏坐标轴
        seq_list = draw_feed_forward(d.ax,
                                     num_node_list=[4, 5, 5, 5, 6, 6, 6, 1])
        print("!!!")
        for i, layer_nodes in enumerate(seq_list):
            [
                node.text('$z_{%i}^{(%i)}$' % (j, i), 'center', fontsize=16)
                for j, node in enumerate(layer_nodes)
            ]
Exemplo n.º 13
0
    def origin(self, tp="png"):
        with DynamicShow(figsize=(5, 4), filename="origin.%s" % tp) as ds:
            xs = [0, 0, -1, 1, -2, 0, 2.0]
            ys = [3, 2, 1, 1, 0, 0, 0.0]
            locs = zip(xs, ys)
            A, B, C, D, E, F, G = [nbrush >> loc for loc in locs]
            for x in ["A", "B", "C", "D", "E", "F", "G"]:
                eval("%s.text('%s')" % (x, x))

            pairs = [(A, B), (B, C), (B, D), (C, E), (C, F), (D, F), (D, G),
                     (E, F), (F, G)]
            edges = [edge >> pair for pair in pairs]
Exemplo n.º 14
0
def fourqubit():
    nbit = 4
    INIT = NodeBrush("tn.tri", size=0.36, color="none", rotate=np.pi / 6)
    PIN = NodeBrush("pin")

    handler = QuantumCircuit(num_bit=nbit, y0=2.)
    handler.x -= 0.5

    itheta = [0]

    def count():
        itheta[0] += 1
        return itheta[0]

    def reset():
        handler.edge.lw = 0
        handler.gate(INIT, 0, "0", fontsize=12)
        handler.edge.lw = 2

    def rxgate(i):
        handler.gate(_.WIDE, i, r'$R_x^{%d}$' % count(), fontsize=14)

    def rzgate(i):
        handler.gate(_.WIDE, i, r'$R_z^{%d}$' % count(), fontsize=14)

    def cphase(i, j):
        handler.gate((_.C, _.GATE), (i, j),
                     ["", r"$\theta^{%d}$" % count()],
                     fontsize=12)

    with DynamicShow((8, 3), 'fourqubit.png') as ds:
        handler.edge.lw = 2
        for i in range(nbit):
            handler.gate(INIT, i, '0', fontsize=12)

        handler.x += 1

        for i in range(nbit - 1):
            with handler.block(slice(i, nbit - 1), pad_x=0.2, pad_y=0.1) as b:
                rxgate(i)
                rxgate(nbit - 1)
                handler.x += 1.0
                rzgate(i)
                rzgate(nbit - 1)

                handler.x += 1.0
                cphase(i, nbit - 1)
            b[0].text(r"$\times d$", "top")
            handler.x += 1.2

        for i in range(nbit):
            handler.gate(_.MEASURE, i)
Exemplo n.º 15
0
    def draw(self, file=None, size=(10, 6)):
        """
        Draw the network architecture 
        Param:
            - file: The file where the image will be saved. Default: None
            - size: the image size. Default: (10,6)
        """

        with DynamicShow(size, filename=file) as d:

            num_hidden_layer = len(self.architecture) - 2
            token_list = ['\sigma^z'] + [
                'y^{(%s)}' % (i + 1) for i in range(num_hidden_layer)
            ] + ['\psi']
            kind_list = ['nn.input'
                         ] + ['nn.hidden'] * num_hidden_layer + ['nn.output']
            radius_list = [0.1] + [0.2] * num_hidden_layer + [0.3]
            x_list = 1.5 * np.arange(len(self.architecture)) + 1.5

            seq_list = []

            # Input pins
            inputPins = NodeBrush('qc.C', d.ax)
            seq_list.append(
                node_sequence(inputPins,
                              self.inputs,
                              center=(0, 0),
                              space=(0, 1)))

            # Network and connections
            for n, kind, radius, y in zip(self.architecture, kind_list,
                                          radius_list, x_list):
                b = NodeBrush(kind, d.ax)
                seq_list.append(
                    node_sequence(b, n, center=(y, 0), space=(0, 1)))

            for st, et in zip(seq_list[:-1], seq_list[1:]):
                connecta2a(st, et, EdgeBrush('-->', d.ax))

            # Output pins
            outputEdge = EdgeBrush('---', d.ax)
            outputPins = NodeBrush('qc.C', d.ax)
            seq_list.append(
                node_sequence(outputPins,
                              self.architecture[-1],
                              center=(x_list[-1] + 1.5, 0),
                              space=(0, 1)))
            connect121(seq_list[-2], seq_list[-1], outputEdge)
Exemplo n.º 16
0
def qft():
    num_bit = 5
    num_bit2 = 3
    with DynamicShow((7, 5), '_phaseest.png') as ds:
        handler = QuantumCircuit(
            num_bit=num_bit + num_bit2,
            y0=2.,
            locs=-np.append(0.8 * np.arange(num_bit),
                            0.9 * num_bit + 0.3 * np.arange(num_bit2)))
        handler.x += 0.7
        with handler.block(slice(0, num_bit - 1), pad_x=0.2,
                           pad_y=0.2) as boxes:
            [handler.gate(_.GATE, i, 'H') for i in range(num_bit)]
        boxes[0].text("A", 'top')
        handler.x += 1.2
        _.BOX.size = (0.4, 0.3)
        with handler.block(slice(0, num_bit + num_bit2 - 1),
                           pad_x=0.2,
                           pad_y=0.2) as boxes:
            for i in range(num_bit):
                handler.gate((_.C, _.BOX),
                             (i, slice(num_bit, num_bit + num_bit2 - 1)),
                             ['', r'$U^{%d}$' % (2**i)])
                if i != num_bit - 1:
                    handler.x += 1.0
        boxes[0].text("B", 'top')
        handler.x += 0.7
        for i in range(num_bit2):
            handler.gate(viznet.NodeBrush('pin'), num_bit + i)
        handler.x += 0.7

        _.BOX.size = (0.6, 0.3)
        handler.gate(_.BOX, slice(0, num_bit - 1), r'QFT${}^\dagger$')
        handler.x += 1.0
        for i in range(num_bit):
            handler.gate(_.END, i)

        # text |0>s
        for i in range(num_bit + num_bit2):
            plt.text(*handler.get_position(i, x=-0.5),
                     r'$\left\vert %s\right\rangle_{Q_%d}$' %
                     (0 if i < num_bit else '?', i + 1),
                     va='center',
                     ha='center',
                     fontsize=16)
        plt.text(3.5, -6, "Quantum Circuit for Phase Estimation", ha='center')
Exemplo n.º 17
0
def mera():
    with DynamicShow((8, 6), filename='_mera.png') as ds:
        initial = base >> (0, 0.001)
        pin1 = topc >> (-0.1, dz)
        pin2 = topc >> (0.1, dz)
        vedge >> (pin1, Pin([-0.1, 0]))
        vedge >> (pin2, Pin([0.1, 0]))
        nodes = [initial]
        for angle, dr, size in zip(
            [np.pi, np.pi * 0.9, np.pi * 0.7, 0.4 * np.pi],
            [0.9, 1.0, 0.8, 0.8], [0.3, 0.25, 0.2, 0.15]):
            nodes = grow(base, nodes, dr=dr, angle=angle, vbar=True, size=size)
        grow(leaf,
             nodes,
             dr=0.6,
             angle=0.4 * np.pi,
             vbar=False,
             size=topc.size)
Exemplo n.º 18
0
def blockfocus():
    '''illustration of block-focus scheme.'''
    num_bit = 6
    with DynamicShow((5, 3), '_blockfocus.png') as ds:
        handler = QuantumCircuit(num_bit=num_bit)
        handler.x += 0.8
        handler.gate(_.GATE, 0, 'X')
        for i in range(1, num_bit):
            handler.gate(_.GATE, i, 'H')
        handler.x += 1.2
        with handler.block(slice(0, num_bit - 1), pad_x=0.1) as b:
            handler.focus([4, 2, 1, 3])
        b[0].text('focus', 'top')
        handler.x += 1.2

        # entangler block
        with handler.block(slice(0, 3)) as b:
            handler.gate((_.C, _.NOT), (1, 0))
            handler.gate((_.C, _.NOT), (3, 2))
            handler.x += 0.7
            handler.gate((_.C, _.NOT), (2, 0))
            handler.x += 0.7
            handler.gate((_.C, _.NOT), (3, 2))
        b[0].text('entangler', 'top')

        handler.x += 1.2
        for i in range(num_bit):
            handler.gate(_.GATE, i, 'H')
        handler.x += 1
        for i in range(num_bit):
            handler.gate(_.MEASURE, i)
        handler.edge.style = '='
        handler.x += 0.8
        for i in range(num_bit):
            handler.gate(_.END, i)

        # text |0>s
        for i in range(num_bit):
            plt.text(-0.5,
                     -i,
                     r'$\left\vert0\right\rangle$',
                     va='center',
                     ha='center',
                     fontsize=16)
Exemplo n.º 19
0
Arquivo: bm.py Projeto: rayonde/viznet
def test_draw_bm():
    '''Draw a Boltzmann Machine'''
    num_node_visible = 6
    with DynamicShow((5, 4), '_bm.png') as d:
        # define brushes
        node = NodeBrush('nn.backfed', d.ax, size='normal')
        edge = EdgeBrush('---', d.ax)

        node_list = add_circled_node_sequence(num_node_visible,
                                              node,
                                              radius=1.0,
                                              offset=(0, 0))

        # connect all
        for i, nodei in enumerate(node_list):
            # add text
            nodei.text(r'$\sigma_%d$' % i)
            for nodej in node_list:
                if nodei is not nodej:
                    edge >> (nodei, nodej)
Exemplo n.º 20
0
def diffcircuit():
    '''illustration of block-focus scheme.'''
    num_bit = 4
    depth = 3
    with DynamicShow((10, 4), '_differentiable.png') as ds:
        plt.text(5, -4, "Differentiable Circuit of Size 4, depth 2")
        handler = QuantumCircuit(num_bit=num_bit)
        handler.x += 1.0
        with handler.block(slice(0, num_bit - 1), pad_x=0.2, pad_y=0.1) as b:
            rot_gate(handler, 1, mask=[0, 1, 1])
        b[0].text('Rotation', 'top')
        handler.x += 1.0
        # entangler block
        with handler.block(slice(0, num_bit - 1), pad_x=0, pad_y=0.1) as b:
            entangle_gate(handler)
        b[0].text('Entangler', 'top')

        for i in range(depth - 2):
            handler.x += 1.0
            rot_gate(handler, 2, mask=[1, 1, 1])
            handler.x += 1.0
            entangle_gate(handler)
        handler.x += 1.0
        rot_gate(handler, 3, mask=[1, 1, 0])

        handler.x += 1.0
        for i in range(num_bit):
            handler.gate(_.MEASURE, i)
        handler.edge.style = '='
        handler.x += 0.8
        for i in range(num_bit):
            handler.gate(_.END, i)

        # text |0>s
        for i in range(num_bit):
            plt.text(-0.5,
                     -i,
                     r'$\left\vert0\right\rangle$',
                     va='center',
                     ha='center',
                     fontsize=16)
Exemplo n.º 21
0
    def mapped(self, tp="png"):
        with DynamicShow(figsize=(5, 4), filename="mapped.%s" % tp) as ds:
            xs = [0, 0, -1, 1, -2, 0, 2.0]
            ys = [3, 2, 1, 1, 0, 0, 0.0]
            locs = zip(xs, ys, "ABCDEFG")
            A, B, C, D, E, F, G = locs
            pairs = [(A, B), (B, C), (B, D), (C, E), (C, F), (D, F), (D, G),
                     (E, F), (F, G)]

            def share_vertex(pair_i, pair_j):
                return (pair_i[0] in pair_j) or (pair_i[1] in pair_j)

            enodes = []

            def f1():
                for p in pairs:
                    en = e2v >> ((p[0][0] + p[1][0]) / 2,
                                 (p[0][1] + p[1][1]) / 2)
                    en.text(p[0][2] + p[1][2])
                    enodes.append(en)
                return enodes

            def f2():
                Ne = len(pairs)
                els = []
                for i in range(Ne):
                    for j in range(i + 1, Ne):
                        if share_vertex(pairs[i], pairs[j]):
                            els.append(edge2 >> (enodes[i], enodes[j]))
                return els

            f1()
            els = f2()
            pdb.set_trace()
            for e in els:
                e.obj.remove()
Exemplo n.º 22
0
def real_bp():
    with DynamicShow((3, 3), '_feed_forward.png') as d:
        draw_feed_forward(d.ax, num_node_list=[2, 5, 5, 1])
Exemplo n.º 23
0
def real_bp():
    with DynamicShow((6, 6), '_feed_forward.png') as d:
        draw_feed_forward(d.ax, num_node_list=[5, 4, 1])
Exemplo n.º 24
0
def plot_ctmrg():
    with DynamicShow(figsize=(6, 4), filename="_ctmrg.png") as pl:
        grid = Grid(([1.0, 0], [0.5, 0.8]))
        box = NodeBrush('box',
                        size=(0.5, 0.2),
                        color="#333333",
                        roundness=0.1,
                        edgecolor="#333333")

        redline = EdgeBrush('-', lw=LW, color="#000000", zorder=100)
        blueline = EdgeBrush('-', lw=LW, color="#999999", zorder=-2)
        iedge = copy.copy(edge)
        iedge.zorder = -1

        def ket(isbra=False):
            X2 = 2
            X1 = 1
            Y = 1
            E1 = red >> grid[-X1, Y]
            E3 = red >> grid[-X1, -Y]
            E4 = red >> grid[X1, -Y]
            E6 = red >> grid[X1, Y]
            E2 = red >> grid[-X2, 0]
            E5 = red >> grid[X2, 0]
            ES = [E1, E2, E3, E4, E5, E6]
            C1 = blue >> grid[-X2, Y]
            C2 = blue >> grid[-X2, -Y]
            C4 = blue >> grid[X2, Y]
            C3 = blue >> grid[X2, -Y]

            dYa = 0.3 * (1 if isbra else -1)
            bl = copy.copy(grass)
            A1 = bl >> grid[-X1, 0] + [0, dYa]
            A2 = bl >> grid[X1, 0] + [0, dYa]

            QUEUE = [E1, C1, E2, C2, E3, E4, C3, E5, C4, E6]
            NQ = 10
            for i in range(NQ):
                iedge >> (QUEUE[i], QUEUE[(i + 1) % NQ])

            eg = redline if isbra else blueline
            eg >> (E2, A1)
            eg >> (E1, A1)
            eg >> (E3, A1)
            eg >> (E4, A2)
            eg >> (E5, A2)
            eg >> (E6, A2)
            eg >> (A1, A2)
            return A1, A2, ES

        A1, A2, ES = ket(True)
        A1_, A2_, ES_ = ket()
        c = box >> grid[0, 0]
        c.text("$\hat{H}$", fontsize=16, color='w')
        redline >> (c, A1)
        blueline >> (c, A1_)
        redline >> (c, A2)
        blueline >> (c, A2_)
        plt.axis("equal")
        plt.axis("off")
        plt.tight_layout()
Exemplo n.º 25
0
    def contract(self, tp="gif"):
        steper = NodeBrush("basic")
        dbl = EdgeBrush('=', lw=2)
        with DynamicShow(figsize=(5, 4), filename="contract.%s" % tp) as ds:
            st = steper >> (3, 3)
            t = st.text("")
            xs = [0, 0, -1, 1, -2, 0, 2.0]
            ys = [3, 2, 1, 1, 0, 0, 0.0]
            locs = zip(xs, ys)
            nds = [nbrush >> loc for loc in locs]
            A, B, C, D, E, F, G = nds
            for obj, x in zip([A, B, C, D, E, F, G],
                              ["A", "B", "C", "D", "E", "F", "G"]):
                obj.text(x)
                obj.edges = []
                obj.label = x

            pairs = [(A, B), (B, C), (B, D), (C, E), (C, F), (D, F), (D, G),
                     (E, F), (F, G)]
            _pairs = [(A, B), (B, C), (B, D), (C, E), (C, F), (D, F), (D, G),
                      (E, F), (F, G)]
            corder = [0, 2, 6, 5, 8, 1, 4, 7, 3]

            edges = []
            for (ip, pair) in enumerate(pairs):
                e = edge >> pair
                e.vertices = pair
                pair[0].edges.append(ip)
                pair[1].edges.append(ip)
                edges.append(e)

            removed_list = []
            sl = []

            def update(i):
                ip = corder[i]
                X, Y = pairs[ip]
                _X, _Y = _pairs[ip]
                st.objs[-1].remove()
                t = st.text(_X.label + _Y.label)
                if pairs[ip] in removed_list:
                    sl[-1].remove()
                    return
                removed_list.append(pairs[ip])
                print(X.label, Y.label)
                res = edges[ip].remove()
                nnode = nbrush >> edges[ip].position
                nnode.edges = []
                nnode.label = X.label + Y.label
                nnode.text(nnode.label)
                if i in [3, 5, 7]:
                    sl.append(selfloop >> nnode.pin("top"))
                # special cases
                vl = []
                for ie in X.edges + Y.edges:
                    res = edges[ie].remove()
                    for v in edges[ie].vertices:
                        if v not in (X, Y):
                            if v in vl:
                                #e = dbl >> (v, nnode)
                                e = next(
                                    filter(lambda e: e.vertices == (v, nnode),
                                           edges))
                                e.obj.set_linewidth(e.obj.get_linewidth() + 2)
                            else:
                                e = edge >> (v, nnode)
                            nnode.edges.append(ie)
                            e.vertices = (v, nnode)
                            edges[ie] = e
                            print(ie, e.vertices[0].label, e.vertices[1].label)
                            pairs[ie] = e.vertices
                            vl.append(v)
                        try:
                            v.edges.remove(ie)
                        except:
                            pass
                X.remove()
                Y.remove()

            ds.steps = [lambda j=i: update(j) for i in range(len(corder))]
Exemplo n.º 26
0
def parseyaml():
    with open(os.path.dirname(__file__) + '/circuit.yaml') as f:
        datamap = yaml.safe_load(f)
    print(datamap)
    with DynamicShow(figsize=(6, 6)) as ds:
        dict2circuit(datamap)
Exemplo n.º 27
0
def test_prodnet2():
    with DynamicShow((6, 4), '_prodnet2.png') as d:
        draw_prodnet2(d.ax, 6)
Exemplo n.º 28
0
def test_prodnet():
    with DynamicShow((6, 4), '_prodnet.png') as d: