Skip to content

Feature/isometries #314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 34 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
0871984
Initial implementation of uniformly controlled gates and column-by-co…
Apr 3, 2018
bf67147
Implemented diagonal gates and decomposition into elementary gates
Apr 4, 2018
703631b
Isometries should work now, using the Simulator for local quregs and …
Apr 6, 2018
869fa26
Implement decompositions in C++, need to finish testing.
Apr 18, 2018
3324513
Restructure Code for C++
Apr 24, 2018
e77f047
Code mostly functional, errors accumulate for many qubits.
Apr 30, 2018
fec25c0
All important features functional.
Jun 5, 2018
c55d386
Move to libs, implement controls.
Jun 11, 2018
e196cb8
Remove a.out
Jun 11, 2018
1bbbbbd
Fix pep8 issues
Feb 17, 2019
b242743
Optimize final diagonal gate
Feb 17, 2019
827bc3f
Merge branch 'develop' into feature/isometries
Feb 17, 2019
44ca63d
Fix failing tests
Feb 19, 2019
769fe73
Fix python 2.7 compatibility
Feb 19, 2019
29e2f77
Merge branch 'develop' into feature/isometries
Takishima Jul 1, 2019
de9f4bb
Add missing license header
Takishima Feb 3, 2020
41a6806
Fix some more issues
Takishima Feb 3, 2020
f3b3201
Fix missing license header
Takishima Feb 3, 2020
13b5160
Fix compilation issue with cppdec.cpp
Takishima Feb 3, 2020
c651d54
Fix compilation issue
Takishima Feb 3, 2020
25f1121
Merge branch 'develop' into pr/314
Takishima Feb 3, 2020
d91b760
Move to C++14 and address a couple more comments
Takishima Feb 3, 2020
e2b91a8
Increase test coverage
Takishima Feb 4, 2020
c43c164
Merge branch 'develop' into pr/314
Takishima Feb 4, 2020
f6ebd35
Revert "Merge branch 'develop' into pr/314"
Takishima Feb 4, 2020
edcf421
Fix failing tests
Takishima Feb 5, 2020
0257934
Fix failing tests
Takishima Feb 5, 2020
73a5dfe
Fix failing tests v3
Takishima Feb 5, 2020
5ec4d17
Disable full python and C++ test for problematic tests
Takishima Feb 5, 2020
ffeb416
Merge branch 'develop' into pr/314
Takishima Feb 5, 2020
ee3f1b0
Ignore a few lines in _ibm_http_client.py for coverage
Takishima Feb 5, 2020
6f759da
Fix coverage
Takishima Feb 5, 2020
3ccb3eb
Merge branch 'develop' into pr/314
Takishima Apr 20, 2020
d4ebc28
Merge branch 'develop' into feature/isometries
Takishima Apr 20, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions projectq/backends/_sim/_cppkernels/simulator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,58 @@ class Simulator{
fused_gates_ = fused_gates;
}

template <class M>
void apply_uniformly_controlled_gate(std::vector<M> &unitaries,
unsigned target_id,
std::vector<unsigned> choice_ids,
std::vector<unsigned> ctrl_ids){
run();
std::size_t n = vec_.size();
std::size_t dist = 1UL << map_[target_id];

auto mask = get_control_mask(ctrl_ids);

#pragma omp parallel for collapse(2) schedule(static)
for(std::size_t high = 0; high < n; high += 2*dist){
for(std::size_t low = 0; low < dist; ++low){
std::size_t entry = high+low;
if((entry&mask) == mask) {
unsigned u = 0;
for(std::size_t i = 0; i < choice_ids.size(); ++i)
u |= ((entry >> map_[choice_ids[i]]) & 1) << i;

auto &m = unitaries[u];
std::complex<double> v[2];
v[0] = vec_[entry];
v[1] = vec_[entry + dist];
vec_[entry] = v[0]*m[0][0] + v[1]*m[0][1];
vec_[entry + dist] = v[0]*m[1][0] + v[1]*m[1][1];
}
}
}
}

template <class M>
void apply_diagonal_gate(std::vector<calc_type> angles,
std::vector<unsigned> ids,
std::vector<unsigned> ctrl_ids)
{
run();
std::size_t n = vec_.size();
complex_type I(0., 1.);
auto mask = get_control_mask(ctrl_ids);

#pragma omp parallel for schedule(static)
for(std::size_t entry = 0; entry < n; ++entry) {
if((entry&mask) == mask) {
unsigned a = 0;
for(std::size_t i = 0; i < ids.size(); ++i)
a |= ((entry >> map_[ids[i]]) & 1) << i;
vec_[entry] *= std::exp(I * angles[a]);
}
}
}

