idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
40,800
def sX ( qubit : Qubit , coefficient : complex = 1.0 ) -> Pauli : return Pauli . sigma ( qubit , 'X' , coefficient )
Return the Pauli sigma_X operator acting on the given qubit
40,801
def sY ( qubit : Qubit , coefficient : complex = 1.0 ) -> Pauli : return Pauli . sigma ( qubit , 'Y' , coefficient )
Return the Pauli sigma_Y operator acting on the given qubit
40,802
def sZ ( qubit : Qubit , coefficient : complex = 1.0 ) -> Pauli : return Pauli . sigma ( qubit , 'Z' , coefficient )
Return the Pauli sigma_Z operator acting on the given qubit
40,803
def pauli_sum ( * elements : Pauli ) -> Pauli : terms = [ ] key = itemgetter ( 0 ) for term , grp in groupby ( heapq . merge ( * elements , key = key ) , key = key ) : coeff = sum ( g [ 1 ] for g in grp ) if not isclose ( coeff , 0.0 ) : terms . append ( ( term , coeff ) ) return Pauli ( tuple ( terms ) )
Return the sum of elements of the Pauli algebra
40,804
def pauli_product ( * elements : Pauli ) -> Pauli : result_terms = [ ] for terms in product ( * elements ) : coeff = reduce ( mul , [ term [ 1 ] for term in terms ] ) ops = ( term [ 0 ] for term in terms ) out = [ ] key = itemgetter ( 0 ) for qubit , qops in groupby ( heapq . merge ( * ops , key = key ) , key = key ) : res = next ( qops ) [ 1 ] for op in qops : pair = res + op [ 1 ] res , rescoeff = PAULI_PROD [ pair ] coeff *= rescoeff if res != 'I' : out . append ( ( qubit , res ) ) p = Pauli ( ( ( tuple ( out ) , coeff ) , ) ) result_terms . append ( p ) return pauli_sum ( * result_terms )
Return the product of elements of the Pauli algebra
40,805
def pauli_pow ( pauli : Pauli , exponent : int ) -> Pauli : if not isinstance ( exponent , int ) or exponent < 0 : raise ValueError ( "The exponent must be a non-negative integer." ) if exponent == 0 : return Pauli . identity ( ) if exponent == 1 : return pauli y = Pauli . identity ( ) x = pauli n = exponent while n > 1 : if n % 2 == 0 : x = x * x n = n // 2 else : y = x * y x = x * x n = ( n - 1 ) // 2 return x * y
Raise an element of the Pauli algebra to a non - negative integer power .
40,806
def pauli_commuting_sets ( element : Pauli ) -> Tuple [ Pauli , ... ] : if len ( element ) < 2 : return ( element , ) groups : List [ Pauli ] = [ ] for term in element : pterm = Pauli ( ( term , ) ) assigned = False for i , grp in enumerate ( groups ) : if paulis_commute ( grp , pterm ) : groups [ i ] = grp + pterm assigned = True break if not assigned : groups . append ( pterm ) return tuple ( groups )
Gather the terms of a Pauli polynomial into commuting sets .
40,807
def astensor ( array : TensorLike ) -> BKTensor : array = np . asarray ( array , dtype = CTYPE ) return array
Converts a numpy array to the backend s tensor object
40,808
def productdiag ( tensor : BKTensor ) -> BKTensor : N = rank ( tensor ) tensor = reshape ( tensor , [ 2 ** ( N // 2 ) , 2 ** ( N // 2 ) ] ) tensor = np . diag ( tensor ) tensor = reshape ( tensor , [ 2 ] * ( N // 2 ) ) return tensor
Returns the matrix diagonal of the product tensor
40,809
def tensormul ( tensor0 : BKTensor , tensor1 : BKTensor , indices : typing . List [ int ] ) -> BKTensor : r N = rank ( tensor1 ) K = rank ( tensor0 ) // 2 assert K == len ( indices ) out = list ( EINSUM_SUBSCRIPTS [ 0 : N ] ) left_in = list ( EINSUM_SUBSCRIPTS [ N : N + K ] ) left_out = [ out [ idx ] for idx in indices ] right = list ( EINSUM_SUBSCRIPTS [ 0 : N ] ) for idx , s in zip ( indices , left_in ) : right [ idx ] = s subscripts = '' . join ( left_out + left_in + [ ',' ] + right + [ '->' ] + out ) tensor = einsum ( subscripts , tensor0 , tensor1 ) return tensor
r Generalization of matrix multiplication to product tensors .
40,810
def invert_map ( mapping : dict , one_to_one : bool = True ) -> dict : if one_to_one : inv_map = { value : key for key , value in mapping . items ( ) } else : inv_map = { } for key , value in mapping . items ( ) : inv_map . setdefault ( value , set ( ) ) . add ( key ) return inv_map
Invert a dictionary . If not one_to_one then the inverted map will contain lists of former keys as values .
40,811
def bitlist_to_int ( bitlist : Sequence [ int ] ) -> int : return int ( '' . join ( [ str ( d ) for d in bitlist ] ) , 2 )
Converts a sequence of bits to an integer .
40,812
def int_to_bitlist ( x : int , pad : int = None ) -> Sequence [ int ] : if pad is None : form = '{:0b}' else : form = '{:0' + str ( pad ) + 'b}' return [ int ( b ) for b in form . format ( x ) ]
Converts an integer to a binary sequence of bits .
40,813
def spanning_tree_count ( graph : nx . Graph ) -> int : laplacian = nx . laplacian_matrix ( graph ) . toarray ( ) comatrix = laplacian [ : - 1 , : - 1 ] det = np . linalg . det ( comatrix ) count = int ( round ( det ) ) return count
Return the number of unique spanning trees of a graph using Kirchhoff s matrix tree theorem .
40,814
def rationalize ( flt : float , denominators : Set [ int ] = None ) -> Fraction : if denominators is None : denominators = _DENOMINATORS frac = Fraction . from_float ( flt ) . limit_denominator ( ) if frac . denominator not in denominators : raise ValueError ( 'Cannot rationalize' ) return frac
Convert a floating point number to a Fraction with a small denominator .
40,815
def symbolize ( flt : float ) -> sympy . Symbol : try : ratio = rationalize ( flt ) res = sympy . simplify ( ratio ) except ValueError : ratio = rationalize ( flt / np . pi ) res = sympy . simplify ( ratio ) * sympy . pi return res
Attempt to convert a real number into a simpler symbolic representation .
40,816
def pyquil_to_image ( program : pyquil . Program ) -> PIL . Image : circ = pyquil_to_circuit ( program ) latex = circuit_to_latex ( circ ) img = render_latex ( latex ) return img
Returns an image of a pyquil circuit .
40,817
def circuit_to_pyquil ( circuit : Circuit ) -> pyquil . Program : prog = pyquil . Program ( ) for elem in circuit . elements : if isinstance ( elem , Gate ) and elem . name in QUIL_GATES : params = list ( elem . params . values ( ) ) if elem . params else [ ] prog . gate ( elem . name , params , elem . qubits ) elif isinstance ( elem , Measure ) : prog . measure ( elem . qubit , elem . cbit ) else : raise ValueError ( 'Cannot convert operation to pyquil' ) return prog
Convert a QuantumFlow circuit to a pyQuil program
40,818
def pyquil_to_circuit ( program : pyquil . Program ) -> Circuit : circ = Circuit ( ) for inst in program . instructions : if isinstance ( inst , pyquil . Declare ) : continue if isinstance ( inst , pyquil . Halt ) : continue if isinstance ( inst , pyquil . Pragma ) : continue elif isinstance ( inst , pyquil . Measurement ) : circ += Measure ( inst . qubit . index ) elif isinstance ( inst , pyquil . Gate ) : defgate = STDGATES [ inst . name ] gate = defgate ( * inst . params ) qubits = [ q . index for q in inst . qubits ] gate = gate . relabel ( qubits ) circ += gate else : raise ValueError ( 'PyQuil program is not protoquil' ) return circ
Convert a protoquil pyQuil program to a QuantumFlow Circuit
40,819
def quil_to_program ( quil : str ) -> Program : pyquil_instructions = pyquil . parser . parse ( quil ) return pyquil_to_program ( pyquil_instructions )
Parse a quil program and return a Program object
40,820
def state_to_wavefunction ( state : State ) -> pyquil . Wavefunction : amplitudes = state . vec . asarray ( ) amplitudes = amplitudes . transpose ( ) amplitudes = amplitudes . reshape ( [ amplitudes . size ] ) return pyquil . Wavefunction ( amplitudes )
Convert a QuantumFlow state to a pyQuil Wavefunction
40,821
def load ( self , binary : pyquil . Program ) -> 'QuantumFlowQVM' : assert self . status in [ 'connected' , 'done' ] prog = quil_to_program ( str ( binary ) ) self . _prog = prog self . program = binary self . status = 'loaded' return self
Load a pyQuil program and initialize QVM into a fresh state .
40,822
def run ( self ) -> 'QuantumFlowQVM' : assert self . status in [ 'loaded' ] self . status = 'running' self . _ket = self . _prog . run ( ) return self
Run a previously loaded program
40,823
def wavefunction ( self ) -> pyquil . Wavefunction : assert self . status == 'done' assert self . _ket is not None wavefn = state_to_wavefunction ( self . _ket ) return wavefn
Return the wavefunction of a completed program .
40,824
def evaluate ( tensor : BKTensor ) -> TensorLike : if isinstance ( tensor , _DTYPE ) : if torch . numel ( tensor ) == 1 : return tensor . item ( ) if tensor . numel ( ) == 2 : return tensor [ 0 ] . cpu ( ) . numpy ( ) + 1.0j * tensor [ 1 ] . cpu ( ) . numpy ( ) return tensor [ 0 ] . cpu ( ) . numpy ( ) + 1.0j * tensor [ 1 ] . cpu ( ) . numpy ( ) return tensor
Return the value of a tensor
40,825
def rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
Return the number of dimensions of a tensor
40,826
def state_fidelity ( state0 : State , state1 : State ) -> bk . BKTensor : assert state0 . qubits == state1 . qubits tensor = bk . absolute ( bk . inner ( state0 . tensor , state1 . tensor ) ) ** bk . fcast ( 2 ) return tensor
Return the quantum fidelity between pure states .
40,827
def state_angle ( ket0 : State , ket1 : State ) -> bk . BKTensor : return fubini_study_angle ( ket0 . vec , ket1 . vec )
The Fubini - Study angle between states .
40,828
def states_close ( state0 : State , state1 : State , tolerance : float = TOLERANCE ) -> bool : return vectors_close ( state0 . vec , state1 . vec , tolerance )
Returns True if states are almost identical .
40,829
def purity ( rho : Density ) -> bk . BKTensor : tensor = rho . tensor N = rho . qubit_nb matrix = bk . reshape ( tensor , [ 2 ** N , 2 ** N ] ) return bk . trace ( bk . matmul ( matrix , matrix ) )
Calculate the purity of a mixed quantum state .
40,830
def bures_distance ( rho0 : Density , rho1 : Density ) -> float : fid = fidelity ( rho0 , rho1 ) op0 = asarray ( rho0 . asoperator ( ) ) op1 = asarray ( rho1 . asoperator ( ) ) tr0 = np . trace ( op0 ) tr1 = np . trace ( op1 ) return np . sqrt ( tr0 + tr1 - 2. * np . sqrt ( fid ) )
Return the Bures distance between mixed quantum states
40,831
def bures_angle ( rho0 : Density , rho1 : Density ) -> float : return np . arccos ( np . sqrt ( fidelity ( rho0 , rho1 ) ) )
Return the Bures angle between mixed quantum states
40,832
def density_angle ( rho0 : Density , rho1 : Density ) -> bk . BKTensor : return fubini_study_angle ( rho0 . vec , rho1 . vec )
The Fubini - Study angle between density matrices
40,833
def densities_close ( rho0 : Density , rho1 : Density , tolerance : float = TOLERANCE ) -> bool : return vectors_close ( rho0 . vec , rho1 . vec , tolerance )
Returns True if densities are almost identical .
40,834
def entropy ( rho : Density , base : float = None ) -> float : op = asarray ( rho . asoperator ( ) ) probs = np . linalg . eigvalsh ( op ) probs = np . maximum ( probs , 0.0 ) return scipy . stats . entropy ( probs , base = base )
Returns the von - Neumann entropy of a mixed quantum state .
40,835
def mutual_info ( rho : Density , qubits0 : Qubits , qubits1 : Qubits = None , base : float = None ) -> float : if qubits1 is None : qubits1 = tuple ( set ( rho . qubits ) - set ( qubits0 ) ) rho0 = rho . partial_trace ( qubits1 ) rho1 = rho . partial_trace ( qubits0 ) ent = entropy ( rho , base ) ent0 = entropy ( rho0 , base ) ent1 = entropy ( rho1 , base ) return ent0 + ent1 - ent
Compute the bipartite von - Neumann mutual information of a mixed quantum state .
40,836
def gate_angle ( gate0 : Gate , gate1 : Gate ) -> bk . BKTensor : return fubini_study_angle ( gate0 . vec , gate1 . vec )
The Fubini - Study angle between gates
40,837
def channel_angle ( chan0 : Channel , chan1 : Channel ) -> bk . BKTensor : return fubini_study_angle ( chan0 . vec , chan1 . vec )
The Fubini - Study angle between channels
40,838
def inner_product ( vec0 : QubitVector , vec1 : QubitVector ) -> bk . BKTensor : if vec0 . rank != vec1 . rank or vec0 . qubit_nb != vec1 . qubit_nb : raise ValueError ( 'Incompatibly vectors. Qubits and rank must match' ) vec1 = vec1 . permute ( vec0 . qubits ) return bk . inner ( vec0 . tensor , vec1 . tensor )
Hilbert - Schmidt inner product between qubit vectors
40,839
def outer_product ( vec0 : QubitVector , vec1 : QubitVector ) -> QubitVector : R = vec0 . rank R1 = vec1 . rank N0 = vec0 . qubit_nb N1 = vec1 . qubit_nb if R != R1 : raise ValueError ( 'Incompatibly vectors. Rank must match' ) if not set ( vec0 . qubits ) . isdisjoint ( vec1 . qubits ) : raise ValueError ( 'Overlapping qubits' ) qubits : Qubits = tuple ( vec0 . qubits ) + tuple ( vec1 . qubits ) tensor = bk . outer ( vec0 . tensor , vec1 . tensor ) tensor = bk . reshape ( tensor , ( [ 2 ** N0 ] * R ) + ( [ 2 ** N1 ] * R ) ) perm = [ idx for ij in zip ( range ( 0 , R ) , range ( R , 2 * R ) ) for idx in ij ] tensor = bk . transpose ( tensor , perm ) return QubitVector ( tensor , qubits )
Direct product of qubit vectors
40,840
def vectors_close ( vec0 : QubitVector , vec1 : QubitVector , tolerance : float = TOLERANCE ) -> bool : if vec0 . rank != vec1 . rank : return False if vec0 . qubit_nb != vec1 . qubit_nb : return False if set ( vec0 . qubits ) ^ set ( vec1 . qubits ) : return False return bk . evaluate ( fubini_study_angle ( vec0 , vec1 ) ) <= tolerance
Return True if vectors in close in the projective Hilbert space .
40,841
def flatten ( self ) -> bk . BKTensor : N = self . qubit_nb R = self . rank return bk . reshape ( self . tensor , [ 2 ** N ] * R )
Return tensor with with qubit indices flattened
40,842
def relabel ( self , qubits : Qubits ) -> 'QubitVector' : qubits = tuple ( qubits ) assert len ( qubits ) == self . qubit_nb vec = copy ( self ) vec . qubits = qubits return vec
Return a copy of this vector with new qubits
40,843
def H ( self ) -> 'QubitVector' : N = self . qubit_nb R = self . rank tensor = self . tensor tensor = bk . reshape ( tensor , [ 2 ** ( N * R // 2 ) ] * 2 ) tensor = bk . transpose ( tensor ) tensor = bk . reshape ( tensor , [ 2 ] * R * N ) tensor = bk . conj ( tensor ) return QubitVector ( tensor , self . qubits )
Return the conjugate transpose of this tensor .
40,844
def norm ( self ) -> bk . BKTensor : return bk . absolute ( bk . inner ( self . tensor , self . tensor ) )
Return the norm of this vector
40,845
def partial_trace ( self , qubits : Qubits ) -> 'QubitVector' : N = self . qubit_nb R = self . rank if R == 1 : raise ValueError ( 'Cannot take trace of vector' ) new_qubits : List [ Qubit ] = list ( self . qubits ) for q in qubits : new_qubits . remove ( q ) if not new_qubits : raise ValueError ( 'Cannot remove all qubits with partial_trace.' ) indices = [ self . qubits . index ( qubit ) for qubit in qubits ] subscripts = list ( EINSUM_SUBSCRIPTS ) [ 0 : N * R ] for idx in indices : for r in range ( 1 , R ) : subscripts [ r * N + idx ] = subscripts [ idx ] subscript_str = '' . join ( subscripts ) tensor = self . asarray ( ) tensor = np . einsum ( subscript_str , tensor ) return QubitVector ( tensor , new_qubits )
Return the partial trace over some subset of qubits
40,846
def fit_zyz ( target_gate ) : steps = 1000 dev = '/gpu:0' if bk . DEVICE == 'gpu' else '/cpu:0' with tf . device ( dev ) : t = tf . Variable ( tf . random . normal ( [ 3 ] ) ) def loss_fn ( ) : gate = qf . ZYZ ( t [ 0 ] , t [ 1 ] , t [ 2 ] ) ang = qf . fubini_study_angle ( target_gate . vec , gate . vec ) return ang opt = tf . optimizers . Adam ( learning_rate = 0.001 ) opt . minimize ( loss_fn , var_list = [ t ] ) for step in range ( steps ) : opt . minimize ( loss_fn , var_list = [ t ] ) loss = loss_fn ( ) print ( step , loss . numpy ( ) ) if loss < 0.01 : break else : print ( "Failed to coverge" ) return bk . evaluate ( t )
Tensorflow 2 . 0 example . Given an arbitrary one - qubit gate use gradient descent to find corresponding parameters of a universal ZYZ gate .
40,847
def run ( self , ket : State = None ) -> State : if ket is None : qubits = self . qubits ket = zero_state ( qubits ) ket = self . _initilize ( ket ) pc = 0 while pc >= 0 and pc < len ( self ) : instr = self . instructions [ pc ] ket = ket . update ( { PC : pc + 1 } ) ket = instr . run ( ket ) pc = ket . memory [ PC ] return ket
Compiles and runs a program . The optional program argument supplies the initial state and memory . Else qubits and classical bits start from zero states .
40,848
def relabel ( self , qubits : Qubits ) -> 'Gate' : gate = copy ( self ) gate . vec = gate . vec . relabel ( qubits ) return gate
Return a copy of this Gate with new qubits
40,849
def run ( self , ket : State ) -> State : qubits = self . qubits indices = [ ket . qubits . index ( q ) for q in qubits ] tensor = bk . tensormul ( self . tensor , ket . tensor , indices ) return State ( tensor , ket . qubits , ket . memory )
Apply the action of this gate upon a state
40,850
def evolve ( self , rho : Density ) -> Density : chan = self . aschannel ( ) return chan . evolve ( rho )
Apply the action of this gate upon a density
40,851
def aschannel ( self ) -> 'Channel' : N = self . qubit_nb R = 4 tensor = bk . outer ( self . tensor , self . H . tensor ) tensor = bk . reshape ( tensor , [ 2 ** N ] * R ) tensor = bk . transpose ( tensor , [ 0 , 3 , 1 , 2 ] ) return Channel ( tensor , self . qubits )
Converts a Gate into a Channel
40,852
def su ( self ) -> 'Gate' : rank = 2 ** self . qubit_nb U = asarray ( self . asoperator ( ) ) U /= np . linalg . det ( U ) ** ( 1 / rank ) return Gate ( tensor = U , qubits = self . qubits )
Convert gate tensor to the special unitary group .
40,853
def relabel ( self , qubits : Qubits ) -> 'Channel' : chan = copy ( self ) chan . vec = chan . vec . relabel ( qubits ) return chan
Return a copy of this channel with new qubits
40,854
def permute ( self , qubits : Qubits ) -> 'Channel' : vec = self . vec . permute ( qubits ) return Channel ( vec . tensor , qubits = vec . qubits )
Return a copy of this channel with qubits in new order
40,855
def sharp ( self ) -> 'Channel' : r N = self . qubit_nb tensor = self . tensor tensor = bk . reshape ( tensor , [ 2 ** N ] * 4 ) tensor = bk . transpose ( tensor , ( 0 , 2 , 1 , 3 ) ) tensor = bk . reshape ( tensor , [ 2 ] * 4 * N ) return Channel ( tensor , self . qubits )
r Return the sharp transpose of the superoperator .
40,856
def choi ( self ) -> bk . BKTensor : N = self . qubit_nb return bk . reshape ( self . sharp . tensor , [ 2 ** ( N * 2 ) ] * 2 )
Return the Choi matrix representation of this super operator
40,857
def evolve ( self , rho : Density ) -> Density : N = rho . qubit_nb qubits = rho . qubits indices = list ( [ qubits . index ( q ) for q in self . qubits ] ) + list ( [ qubits . index ( q ) + N for q in self . qubits ] ) tensor = bk . tensormul ( self . tensor , rho . tensor , indices ) return Density ( tensor , qubits , rho . memory )
Apply the action of this channel upon a density
40,858
def fcast ( value : float ) -> TensorLike : newvalue = tf . cast ( value , FTYPE ) if DEVICE == 'gpu' : newvalue = newvalue . gpu ( ) return newvalue
Cast to float tensor
40,859
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( array , dtype = CTYPE ) if DEVICE == 'gpu' : tensor = tensor . gpu ( ) N = int ( math . log2 ( size ( tensor ) ) ) tensor = tf . reshape ( tensor , ( [ 2 ] * N ) ) return tensor
Convert to product tensor
40,860
def count_operations ( elements : Iterable [ Operation ] ) -> Dict [ Type [ Operation ] , int ] : op_count : Dict [ Type [ Operation ] , int ] = defaultdict ( int ) for elem in elements : op_count [ type ( elem ) ] += 1 return dict ( op_count )
Return a count of different operation types given a colelction of operations such as a Circuit or DAGCircuit
40,861
def map_gate ( gate : Gate , args : Sequence [ Qubits ] ) -> Circuit : circ = Circuit ( ) for qubits in args : circ += gate . relabel ( qubits ) return circ
Applies the same gate all input qubits in the argument list .
40,862
def qft_circuit ( qubits : Qubits ) -> Circuit : N = len ( qubits ) circ = Circuit ( ) for n0 in range ( N ) : q0 = qubits [ n0 ] circ += H ( q0 ) for n1 in range ( n0 + 1 , N ) : q1 = qubits [ n1 ] angle = pi / 2 ** ( n1 - n0 ) circ += CPHASE ( angle , q1 , q0 ) circ . extend ( reversal_circuit ( qubits ) ) return circ
Returns the Quantum Fourier Transform circuit
40,863
def reversal_circuit ( qubits : Qubits ) -> Circuit : N = len ( qubits ) circ = Circuit ( ) for n in range ( N // 2 ) : circ += SWAP ( qubits [ n ] , qubits [ N - 1 - n ] ) return circ
Returns a circuit to reverse qubits
40,864
def zyz_circuit ( t0 : float , t1 : float , t2 : float , q0 : Qubit ) -> Circuit : circ = Circuit ( ) circ += TZ ( t0 , q0 ) circ += TY ( t1 , q0 ) circ += TZ ( t2 , q0 ) return circ
Circuit equivalent of 1 - qubit ZYZ gate
40,865
def phase_estimation_circuit ( gate : Gate , outputs : Qubits ) -> Circuit : circ = Circuit ( ) circ += map_gate ( H ( ) , list ( zip ( outputs ) ) ) for cq in reversed ( outputs ) : cgate = control_gate ( cq , gate ) circ += cgate gate = gate @ gate circ += qft_circuit ( outputs ) . H return circ
Returns a circuit for quantum phase estimation .
40,866
def ghz_circuit ( qubits : Qubits ) -> Circuit : circ = Circuit ( ) circ += H ( qubits [ 0 ] ) for q0 in range ( 0 , len ( qubits ) - 1 ) : circ += CNOT ( qubits [ q0 ] , qubits [ q0 + 1 ] ) return circ
Returns a circuit that prepares a multi - qubit Bell state from the zero state .
40,867
def extend ( self , other : Operation ) -> None : if isinstance ( other , Circuit ) : self . elements . extend ( other . elements ) else : self . elements . extend ( [ other ] )
Append gates from circuit to the end of this circuit
40,868
def run ( self , ket : State = None ) -> State : if ket is None : qubits = self . qubits ket = zero_state ( qubits = qubits ) for elem in self . elements : ket = elem . run ( ket ) return ket
Apply the action of this circuit upon a state .
40,869
def asgate ( self ) -> Gate : gate = identity_gate ( self . qubits ) for elem in self . elements : gate = elem . asgate ( ) @ gate return gate
Return the action of this circuit as a gate
40,870
def join_channels ( * channels : Channel ) -> Channel : vectors = [ chan . vec for chan in channels ] vec = reduce ( outer_product , vectors ) return Channel ( vec . tensor , vec . qubits )
Join two channels acting on different qubits into a single channel acting on all qubits
40,871
def channel_to_kraus ( chan : Channel ) -> 'Kraus' : qubits = chan . qubits N = chan . qubit_nb choi = asarray ( chan . choi ( ) ) evals , evecs = np . linalg . eig ( choi ) evecs = np . transpose ( evecs ) assert np . allclose ( evals . imag , 0.0 ) assert np . all ( evals . real >= 0.0 ) values = np . sqrt ( evals . real ) ops = [ ] for i in range ( 2 ** ( 2 * N ) ) : if not np . isclose ( values [ i ] , 0.0 ) : mat = np . reshape ( evecs [ i ] , ( 2 ** N , 2 ** N ) ) * values [ i ] g = Gate ( mat , qubits ) ops . append ( g ) return Kraus ( ops )
Convert a channel superoperator into a Kraus operator representation of the same channel .
40,872
def run ( self , ket : State ) -> State : res = [ op . run ( ket ) for op in self . operators ] probs = [ asarray ( ket . norm ( ) ) * w for ket , w in zip ( res , self . weights ) ] probs = np . asarray ( probs ) probs /= np . sum ( probs ) newket = np . random . choice ( res , p = probs ) return newket . normalize ( )
Apply the action of this Kraus quantum operation upon a state
40,873
def evolve ( self , rho : Density ) -> Density : qubits = rho . qubits results = [ op . evolve ( rho ) for op in self . operators ] tensors = [ rho . tensor * w for rho , w in zip ( results , self . weights ) ] tensor = reduce ( add , tensors ) return Density ( tensor , qubits )
Apply the action of this Kraus quantum operation upon a density
40,874
def H ( self ) -> 'Kraus' : operators = [ op . H for op in self . operators ] return Kraus ( operators , self . weights )
Return the complex conjugate of this Kraus operation
40,875
def asgate ( self ) -> Gate : return np . random . choice ( self . operators , p = self . weights )
Return one of the composite Kraus operators at random with the appropriate weights
40,876
def _display_layers ( circ : Circuit , qubits : Qubits ) -> Circuit : N = len ( qubits ) qubit_idx = dict ( zip ( qubits , range ( N ) ) ) gate_layers = DAGCircuit ( circ ) . layers ( ) layers = [ ] lcirc = Circuit ( ) layers . append ( lcirc ) unused = [ True ] * N for gl in gate_layers : assert isinstance ( gl , Circuit ) for gate in gl : indices = [ qubit_idx [ q ] for q in gate . qubits ] if not all ( unused [ min ( indices ) : max ( indices ) + 1 ] ) : lcirc = Circuit ( ) layers . append ( lcirc ) unused = [ True ] * N unused [ min ( indices ) : max ( indices ) + 1 ] = [ False ] * ( max ( indices ) - min ( indices ) + 1 ) lcirc += gate return Circuit ( layers )
Separate a circuit into groups of gates that do not visually overlap
40,877
def render_latex ( latex : str ) -> PIL . Image : tmpfilename = 'circ' with tempfile . TemporaryDirectory ( ) as tmpdirname : tmppath = os . path . join ( tmpdirname , tmpfilename ) with open ( tmppath + '.tex' , 'w' ) as latex_file : latex_file . write ( latex ) subprocess . run ( [ "pdflatex" , "-halt-on-error" , "-output-directory={}" . format ( tmpdirname ) , "{}" . format ( tmpfilename + '.tex' ) ] , stdout = subprocess . PIPE , stderr = subprocess . DEVNULL , check = True ) subprocess . run ( [ 'pdftocairo' , '-singlefile' , '-png' , '-q' , tmppath + '.pdf' , tmppath ] ) img = PIL . Image . open ( tmppath + '.png' ) return img
Convert a single page LaTeX document into an image .
40,878
def circuit_to_image ( circ : Circuit , qubits : Qubits = None ) -> PIL . Image : latex = circuit_to_latex ( circ , qubits ) img = render_latex ( latex ) return img
Create an image of a quantum circuit .
40,879
def _latex_format ( obj : Any ) -> str : if isinstance ( obj , float ) : try : return sympy . latex ( symbolize ( obj ) ) except ValueError : return "{0:.4g}" . format ( obj ) return str ( obj )
Format an object as a latex string .
40,880
def fit_zyz ( target_gate ) : assert bk . BACKEND == 'eager' tf = bk . TL tfe = bk . tfe steps = 4000 dev = '/gpu:0' if bk . DEVICE == 'gpu' else '/cpu:0' with tf . device ( dev ) : t = tfe . Variable ( np . random . normal ( size = [ 3 ] ) , name = 't' ) def loss_fn ( ) : gate = qf . ZYZ ( t [ 0 ] , t [ 1 ] , t [ 2 ] ) ang = qf . fubini_study_angle ( target_gate . vec , gate . vec ) return ang loss_and_grads = tfe . implicit_value_and_gradients ( loss_fn ) opt = tf . train . AdamOptimizer ( learning_rate = 0.001 ) for step in range ( steps ) : loss , grads_and_vars = loss_and_grads ( ) sys . stdout . write ( '\r' ) sys . stdout . write ( "step: {:3d} loss: {:10.9f}" . format ( step , loss . numpy ( ) ) ) if loss < 0.0001 : break opt . apply_gradients ( grads_and_vars ) print ( ) return bk . evaluate ( t )
Tensorflow eager mode example . Given an arbitrary one - qubit gate use gradient descent to find corresponding parameters of a universal ZYZ gate .
40,881
def print_versions ( file : typing . TextIO = None ) -> None : print ( '** QuantumFlow dependencies (> python -m quantumflow.meta) **' ) print ( 'quantumflow \t' , qf . __version__ , file = file ) print ( 'python \t' , sys . version [ 0 : 5 ] , file = file ) print ( 'numpy \t' , np . __version__ , file = file ) print ( 'networkx \t' , nx . __version__ , file = file ) print ( 'cvxpy \t' , cvx . __version__ , file = file ) print ( 'pyquil \t' , pyquil . __version__ , file = file ) print ( bk . name , ' \t' , bk . version , '(BACKEND)' , file = file )
Print version strings of currently installed dependencies
40,882
def fit_zyz ( target_gate ) : assert bk . BACKEND == 'tensorflow' tf = bk . TL steps = 4000 t = tf . get_variable ( 't' , [ 3 ] ) gate = qf . ZYZ ( t [ 0 ] , t [ 1 ] , t [ 2 ] ) ang = qf . fubini_study_angle ( target_gate . vec , gate . vec ) opt = tf . train . AdamOptimizer ( learning_rate = 0.001 ) train = opt . minimize ( ang , var_list = [ t ] ) with tf . Session ( ) as sess : init_op = tf . global_variables_initializer ( ) sess . run ( init_op ) for step in range ( steps ) : sess . run ( train ) loss = sess . run ( ang ) sys . stdout . write ( '\r' ) sys . stdout . write ( "step: {} gate_angle: {}" . format ( step , loss ) ) if loss < 0.0001 : break print ( ) return sess . run ( t )
Tensorflow example . Given an arbitrary one - qubit gate use gradient descent to find corresponding parameters of a universal ZYZ gate .
40,883
def zyz_decomposition ( gate : Gate ) -> Circuit : if gate . qubit_nb != 1 : raise ValueError ( 'Expected 1-qubit gate' ) q , = gate . qubits U = asarray ( gate . asoperator ( ) ) U /= np . linalg . det ( U ) ** ( 1 / 2 ) if abs ( U [ 0 , 0 ] ) > abs ( U [ 1 , 0 ] ) : theta1 = 2 * np . arccos ( min ( abs ( U [ 0 , 0 ] ) , 1 ) ) else : theta1 = 2 * np . arcsin ( min ( abs ( U [ 1 , 0 ] ) , 1 ) ) cos_halftheta1 = np . cos ( theta1 / 2 ) if not np . isclose ( cos_halftheta1 , 0.0 ) : phase = U [ 1 , 1 ] / cos_halftheta1 theta0_plus_theta2 = 2 * np . arctan2 ( np . imag ( phase ) , np . real ( phase ) ) else : theta0_plus_theta2 = 0.0 sin_halftheta1 = np . sin ( theta1 / 2 ) if not np . isclose ( sin_halftheta1 , 0.0 ) : phase = U [ 1 , 0 ] / sin_halftheta1 theta0_sub_theta2 = 2 * np . arctan2 ( np . imag ( phase ) , np . real ( phase ) ) else : theta0_sub_theta2 = 0.0 theta0 = ( theta0_plus_theta2 + theta0_sub_theta2 ) / 2 theta2 = ( theta0_plus_theta2 - theta0_sub_theta2 ) / 2 t0 = theta0 / np . pi t1 = theta1 / np . pi t2 = theta2 / np . pi circ1 = Circuit ( ) circ1 += TZ ( t2 , q ) circ1 += TY ( t1 , q ) circ1 += TZ ( t0 , q ) return circ1
Returns the Euler Z - Y - Z decomposition of a local 1 - qubit gate .
40,884
def kronecker_decomposition ( gate : Gate ) -> Circuit : if gate . qubit_nb != 2 : raise ValueError ( 'Expected 2-qubit gate' ) U = asarray ( gate . asoperator ( ) ) rank = 2 ** gate . qubit_nb U /= np . linalg . det ( U ) ** ( 1 / rank ) R = np . stack ( [ U [ 0 : 2 , 0 : 2 ] . reshape ( 4 ) , U [ 0 : 2 , 2 : 4 ] . reshape ( 4 ) , U [ 2 : 4 , 0 : 2 ] . reshape ( 4 ) , U [ 2 : 4 , 2 : 4 ] . reshape ( 4 ) ] ) u , s , vh = np . linalg . svd ( R ) v = vh . transpose ( ) A = ( np . sqrt ( s [ 0 ] ) * u [ : , 0 ] ) . reshape ( 2 , 2 ) B = ( np . sqrt ( s [ 0 ] ) * v [ : , 0 ] ) . reshape ( 2 , 2 ) q0 , q1 = gate . qubits g0 = Gate ( A , qubits = [ q0 ] ) g1 = Gate ( B , qubits = [ q1 ] ) if not gates_close ( gate , Circuit ( [ g0 , g1 ] ) . asgate ( ) ) : raise ValueError ( "Gate cannot be decomposed into two 1-qubit gates" ) circ = Circuit ( ) circ += zyz_decomposition ( g0 ) circ += zyz_decomposition ( g1 ) assert gates_close ( gate , circ . asgate ( ) ) return circ
Decompose a 2 - qubit unitary composed of two 1 - qubit local gates .
40,885
def canonical_coords ( gate : Gate ) -> Sequence [ float ] : circ = canonical_decomposition ( gate ) gate = circ . elements [ 6 ] params = [ gate . params [ key ] for key in ( 'tx' , 'ty' , 'tz' ) ] return params
Returns the canonical coordinates of a 2 - qubit gate
40,886
def _eig_complex_symmetric ( M : np . ndarray ) -> Tuple [ np . ndarray , np . ndarray ] : if not np . allclose ( M , M . transpose ( ) ) : raise np . linalg . LinAlgError ( 'Not a symmetric matrix' ) max_attempts = 16 for _ in range ( max_attempts ) : c = np . random . uniform ( 0 , 1 ) matrix = c * M . real + ( 1 - c ) * M . imag _ , eigvecs = np . linalg . eigh ( matrix ) eigvecs = np . array ( eigvecs , dtype = complex ) eigvals = np . diag ( eigvecs . transpose ( ) @ M @ eigvecs ) reconstructed = eigvecs @ np . diag ( eigvals ) @ eigvecs . transpose ( ) if np . allclose ( M , reconstructed ) : return eigvals , eigvecs raise np . linalg . LinAlgError ( 'Cannot diagonalize complex symmetric matrix.' )
Diagonalize a complex symmetric matrix . The eigenvalues are complex and the eigenvectors form an orthogonal matrix .
40,887
def maxcut_qaoa ( graph , steps = DEFAULT_STEPS , learning_rate = LEARNING_RATE , verbose = False ) : if not isinstance ( graph , nx . Graph ) : graph = nx . from_edgelist ( graph ) init_scale = 0.01 init_bias = 0.5 init_beta = normal ( loc = init_bias , scale = init_scale , size = [ steps ] ) init_gamma = normal ( loc = init_bias , scale = init_scale , size = [ steps ] ) beta = tf . get_variable ( 'beta' , initializer = init_beta ) gamma = tf . get_variable ( 'gamma' , initializer = init_gamma ) circ = qubo_circuit ( graph , steps , beta , gamma ) cuts = graph_cuts ( graph ) maxcut = cuts . max ( ) expect = circ . run ( ) . expectation ( cuts ) loss = - expect opt = tf . train . GradientDescentOptimizer ( learning_rate = learning_rate ) train = opt . minimize ( loss , var_list = [ beta , gamma ] ) with tf . Session ( ) as sess : init_op = tf . global_variables_initializer ( ) sess . run ( init_op ) block = 10 min_difference = 0.0001 last_ratio = - 1 for step in range ( 0 , MAX_OPT_STEPS , block ) : for _ in range ( block ) : sess . run ( train ) ratio = sess . run ( expect ) / maxcut if ratio - last_ratio < min_difference : break last_ratio = ratio if verbose : print ( "# step: {} ratio: {:.4f}%" . format ( step , ratio ) ) opt_beta = sess . run ( beta ) opt_gamma = sess . run ( gamma ) return ratio , opt_beta , opt_gamma
QAOA Maxcut using tensorflow
40,888
def identity_gate ( qubits : Union [ int , Qubits ] ) -> Gate : _ , qubits = qubits_count_tuple ( qubits ) return I ( * qubits )
Returns the K - qubit identity gate
40,889
def join_gates ( * gates : Gate ) -> Gate : vectors = [ gate . vec for gate in gates ] vec = reduce ( outer_product , vectors ) return Gate ( vec . tensor , vec . qubits )
Direct product of two gates . Qubit count is the sum of each gate s bit count .
40,890
def control_gate ( control : Qubit , gate : Gate ) -> Gate : if control in gate . qubits : raise ValueError ( 'Gate and control qubits overlap' ) qubits = [ control , * gate . qubits ] gate_tensor = join_gates ( P0 ( control ) , identity_gate ( gate . qubits ) ) . tensor + join_gates ( P1 ( control ) , gate ) . tensor controlled_gate = Gate ( qubits = qubits , tensor = gate_tensor ) return controlled_gate
Return a controlled unitary gate . Given a gate acting on K qubits return a new gate on K + 1 qubits prepended with a control bit .
40,891
def conditional_gate ( control : Qubit , gate0 : Gate , gate1 : Gate ) -> Gate : assert gate0 . qubits == gate1 . qubits tensor = join_gates ( P0 ( control ) , gate0 ) . tensor tensor += join_gates ( P1 ( control ) , gate1 ) . tensor gate = Gate ( tensor = tensor , qubits = [ control , * gate0 . qubits ] ) return gate
Return a conditional unitary gate . Do gate0 on bit 1 if bit 0 is zero else do gate1 on 1
40,892
def print_gate ( gate : Gate , ndigits : int = 2 , file : TextIO = None ) -> None : N = gate . qubit_nb gate_tensor = gate . vec . asarray ( ) lines = [ ] for index , amplitude in np . ndenumerate ( gate_tensor ) : ket = "" . join ( [ str ( n ) for n in index [ 0 : N ] ] ) bra = "" . join ( [ str ( index [ n ] ) for n in range ( N , 2 * N ) ] ) if round ( abs ( amplitude ) ** 2 , ndigits ) > 0.0 : lines . append ( '{} -> {} : {}' . format ( bra , ket , amplitude ) ) lines . sort ( key = lambda x : int ( x [ 0 : N ] ) ) print ( '\n' . join ( lines ) , file = file )
Pretty print a gate tensor
40,893
def random_gate ( qubits : Union [ int , Qubits ] ) -> Gate : r N , qubits = qubits_count_tuple ( qubits ) unitary = scipy . stats . unitary_group . rvs ( 2 ** N ) return Gate ( unitary , qubits = qubits , name = 'RAND{}' . format ( N ) )
r Returns a random unitary gate on K qubits .
40,894
def has_function ( function_name , libraries = None ) : compiler = distutils . ccompiler . new_compiler ( ) with muted ( sys . stdout , sys . stderr ) : result = compiler . has_function ( function_name , libraries = libraries ) if os . path . exists ( 'a.out' ) : os . remove ( 'a.out' ) return result
Checks if a given functions exists in the current platform .
40,895
async def handle_agent_message ( self , agent_addr , message ) : message_handlers = { AgentHello : self . handle_agent_hello , AgentJobStarted : self . handle_agent_job_started , AgentJobDone : self . handle_agent_job_done , AgentJobSSHDebug : self . handle_agent_job_ssh_debug , Pong : self . _handle_pong } try : func = message_handlers [ message . __class__ ] except : raise TypeError ( "Unknown message type %s" % message . __class__ ) self . _create_safe_task ( func ( agent_addr , message ) )
Dispatch messages received from agents to the right handlers
40,896
async def handle_client_hello ( self , client_addr , _ : ClientHello ) : self . _logger . info ( "New client connected %s" , client_addr ) self . _registered_clients . add ( client_addr ) await self . send_container_update_to_client ( [ client_addr ] )
Handle an ClientHello message . Send available containers to the client
40,897
async def handle_client_ping ( self , client_addr , _ : Ping ) : await ZMQUtils . send_with_addr ( self . _client_socket , client_addr , Pong ( ) )
Handle an Ping message . Pong the client
40,898
async def handle_client_new_job ( self , client_addr , message : ClientNewJob ) : self . _logger . info ( "Adding a new job %s %s to the queue" , client_addr , message . job_id ) self . _waiting_jobs [ ( client_addr , message . job_id ) ] = message await self . update_queue ( )
Handle an ClientNewJob message . Add a job to the queue and triggers an update
40,899
async def handle_client_kill_job ( self , client_addr , message : ClientKillJob ) : if ( client_addr , message . job_id ) in self . _waiting_jobs : del self . _waiting_jobs [ ( client_addr , message . job_id ) ] await ZMQUtils . send_with_addr ( self . _client_socket , client_addr , BackendJobDone ( message . job_id , ( "killed" , "You killed the job" ) , 0.0 , { } , { } , { } , "" , None , "" , "" ) ) elif ( client_addr , message . job_id ) in self . _job_running : agent_addr = self . _job_running [ ( client_addr , message . job_id ) ] [ 0 ] await ZMQUtils . send_with_addr ( self . _agent_socket , agent_addr , BackendKillJob ( ( client_addr , message . job_id ) ) ) else : self . _logger . warning ( "Client %s attempted to kill unknown job %s" , str ( client_addr ) , str ( message . job_id ) )
Handle an ClientKillJob message . Remove a job from the waiting list or send the kill message to the right agent .