Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
'']
verbose = args['--verbose']
# Get grid from file
with open(grid_filename) as grid_stream:
qubits = GetGridQubit(grid_stream)
# Get circuit from file
with open(circuit_filename) as circuit_stream:
circuit = GetCircuit(circuit_stream, qubits)
# Print quantum circuit
if verbose: print(circuit, file=stderr)
# Print amplitudes
simulator = cirq.Simulator()
results = simulator.simulate(circuit, qubit_order=qubits)
for x, v in enumerate(results.final_state):
print(('{{: {}d}}: |{{}}>'.format(len(str(len(qubits))) + 2)).format(
x,
bin(x)[2:].zfill(len(qubits))[::-1]), v)
(input_qubits, output_qubit) = set_io_qubits(qubit_count)
#Choose the x' and make an oracle which can recognize it.
x_bits = [random.randint(0, 1) for _ in range(qubit_count)]
print('Secret bit sequence: {}'.format(x_bits))
# Make oracle (black box)
oracle = make_oracle(input_qubits, output_qubit, x_bits)
# Embed the oracle into a quantum circuit implementing Grover's algorithm.
circuit = make_grover_circuit(input_qubits, output_qubit, oracle)
print('Circuit:')
print(circuit)
# Sample from the circuit a couple times.
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
print('Sampled results:\n{}'.format(frequencies))
# Check if we actually found the secret value.
most_common_bitstring = frequencies.most_common(1)[0][0]
print('Most common bitstring: {}'.format(most_common_bitstring))
print('Found a match: {}'.format(
most_common_bitstring == bitstring(x_bits)))
def deutsch_algorithm(oracle):
"""Yields a circuit for Deutsch's algorithm given operations implementing
the oracle."""
yield cirq.X(q1)
yield cirq.H(q0), cirq.H(q1)
yield oracle
yield cirq.H(q0)
yield cirq.measure(q0)
# Display each circuit for all oracles
for key, oracle in oracles.items():
print('Circuit for {}...'.format(key))
print(cirq.Circuit(deutsch_algorithm(oracle)), end="\n\n")
# Get a simulator
simulator = cirq.Simulator()
# Execute the circuit for each oracle to distinguish constant from balanced
for key, oracle in oracles.items():
result = simulator.run(
cirq.Circuit(deutsch_algorithm(oracle)),
repetitions=10
)
print('oracle: {:<4} results: {}'.format(key, result))
oracle = make_oracle(input_qubits,
output_qubit,
secret_factor_bits,
secret_bias_bit)
print('Secret function:\nf(a) = a·<{}> + {} (mod 2)'.format(
', '.join(str(e) for e in secret_factor_bits),
secret_bias_bit))
# Embed the oracle into a special quantum circuit querying it exactly once.
circuit = make_bernstein_vazirani_circuit(
input_qubits, output_qubit, oracle)
print('Circuit:')
print(circuit)
# Sample from the circuit a couple times.
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
print('Sampled results:\n{}'.format(frequencies))
# Check if we actually found the secret value.
most_common_bitstring = frequencies.most_common(1)[0][0]
print('Most common matches secret factors:\n{}'.format(
most_common_bitstring == bitstring(secret_factor_bits)))
def run_bench(benchmark, nqubits, gate, locs=(1, )):
qubits = [cirq.GridQubit(k, 0) for k in range(nqubits)]
circuit = cirq.Circuit()
locs = tuple(qubits[k] for k in locs)
circuit.append(gate(*locs))
simulator = Simulator(dtype=np.complex128)
benchmark(simulator.simulate, circuit, qubit_order=qubits)
def main():
"""Demonstrates the Quantum Fourier transform."""
# Create circuit and display it
qft_circuit = generate_2x2_grid_qft_circuit()
print('Circuit:')
print(qft_circuit)
# Simulate and collect the final state
simulator = cirq.Simulator()
result = simulator.simulate(qft_circuit)
# Display the final state
print('\nFinalState')
print(np.around(result.final_state, 3))
def expectations(circuit):
"""Simulates the circuit and computes expectation values of the final
state.
Args:
circuit : cirq.Circuit
Circuit to simulate.
"""
# Get a simulator
sim = cirq.Simulator()
ancilla_expectation = 0.0
# Post-select on the |1> outcome for the ancilla qubit
# Or equivalently an expectation of -1.0
while ancilla_expectation != -1.0:
res = sim.compute_displays(circuit)
ancilla_expectation = round(res.display_values["a"], 3)
# Compute expectations and display them
print("X =", res.display_values["x"])
print("Y =", res.display_values["y"])
print("Z =", res.display_values["z"])
crot = cirq.ControlledGate(rot)
circ.append(crot(regA[j], regA[k]))
"""
# Measure all qubits in the readout register
circ.append(cirq.measure(*regA, key="z"))
# Print out the circuit
#print("Circuit:")
#print(circ[5:])
# =============================================================================
# Executing the circuit for QPE
# =============================================================================
sim = cirq.Simulator()
res = sim.run(circ, repetitions=1000)
hist = res.histogram(key="z")
top = hist.most_common(2)
estimated = [np.exp(2j * np.pi * binary_decimal(bin(x[0]))) for x in top]
print("\nEigenvalues from QPE:")
print(sorted(estimated, key=lambda x: abs(x)**2))
print("\nActual eigenvalues:")
print(sorted(evals, key=lambda x: abs(x)**2))
def simulate(circ):
"""Returns the wavefunction after applying the circuit."""
sim = cirq.Simulator()
return sim.simulate(circ).final_state