template <class F, class QuReg>
void emulate_math(F const& f, QuReg quregs, std::vector<unsigned> ctrl,
unsigned num_threads=1){
Expand Down
2 changes: 2 additions & 0 deletions projectq/backends/_sim/_cppsim.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ PYBIND11_PLUGIN(_cppsim) {
.def("is_classical", &Simulator::is_classical)
.def("measure_qubits", &Simulator::measure_qubits_return)
.def("apply_controlled_gate", &Simulator::apply_controlled_gate<MatrixType>)
.def("apply_uniformly_controlled_gate", &Simulator::apply_uniformly_controlled_gate<MatrixType>)
.def("apply_diagonal_gate", &Simulator::apply_diagonal_gate<MatrixType>)
.def("emulate_math", &emulate_math_wrapper<QuRegs>)
.def("get_expectation_value", &Simulator::get_expectation_value)
.def("apply_qubit_operator", &Simulator::apply_qubit_operator)
Expand Down
38 changes: 38 additions & 0 deletions projectq/backends/_sim/_pysim.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import random
import numpy as _np
import cmath


class Simulator(object):
Expand Down Expand Up @@ -397,6 +398,43 @@ def apply_controlled_gate(self, m, ids, ctrlids):
pos = [self._map[ID] for ID in ids]
self._multi_qubit_gate(m, pos, mask)

def apply_uniformly_controlled_gate(self, unitaries, target_id,
choice_ids, ctrl_ids):
choice_pos = [self._map[ID] for ID in choice_ids]
pos = self._map[target_id]
mask = self._get_control_mask(ctrl_ids)

def kernel(u, d, m):
return u * m[0][0] + d * m[0][1], u * m[1][0] + d * m[1][1]

dist = 1 << pos
n = len(self._state)
for high in range(0, n, 2*dist):
for low in range(0, dist):
entry = high+low
if (entry & mask) == mask:
u = 0
for i in range(len(choice_pos)):
u |= ((entry >> choice_pos[i]) & 1) << i
id1 = entry
id2 = entry + dist
self._state[id1], self._state[id2] = kernel(
self._state[id1],
self._state[id2],
unitaries[u])

def apply_diagonal_gate(self, angles, ids, ctrlids):
pos = [self._map[ID] for ID in ids]
mask = self._get_control_mask(ctrlids)

n = len(self._state)
for entry in range(n):
if (entry & mask) == mask:
a = 0
for i in range(len(pos)):
a |= ((entry >> pos[i]) & 1) << i
self._state[entry] *= cmath.exp(1j*angles[a])

def _single_qubit_gate(self, m, pos, mask):
"""
Applies the single qubit gate matrix m to the qubit at position `pos`
Expand Down
34 changes: 30 additions & 4 deletions projectq/backends/_sim/_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,23 @@
"""

import math
import cmath
import random
from projectq.types import WeakQubitRef
from projectq.cengines import BasicEngine
from projectq.meta import get_control_count, LogicalQubitIDTag
from projectq.ops import (NOT,
from projectq.ops import (All,
NOT,
H,
R,
Measure,
FlushGate,
Allocate,
Deallocate,
BasicMathGate,
TimeEvolution)
from projectq.types import WeakQubitRef
TimeEvolution,
UniformlyControlledGate,
DiagonalGate)

try:
from ._cppsim import Simulator as SimulatorBackend
Expand Down Expand Up @@ -104,7 +108,9 @@ def is_available(self, cmd):
if (cmd.gate == Measure or cmd.gate == Allocate or
cmd.gate == Deallocate or
isinstance(cmd.gate, BasicMathGate) or
isinstance(cmd.gate, TimeEvolution)):
isinstance(cmd.gate, TimeEvolution) or
isinstance(cmd.gate, UniformlyControlledGate) or
isinstance(cmd.gate, DiagonalGate)):
return True
try:
m = cmd.gate.matrix
Expand Down Expand Up @@ -399,6 +405,26 @@ def _handle(self, cmd):
qubitids = [qb.id for qb in cmd.qubits[0]]
ctrlids = [qb.id for qb in cmd.control_qubits]
self._simulator.emulate_time_evolution(op, t, qubitids, ctrlids)
elif isinstance(cmd.gate, UniformlyControlledGate):
choice_ids = [qb.id for qb in cmd.qubits[0]]
ctrl_ids = [qb.id for qb in cmd.control_qubits]
target_id = cmd.qubits[1][0].id
unitaries = [gate.matrix.tolist() for gate in cmd.gate.gates]
assert len(unitaries) == 2**len(choice_ids)
self._simulator.apply_uniformly_controlled_gate(unitaries,
target_id,
choice_ids,
ctrl_ids)
if cmd.gate.up_to_diagonal:
angles = [-cmath.phase(p) for p in cmd.gate.decomposition[1]]
ids = [target_id]+choice_ids
self._simulator.apply_diagonal_gate(angles, ids, [])
elif isinstance(cmd.gate, DiagonalGate):
ids = [q.id for qr in cmd.qubits for q in qr]
ctrlids = [qb.id for qb in cmd.control_qubits]
angles = cmd.gate.angles
assert len(angles) == 2**len(ids)
self._simulator.apply_diagonal_gate(angles, ids, ctrlids)
elif len(cmd.gate.matrix) <= 2 ** 5:
matrix = cmd.gate.matrix
ids = [qb.id for qr in cmd.qubits for qb in qr]
Expand Down
90 changes: 89 additions & 1 deletion projectq/backends/_sim/_simulator_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import copy
import math
import cmath
import numpy
import pytest
import random
Expand All @@ -31,7 +32,8 @@
LocalOptimizer, NotYetMeasuredError)
from projectq.ops import (All, Allocate, BasicGate, BasicMathGate, CNOT,
Command, H, MatrixGate, Measure, QubitOperator,
Rx, Ry, Rz, S, TimeEvolution, Toffoli, X, Y, Z)
Rx, Ry, Rz, S, T, TimeEvolution, Toffoli, X, Y, Z,
DiagonalGate, UniformlyControlledGate)
from projectq.meta import Control, Dagger, LogicalQubitIDTag
from projectq.types import WeakQubitRef

