Exemplo n.º 1
0
 def __init__(self,
              N,
              batch_shape,
              echo_pulse=True,
              name='conditional_displacement'):
     super().__init__(name=name)
     self.displace = ops.DisplacementOperator(
         N, tensor_with=[ops.identity(2), None])
     self.P = {
         i: utils.tensor([ops.projector(i, 2),
                          ops.identity(N)])
         for i in [0, 1]
     }
     self.batch_shape = batch_shape
     self.qubit_op = utils.tensor([ops.sigma_x(),
                                   ops.identity(N)
                                   ]) if echo_pulse else ops.identity(2 * N)
Exemplo n.º 2
0
    def create_operators(self):
        N = self.N

        # oscillator fixed operators
        self.I = tensor([ops.identity(2), ops.identity(N)])
        self.a = tensor([ops.identity(2), ops.destroy(N)])
        self.a_dag = tensor([ops.identity(2), ops.create(N)])
        self.q = tensor([ops.identity(2), ops.position(N)])
        self.p = tensor([ops.identity(2), ops.momentum(N)])
        self.n = tensor([ops.identity(2), ops.num(N)])
        self.parity = tensor([ops.identity(2), ops.parity(N)])

        # qubit fixed operators
        self.sx = tensor([ops.sigma_x(), ops.identity(N)])
        self.sy = tensor([ops.sigma_y(), ops.identity(N)])
        self.sz = tensor([ops.sigma_z(), ops.identity(N)])
        self.sm = tensor([ops.sigma_m(), ops.identity(N)])
        self.H = tensor([ops.hadamard(), ops.identity(N)])

        # oscillator parameterized operators
        tensor_with = [ops.identity(2), None]
        self.displace = ops.DisplacementOperator(N, tensor_with=tensor_with)
        self.rotate = ops.RotationOperator(N, tensor_with=tensor_with)

        # qubit parameterized operators
        tensor_with = [None, ops.identity(N)]
        self.rotate_qb_xy = ops.QubitRotationXY(tensor_with=tensor_with)
        self.rotate_qb_z = ops.QubitRotationZ(tensor_with=tensor_with)

        # qubit sigma_z measurement projector
        self.P = {
            i: tensor([ops.projector(i, 2),
                       ops.identity(N)])
            for i in [0, 1]
        }
Exemplo n.º 3
0
 def __init__(self, N, batch_shape, name='qubit_rotation'):
     super().__init__(name=name)
     self.rotation_op = ops.QubitRotationXY(
         tensor_with=[None, ops.identity(N)])
     self.batch_shape = batch_shape
