diff --git a/06_krisis.py b/06_krisis.py new file mode 100644 index 0000000..1284345 --- /dev/null +++ b/06_krisis.py @@ -0,0 +1,25 @@ +import cirq +from math import pi + + +def superdense(): + # Pick a qubit. + q0 = cirq.GridQubit(0, 0) + + # Create a circuit + circuit = cirq.Circuit( + cirq.rx(pi/8).on(q0), + cirq.rz(pi/2).on(q0), + cirq.measure(q0, key='q0'), + ) + print("Circuit:") + print(circuit) + + simulator = cirq.Simulator() + result = simulator.run(circuit, repetitions=100) + print("Results:") + print(result) + + +if __name__ == "__main__": + superdense() diff --git a/lib_q_computer_math.py b/lib_q_computer_math.py index 2cc657b..5afee9c 100644 --- a/lib_q_computer_math.py +++ b/lib_q_computer_math.py @@ -93,6 +93,35 @@ class State(Matrix): super().__init__(m) self.name = name + @classmethod + def from_angles(cls, theta, phi): + m0 = np.cos(theta / 2) + m1 = np.sin(theta / 2) * np.power(np.e, (1j * phi)) + m = m0 * _0 + m1 * _1 + return cls(m.m) + + def to_angles(self): + if not self.m.shape == (2, 1): + raise Exception("State needs to be 2x1 matrix") + m0, m1 = self.m[0][0], self.m[1][0] + + # theta is between 0 and pi + theta = 2 * np.arccos(m0) + if theta < 0: + theta += np.pi + assert 0 <= theta <= np.pi + + div = np.sin(theta/2) + if div == 0: + phi = 0 + else: + exp = m1 / div + phi = np.log(complex(exp)) / 1j + if phi < 0: + phi += 2 * np.pi + assert 0 <= phi <= 2 * np.pi + return theta, phi + def __repr__(self): if self.name: return '|{}>'.format(self.name) @@ -178,6 +207,22 @@ _1 = State([[0], [1]], name='1') +_p = State([[1 / np.sqrt(2)], [1 / np.sqrt(2)]], name='+') + +_m = State([[1 / np.sqrt(2)], [-1 / np.sqrt(2)]], name='-') + +_00 = State([[1], + [0], + [0], + [0]], + name='00') + +_11 = State([[0], + [0], + [0], + [1]], + name='11') + _ = I = UnitaryOperator([[1, 0], [0, 1]], name="-") @@ -232,6 +277,7 @@ class TwoQubitGate(object): C = TwoQubitGate("C") x = TwoQubitGate("x") + # TODO: End Hacky way to define 2-qbit gate ########################################################### @@ -338,6 +384,26 @@ def test(): [0, 1]]) +def test_to_from_angles(): + for q in [_0, _1, _p, _m]: + angles = q.to_angles() + s = State.from_angles(*angles) + assert q == s + + assert State.from_angles(0, 0) == _0 + assert State.from_angles(np.pi, 0) == _1 + assert State.from_angles(np.pi / 2, 0) == _p + assert State.from_angles(np.pi / 2, np.pi) == _m + for theta, phi, qbit in [ + (0, 0, _0), + (np.pi, 0, _1), + (np.pi / 2, 0, _p), + (np.pi / 2, np.pi, _m), + ]: + s = State.from_angles(theta, phi) + assert s == qbit + + def naive_load_test(N): import os import psutil @@ -513,4 +579,12 @@ def test_quantum_processor(): if __name__ == "__main__": test() - test_quantum_processor() + test_to_from_angles() + + # test_quantum_processor() + # print(_1 | _0) + # qubit = _00 + _11 + # print(qubit) + # bell = CNOT.on(qubit) + # HI = I*H + # print(bell)