Expand Down Expand Up @@ -521,6 +523,92 @@ def build_matrix(list_single_matrices):
init_wavefunction)


def test_simulator_apply_diagonal_gate(sim):
eng = MainEngine(sim)
qureg = eng.allocate_qureg(4)
eng.flush()

target_1 = qureg[0]
control = qureg[1]
target_0 = qureg[2]
empty = qureg[3]

wf = [1./4.]*(1 << 4)
eng.backend.set_wavefunction(wf, qureg)

D = DiagonalGate(angles=range(4))
with Control(eng, control):
D | (target_0, target_1)

eng.flush()
qbit_to_bit_map, final_wavefunction = copy.deepcopy(eng.backend.cheat())
All(Measure) | qureg

desired_state = [1./4.*cmath.exp(1j*i) for i in
[0, 0, 0, 2, 0, 0, 1, 3, 0, 0, 0, 2, 0, 0, 1, 3]]
assert numpy.allclose(final_wavefunction, desired_state)


def test_simulator_apply_uniformly_controlled_gate():
eng = MainEngine()
qureg = eng.allocate_qureg(3)
eng.flush()
wf = [math.sqrt(1./8.)]*(1 << 3)
eng.backend.set_wavefunction(wf, qureg)

A = Rx(numpy.pi/5)
B = H
C = Rz(numpy.pi/5)
D = Ry(numpy.pi/3)
U = UniformlyControlledGate([A, B, C, D])
with Dagger(eng):
U | ([qureg[0], qureg[2]], qureg[1])
eng.flush()
qbit_to_bit_map, final_wavefunction = copy.deepcopy(eng.backend.cheat())
vec = numpy.array([final_wavefunction]).T
vec[[1, 2]] = vec[[2, 1]] # reorder basis
vec[[5, 6]] = vec[[6, 5]]
reference = numpy.matrix(scipy.linalg.block_diag(A.matrix, B.matrix,
C.matrix, D.matrix))
assert numpy.allclose(reference*vec, wf)


def test_simulator_apply_uniformly_controlled_gate_with_control(sim):
eng = MainEngine(sim)
qureg = eng.allocate_qureg(5)
eng.flush()

control = qureg[0]
choice_1 = qureg[1]
target = qureg[2]
empty = qureg[3]
choice_0 = qureg[4]

gates = [X, H, S, T]
U = UniformlyControlledGate(gates)

id = Rz(0.0)
gates_equiv = [id, X, id, S, id, X, id, S,
id, H, id, T, id, H, id, T]
U_equiv = UniformlyControlledGate(gates_equiv)

All(H) | qureg
with Control(eng, control):
U | ([choice_0, choice_1], target)

with Dagger(eng):
All(H) | qureg
U_equiv | (qureg[0:2]+qureg[3:5], target)

eng.flush()
qbit_to_bit_map, final_wavefunction = copy.deepcopy(eng.backend.cheat())
All(Measure) | qureg

print(final_wavefunction)
desired_state = [1.0] + [0.0]*31
assert numpy.allclose(final_wavefunction, desired_state)


def test_simulator_set_wavefunction(sim, mapper):
engine_list = [LocalOptimizer()]
if mapper is not None:
Expand Down
7 changes: 7 additions & 0 deletions projectq/libs/isometries/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from .decompositions import _decompose_diagonal_gate
from .decompositions import _decompose_uniformly_controlled_gate
from .decompositions import _decompose_isometry
from .single_qubit_gate import _SingleQubitGate
from .apply_decompositions import (_apply_isometry,
_apply_diagonal_gate,
_apply_uniformly_controlled_gate)
Loading