def plot_phase_space(state,
                     tensorstate,
                     phase_space_rep='wigner',
                     lim=4,
                     pts=81,
                     title=None):
    """
    Plot phase space representation of the state. Converts a batch of states
    to density matrix.
    
    Args:
        state (tf.Tensor([B,N], c64)): batched state vector
        tensorstate (bool): flag if tensored with qubit
        phase_space_rep (str): either 'wigner' or 'CF'
        lim (float): plot limit in displacement units
        pts (int): number of pixels in each direction 
        title (str): figure title (optional)
    
    """

    assert len(state.shape) >= 2 and state.shape[1] > 1

    # create operators
    if tensorstate:
        N = int(state.shape[1] / 2)
        parity = utils.tensor([ops.identity(2), ops.parity(N)])
        D = ops.DisplacementOperator(N, tensor_with=[ops.identity(2), None])
    else:
        N = state.shape[1]
        D = ops.DisplacementOperator(N)
        parity = ops.parity(N)

    # project every trajectory onto |g> subspace
    if tensorstate:
        P0 = utils.tensor([ops.projector(0, 2), ops.identity(N)])
        state, _ = utils.normalize(tf.linalg.matvec(P0, state))

    # make a density matrix
    dm = utils.density_matrix(state)

    # Generate a grid of phase space points
    x = np.linspace(-lim, lim, pts)
    y = np.linspace(-lim, lim, pts)

    xs_mesh, ys_mesh = np.meshgrid(x, y, indexing='ij')
    grid = tf.cast(xs_mesh + 1j * ys_mesh, c64)
    grid_flat = tf.reshape(grid, [-1])

    matmul = tf.linalg.matmul

    # Calculate and plot the phase space representation
    if phase_space_rep == 'wigner':
        displaced_parity = matmul(D(grid_flat), matmul(parity, D(-grid_flat)))
        W = 1 / pi * tf.linalg.trace(matmul(displaced_parity, dm))
        W_grid = tf.reshape(W, grid.shape)

        fig, ax = plt.subplots(1, 1, dpi=200)
        fig.suptitle(title)
        ax.pcolormesh(x,
                      y,
                      np.transpose(W_grid.numpy().real),
                      cmap='RdBu_r',
                      vmin=-1 / pi,
                      vmax=1 / pi)
        ax.set_aspect('equal')

    if phase_space_rep == 'CF':

        C = tf.linalg.trace(matmul(D(grid_flat), dm))
        C_grid = tf.reshape(C, grid.shape)

        fig, axes = plt.subplots(1, 2, sharey=True, dpi=200)
        fig.suptitle(title)
        axes[0].pcolormesh(x,
                           y,
                           np.transpose(C_grid.numpy().real),
                           cmap='RdBu_r',
                           vmin=-1,
                           vmax=1)
        axes[1].pcolormesh(x,
                           y,
                           np.transpose(C_grid.numpy().imag),
                           cmap='RdBu_r',
                           vmin=-1,
                           vmax=1)
        axes[0].set_title('Re')
        axes[1].set_title('Im')
        axes[0].set_aspect('equal')
        axes[1].set_aspect('equal')

    plt.tight_layout()
Exemplo n.º 5
0
print()

# call the assignment function
op.assignment(45)

# line space
print()

# call the logical function
op.logical(True, True)  # positional arguments
# This is assigned by position. It means a is True and b is False
#  What if you wanted to say a is False and b is True, using the same position?

# line space
print()

# the solution is using Named Arguments
op.logical(b=True, a=False)

# line space
print()

# call the membership function
op.membership()

# line space
print()

