Add examples and clean up some stuff

This commit is contained in:
2024-12-08 22:06:58 -08:00
parent 5adc755be4
commit 9b8584bd6f
10 changed files with 275 additions and 102 deletions

30
examples/bell.lisp Normal file
View File

@ -0,0 +1,30 @@
;;;; Example Bell state creation circuits
(in-package :cl-quantum/examples)
(defun make-bell-phi+-circuit ()
"Return a circuit that makes a Bell phi+ state. That is |00>+|11>."
(with-build-circuit
(:h 0)
(:cnot 1 0)))
(defun make-bell-phi--circuit ()
"Return a circuit that makes a Bell phi- state. That is |00>-|11>."
(with-build-circuit
(:h 0)
(:cnot 1 0)
(:z 1)))
(defun make-bell-psi+-circuit ()
"Return a circuit that makes a Bell psi+ state. That is |01>+|10>."
(with-build-circuit
(:x 1)
(:h 0)
(:cnot 1 0)))
(defun make-bell-psi--circuit ()
"Return a circuit that makes a Bell psi- state. That is |01>-|10>."
(with-build-circuit
(:x 1)
(:h 0)
(:cnot 1 0)
(:z 1)))

38
examples/grover.lisp Normal file
View File

@ -0,0 +1,38 @@
;;;; An example of Grover's algorithm (quantum search)
(in-package :cl-quantum/examples)
(defun count-grover-iterations (bits targets)
"Count the number of iterations it takes to have a high probability of finding
TARGETS in a search space of 2^BITS."
(values (floor (* (/ pi 4) (sqrt (/ (ash 1 bits) targets))))))
(defun make-grover-circuit (bits target)
"Generate a quantum circuit that runs Grover's algorithm over a state of BITS
bits and finds when the state is equal to TARGET."
(assert (> (ash 1 bits) target)
(bits target)
"Target bit of ~s out of range for state with ~s bits." target bits)
(with-build-circuit
;; Setup
(loop for i below bits do (:h i))
;; Oracle
(loop
repeat (count-grover-iterations bits 1)
do
(loop for i below bits
for cur = (logand (ash target (- i)) 1)
when (zerop cur)
do (:x i))
(:ncz 0 (loop for i from 1 below bits collect i))
(loop for i below bits
for cur = (logand (ash target (- i)) 1)
when (zerop cur)
do (:x i))
;; Diffuser
(loop for i below bits do (:h i))
(loop for i below bits do (:x i))
(:ncz 0 (loop for i from 1 below bits collect i))
(loop for i below bits do (:x i))
(loop for i below bits do (:h i)))))

8
examples/package.lisp Normal file
View File

@ -0,0 +1,8 @@
(defpackage :cl-quantum/examples
(:documentation "A collection of examples for ql-quantum.")
(:use :cl :cl-quantum/state :cl-quantum/circuit)
(:export #:make-grover-circuit
#:make-bell-phi+-circuit
#:make-bell-phi--circuit
#:make-bell-psi+-circuit
#:make-bell-psi--circuit))