# call the identity function
op.identity('hello', 'this is the hello world')
Exemplo n.º 6
0
def parsingLines(line, f):
    line[0] = str.upper(line[0])

    if line[0] == "LATTYPE":
        if line.__len__() == 1:
            print(
                "[HIPERWALK] Syntax error at  LATTYPE, missing lattice type.")
            exit(-1)
        if (line[1] != "NATURAL") and (line[1] != "DIAGONAL") and (line[1] !=
                                                                   "TEST"):
            print(
                "[HIPERWALK] Syntax error at  LATTYPE, unknown lattice type, %s"
                % line[1])
            exit(-1)
        cfg.LATTYPE = line[1]

    elif line[0] == "BEGINSTATE":
        cfg.STATE_COMPONENTS = []
        totalComponents = 0
        while line[0] != "ENDSTATE":

            line = f.readline()

            while line == "\n":  ### Parsing \n
                line = f.readline()

            line = str.upper(line)
            line = line.split()

            if line[0] != "ENDSTATE":
                totalComponents = totalComponents + 1
                if cfg.WALK == "DTQW1D":
                    cfg.STATE_COMPONENTS = np.append(cfg.STATE_COMPONENTS, [
                        float(line[0]),
                        float(line[1]),
                        int(line[2]),
                        int(line[3])
                    ], 0)
                elif cfg.WALK == "DTQW2D":
                    cfg.STATE_COMPONENTS = np.append(cfg.STATE_COMPONENTS, [
                        float(line[0]),
                        float(line[1]),
                        int(line[2]),
                        int(line[3]),
                        int(line[4])
                    ], 0)
                elif cfg.WALK == "STAGGERED1D":
                    cfg.STATE_COMPONENTS = np.append(
                        cfg.STATE_COMPONENTS,
                        [float(line[0]),
                         float(line[1]),
                         int(line[2])], 0)
                elif cfg.WALK == "STAGGERED2D":
                    cfg.STATE_COMPONENTS = np.append(cfg.STATE_COMPONENTS, [
                        float(line[0]),
                        float(line[1]),
                        int(line[2]),
                        int(line[3])
                    ], 0)

        if cfg.WALK == "DTQW1D":
            cfg.STATE_COMPONENTS.shape = totalComponents, 4
            aux = int((st.return_MAX_Position(cfg.STATE_COMPONENTS, 2) + 1))
            if aux == 0:
                aux = aux + 2
            elif aux == 1:
                aux = aux + 1
            cfg.COINVECTORDIMENSION = aux

        if cfg.WALK == "DTQW2D":
            cfg.STATE_COMPONENTS.shape = totalComponents, 5
            cfg.COINVECTORDIMENSION = 4

        if cfg.WALK == "STAGGERED1D":
            cfg.STATE_COMPONENTS.shape = totalComponents, 3

        if cfg.WALK == "STAGGERED2D":
            cfg.STATE_COMPONENTS.shape = totalComponents, 4
        st.generateState()

    elif line[0] == "BEGINCOIN":
        line = f.readline()
        while line == "\n":  ### Parsing \n
            line = f.readline()
        line = str.upper(line)
        line = line.split()

        if line[0] == "IDENTITY":
            cfg.COINOPERATORNAME = "IDENTITY"
            cfg.COINOPERATOR = op.identity(int(line[1]))
        elif line[0] == "HADAMARD":
            cfg.COINOPERATORNAME = "HADAMARD"
            cfg.COINOPERATOR = op.hadamard(int(line[1]))
        elif line[0] == "FOURIER":
            cfg.COINOPERATORNAME = "FOURIER"
            cfg.COINOPERATOR = op.fourier(int(line[1]))
        elif line[0] == "GROVER":
            cfg.COINOPERATORNAME = "GROVER"
            cfg.COINOPERATOR = op.grover(int(line[1]))
        else:
            N = len(line) / 2
            cfg.COINOPERATOR = np.zeros((N, N), dtype=complex)
            for i in range(N):
                aux = 0
                for j in range(0, 2 * N, 2):
                    cfg.COINOPERATOR[i][aux] = float(
                        line[j]) + 1J * float(line[j + 1])
                    aux = aux + 1
                line = f.readline()
                line = line.split()
            op.check_Unitarity(cfg.COINOPERATOR, N)

    elif line[0] == "BEGINTESSELLATION":
        totalComponents = 0
        while line[0] != "ENDTESSELLATION":

            line = f.readline()
            while line == "\n":  ### Parsing \n
                line = f.readline()
            line = str.upper(line)
            line = line.split()

            if line[0] != "ENDTESSELLATION":
                if len(line) == 2 * cfg.NUMBER_OF_COEFICIENTS:
                    st.checkUnitarity(line)
                    cfg.STAGGERED_COEFICIENTS = np.append(
                        cfg.STAGGERED_COEFICIENTS,
                        [float(row) for row in line], 1)

                    line = f.readline()
                    line = str.upper(line)
                    line = line.split()
                    st.checkUnitarity(line)
                    if len(line) == 2 * cfg.NUMBER_OF_COEFICIENTS:
                        cfg.STAGGERED_COEFICIENTS = np.append(
                            cfg.STAGGERED_COEFICIENTS,
                            [float(row) for row in line], 1)
                    else:
                        print(
                            "[HIPERWALK] Syntax error at BEGINTESSELLATION BLOCK, invalid number of values."
                        )
                        exit(-1)

                    cfg.STAGGERED_COEFICIENTS.shape = 2, cfg.NUMBER_OF_COEFICIENTS * 2

                else:
                    print(
                        "[HIPERWALK] Syntax error at BEGINTESSELLATION BLOCK, invalid number of values."
                    )
                    exit(-1)

    elif line[0] == "DISPLACEMENT":
        if line.__len__() == 1:
            print(
                "[HIPERWALK] Syntax error at  DISPLACEMENT BLOCK, missing values."
            )
            exit(-1)
        elif cfg.WALK == "STAGGERED1D":
            cfg.TESSELLATIONDISPLACEMENT = [int(line[1])]
        elif cfg.WALK == "STAGGERED2D":
            cfg.TESSELLATIONDISPLACEMENT = [int(line[1]), int(line[2])]

    elif line[0] == "DIRECTORY":
        if line.__len__() == 1:
            print(
                "[HIPERWALK] Syntax error at  DIRECTORY BLOCK, missing name.")
            exit(-1)
        cfg.DIRECTORY = line[1]

    elif line[0] == "ANIMATION":
        if line.__len__() == 1:
            print(
                "[HIPERWALK] Syntax error at  ANIMATION BLOCK, missing name.")
            exit(-1)
        if line[1] == "TRUE":
            cfg.ANIMATION = 1
        elif line[1] == "FALSE":
            cfg.ANIMATION = 0
        else:
            print(
                "[HIPERWALK] Syntax error at  ANIMATION BLOCK, unknown value, %s."
                % line[1])
            exit(-1)

    elif line[0] == "DELAY":
        if line.__len__() == 1:
            print("[HIPERWALK] Syntax error at  DELAY BLOCK, missing value.")
            exit(-1)
        if int(line[1]) <= 0:
            print(
                "[HIPERWALK] Syntax error at  DELAY BLOCK, value must be positive integer."
            )
            exit(-1)
        cfg.DELAY = int(line[1])

    elif line[0] == "SIMULATION":
        line[1] = str.upper(line[1])
        if line.__len__() == 1:
            print(
                "[HIPERWALK] Syntax error at  SIMULATION BLOCK, missing simulation type."
            )
            exit(-1)
        if (line[1] != "LOCAL") and (line[1] != "PARALLEL"):
            print(
                "[HIPERWALK] Syntax error at  SIMULATION BLOCK, unknown type. %s"
                % line[1])
            exit(-1)
        cfg.SIMULATIONTYPE = line[1]

    elif line[0] == "HARDWAREID":
        if line.__len__() == 1:
            print(
                "[HIPERWALK] Syntax error at  HARDWAREID BLOCK, missing platform ID."
            )
            exit(-1)
        cfg.HARDWAREID = int(line[1])

    elif line[0] == "PLOTTING":
        if line.__len__() == 1:
            print("[HIPERWALK] Syntax error at  PLOTTING BLOCK, missing name.")
            exit(-1)
        line[1] = str.upper(line[1])
        if line[1] == "ZEROS":
            cfg.PLOTTING_ZEROS = 1

    elif line[0] == "PLOTS":
        if line.__len__() == 1:
            print("[HIPERWALK] Syntax error at  PLOTS BLOCK, missing value.")
            exit(-1)
        if line[1] == "TRUE":
            cfg.GNUPLOT = 1
        elif line[1] == "FALSE":
            cfg.GNUPLOT = 0
        else:
            print(
                "[HIPERWALK] Syntax error at  PLOTS BLOCK, unknown value, %s."
                % line[1])
            exit(-1)

    elif line[0] == "VARIANCE":
        if line.__len__() == 1:
            print(
                "[HIPERWALK] Syntax error at  VARIANCE BLOCK, missing value.")
            exit(-1)
        if line[1] == "TRUE":
            cfg.VARIANCE = 1
        elif line[1] == "FALSE":
            cfg.VARIANCE = 0
        else:
            print(
                "[HIPERWALK] Syntax error at  VARIANCE BLOCK, unknown value, %s."
                % line[1])
            exit(-1)

    elif line[0] == "ALLSTATES":
        if line.__len__() == 1:
            print(
                "[HIPERWALK] Syntax error at  ALLSTATES BLOCK, missing value.")
        if int(line[1]) <= 0:
            print(
                "[HIPERWALK] Syntax error at  ALLSTATES BLOCK, value must be positive integer."
            )
            exit(-1)
        else:
            cfg.ALLSTATES = 1
            cfg.SAVE_STATES_MULTIPLE_OF_N = int(line[1])

    elif line[0] == "ALLPROBS":
        if line.__len__() == 1:
            print(
                "[HIPERWALK] Syntax error at  ALLPROBS BLOCK, missing value.")
        if int(line[1]) <= 0:
            print(
                "[HIPERWALK] Syntax error at  ALLPROBS BLOCK, value must be positive integer."
            )
            exit(-1)
        else:
            cfg.ALLPROBS = 1
            cfg.SAVE_PROBS_MULTIPLE_OF_N = int(line[1])
    elif line[0] == "INITIALSTATE":

        if line.__len__() == 1:
            print(
                "[HIPERWALK] Syntax error at  INITIALSTATE, missing filename.")
            exit(-1)

        if not os.path.isfile(line[1]):
            print("[HIPERWALK] Error at  INITIALSTATE, file '%s' not found." %
                  (line[1]))
            exit(-1)

        a = str(os.path.abspath(str(line[1])))
        cfg.CUSTOM_INITIALSTATE_NAME = a
        st.generateState_CUSTOM()

    elif line[0] == "ADJMATRIX":
        if line.__len__() == 1:
            print("[HIPERWALK] Syntax error at  ADJMATRIX, missing filename.")
            exit(-1)

        if not os.path.isfile(line[1]):
            print("[HIPERWALK] Error at  ADJMATRIX, file '%s' not found." %
                  (line[1]))
            exit(-1)

        a = str(os.path.abspath(str(line[1])))
        cfg.ADJMATRIX_PATH = a

    elif line[0] == "OVERLAP":
        if line.__len__() == 1:
            print("[HIPERWALK] Syntax error at  OVERLAP BLOCK, missing value.")
            exit(-1)
        if line[1] == "TRUE":
            cfg.OVERLAP = 1
        elif line[1] == "FALSE":
            cfg.OVERLAP = 0
        else:
            print(
                "[HIPERWALK] Syntax error at  OVERLAP BLOCK, unknown value, %s."
                % line[1])
            exit(-1)

    elif line[0] == "UNITARY":
        if line.__len__() == 1:
            print("[HIPERWALK] Syntax error at  UNITARY, missing filename.")
            exit(-1)
        for i in range(1, len(line)):
            if (os.path.isfile(line[i]) == False):
                print("[HIPERWALK] Error at  UNITARY, file '%s' not found." %
                      (line[i]))
                exit(-1)

            a = str(os.path.abspath(str(line[i])))
            cfg.CUSTON_OPERATORS_NAME.append(a)
            cfg.CUSTOM_UNITARY_COUNTER = len(line) - 1

    elif line[0] == "LABELS":
        if line.__len__() == 1:
            print("[HIPERWALK] Syntax error at  LABELS , missing filename.")
            exit(-1)
        for i in range(1, len(line)):
            if (os.path.isfile(line[i]) == False):
                print("[HIPERWALK] Error at  LABELS, file '%s' not found." %
                      (line[i]))
                exit(-1)

            a = str(os.path.abspath(str(line[i])))
            cfg.CUSTOM_LABELS_NAME.append(a)
            cfg.CUSTOM_LABELS_NAME_COUNTER = len(line) - 1
        sta.generateDistance_CUSTOM()

    elif line[0] == "DEBUG":
        cfg.DEBUG = 1