idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
228,700
def rectify_ajax_form_data ( self , data ) : for name , field in self . base_fields . items ( ) : try : data [ name ] = field . convert_ajax_data ( data . get ( name , { } ) ) except AttributeError : pass return data
If a widget was converted and the Form data was submitted through an Ajax request then these data fields must be converted to suit the Django Form validation
65
28
228,701
def djng_locale_script ( context , default_language = 'en' ) : language = get_language_from_request ( context [ 'request' ] ) if not language : language = default_language return format_html ( 'angular-locale_{}.js' , language . lower ( ) )
Returns a script tag for including the proper locale script in any HTML page . This tag determines the current language with its locale .
67
25
228,702
def update_widget_attrs ( self , bound_field , attrs ) : bound_field . form . update_widget_attrs ( bound_field , attrs ) widget_classes = self . widget . attrs . get ( 'class' , None ) if widget_classes : if 'class' in attrs : attrs [ 'class' ] += ' ' + widget_classes else : attrs . update ( { 'class' : widget_classes } ) return attrs
Update the dictionary of attributes used while rendering the input widget
104
11
228,703
def implode_multi_values ( self , name , data ) : mkeys = [ k for k in data . keys ( ) if k . startswith ( name + '.' ) ] mvls = [ data . pop ( k ) [ 0 ] for k in mkeys ] if mvls : data . setlist ( name , mvls )
Due to the way Angular organizes it model when Form data is sent via a POST request then for this kind of widget the posted data must to be converted into a format suitable for Django s Form validation .
77
41
228,704
def convert_ajax_data ( self , field_data ) : data = [ key for key , val in field_data . items ( ) if val ] return data
Due to the way Angular organizes it model when this Form data is sent using Ajax then for this kind of widget the sent data has to be converted into a format suitable for Django s Form validation .
36
40
228,705
def process_request ( self , request ) : if request . path == self . ANGULAR_REVERSE : url_name = request . GET . get ( 'djng_url_name' ) url_args = request . GET . getlist ( 'djng_url_args' , [ ] ) url_kwargs = { } # Remove falsy values (empty strings) url_args = filter ( lambda x : x , url_args ) # Read kwargs for param in request . GET : if param . startswith ( 'djng_url_kwarg_' ) : # Ignore kwargs that are empty strings if request . GET [ param ] : url_kwargs [ param [ 15 : ] ] = request . GET [ param ] # [15:] to remove 'djng_url_kwarg' prefix url = unquote ( reverse ( url_name , args = url_args , kwargs = url_kwargs ) ) assert not url . startswith ( self . ANGULAR_REVERSE ) , "Prevent recursive requests" # rebuild the request object with a different environ request . path = request . path_info = url request . environ [ 'PATH_INFO' ] = url query = request . GET . copy ( ) for key in request . GET : if key . startswith ( 'djng_url' ) : query . pop ( key , None ) if six . PY3 : request . environ [ 'QUERY_STRING' ] = query . urlencode ( ) else : request . environ [ 'QUERY_STRING' ] = query . urlencode ( ) . encode ( 'utf-8' ) # Reconstruct GET QueryList in the same way WSGIRequest.GET function works request . GET = http . QueryDict ( request . environ [ 'QUERY_STRING' ] )
Reads url name args kwargs from GET parameters reverses the url and resolves view function Returns the result of resolved view function called with provided args and kwargs Since the view function is called directly it isn t ran through middlewares so the middlewares must be added manually The final result is exactly the same as if the request was for the resolved view .
404
75
228,706
def ng_delete ( self , request , * args , * * kwargs ) : if 'pk' not in request . GET : raise NgMissingParameterError ( "Object id is required to delete." ) obj = self . get_object ( ) response = self . build_json_response ( obj ) obj . delete ( ) return response
Delete object and return it s data in JSON encoding The response is build before the object is actually deleted so that we can still retrieve a serialization in the response even with a m2m relationship
73
39
228,707
def _post_clean ( self ) : super ( NgModelFormMixin , self ) . _post_clean ( ) if self . _errors and self . prefix : self . _errors = ErrorDict ( ( self . add_prefix ( name ) , value ) for name , value in self . _errors . items ( ) )
Rewrite the error dictionary so that its keys correspond to the model fields .
71
15
228,708
def percentage ( self ) : if self . max_value is None or self . max_value is base . UnknownLength : return None elif self . max_value : todo = self . value - self . min_value total = self . max_value - self . min_value percentage = todo / total else : percentage = 1 return percentage * 100
Return current percentage returns None if no max_value is given
76
12
228,709
def example ( fn ) : @ functools . wraps ( fn ) def wrapped ( ) : try : sys . stdout . write ( 'Running: %s\n' % fn . __name__ ) fn ( ) sys . stdout . write ( '\n' ) except KeyboardInterrupt : sys . stdout . write ( '\nSkipping example.\n\n' ) # Sleep a bit to make killing the script easier time . sleep ( 0.2 ) examples . append ( wrapped ) return wrapped
Wrap the examples so they generate readable output
111
9
228,710
def load_stdgraphs ( size : int ) -> List [ nx . Graph ] : from pkg_resources import resource_stream if size < 6 or size > 32 : raise ValueError ( 'Size out of range.' ) filename = 'datasets/data/graph{}er100.g6' . format ( size ) fdata = resource_stream ( 'quantumflow' , filename ) return nx . read_graph6 ( fdata )
Load standard graph validation sets
99
5
228,711
def load_mnist ( size : int = None , border : int = _MNIST_BORDER , blank_corners : bool = False , nums : List [ int ] = None ) -> Tuple [ np . ndarray , np . ndarray , np . ndarray , np . ndarray ] : # DOCME: Fix up formatting above, # DOCME: Explain nums argument # JIT import since keras startup is slow from keras . datasets import mnist def _filter_mnist ( x : np . ndarray , y : np . ndarray , nums : List [ int ] = None ) -> Tuple [ np . ndarray , np . ndarray ] : xt = [ ] yt = [ ] items = len ( y ) for n in range ( items ) : if nums is not None and y [ n ] in nums : xt . append ( x [ n ] ) yt . append ( y [ n ] ) xt = np . stack ( xt ) yt = np . stack ( yt ) return xt , yt def _rescale ( imgarray : np . ndarray , size : int ) -> np . ndarray : N = imgarray . shape [ 0 ] # Chop off border imgarray = imgarray [ : , border : - border , border : - border ] rescaled = np . zeros ( shape = ( N , size , size ) , dtype = np . float ) for n in range ( 0 , N ) : img = Image . fromarray ( imgarray [ n ] ) img = img . resize ( ( size , size ) , Image . LANCZOS ) rsc = np . asarray ( img ) . reshape ( ( size , size ) ) rsc = 256. * rsc / rsc . max ( ) rescaled [ n ] = rsc return rescaled . astype ( dtype = np . uint8 ) def _blank_corners ( imgarray : np . ndarray ) -> None : # Zero out corners sz = imgarray . shape [ 1 ] corner = ( sz // 2 ) - 1 for x in range ( 0 , corner ) : for y in range ( 0 , corner - x ) : imgarray [ : , x , y ] = 0 imgarray [ : , - ( 1 + x ) , y ] = 0 imgarray [ : , - ( 1 + x ) , - ( 1 + y ) ] = 0 imgarray [ : , x , - ( 1 + y ) ] = 0 ( x_train , y_train ) , ( x_test , y_test ) = mnist . load_data ( ) if nums : x_train , y_train = _filter_mnist ( x_train , y_train , nums ) x_test , y_test = _filter_mnist ( x_test , y_test , nums ) if size : x_train = _rescale ( x_train , size ) x_test = _rescale ( x_test , size ) if blank_corners : _blank_corners ( x_train ) _blank_corners ( x_test ) return x_train , y_train , x_test , y_test
Download and rescale the MNIST database of handwritten digits
720
11
228,712
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
Covert numpy array to tensorflow tensor
40
11
228,713
def inner ( tensor0 : BKTensor , tensor1 : BKTensor ) -> BKTensor : # Note: Relying on fact that vdot flattens arrays N = rank ( tensor0 ) axes = list ( range ( N ) ) return tf . tensordot ( tf . math . conj ( tensor0 ) , tensor1 , axes = ( axes , axes ) )
Return the inner product between two states
84
7
228,714
def graph_cuts ( graph : nx . Graph ) -> np . ndarray : N = len ( graph ) diag_hamiltonian = np . zeros ( shape = ( [ 2 ] * N ) , dtype = np . double ) for q0 , q1 in graph . edges ( ) : for index , _ in np . ndenumerate ( diag_hamiltonian ) : if index [ q0 ] != index [ q1 ] : weight = graph [ q0 ] [ q1 ] . get ( 'weight' , 1 ) diag_hamiltonian [ index ] += weight return diag_hamiltonian
For the given graph return the cut value for all binary assignments of the graph .
138
16
228,715
def depth ( self , local : bool = True ) -> int : G = self . graph if not local : def remove_local ( dagc : DAGCircuit ) -> Generator [ Operation , None , None ] : for elem in dagc : if dagc . graph . degree [ elem ] > 2 : yield elem G = DAGCircuit ( remove_local ( self ) ) . graph return nx . dag_longest_path_length ( G ) - 1
Return the circuit depth .
103
5
228,716
def components ( self ) -> List [ 'DAGCircuit' ] : comps = nx . weakly_connected_component_subgraphs ( self . graph ) return [ DAGCircuit ( comp ) for comp in comps ]
Split DAGCircuit into independent components
52
8
228,717
def zero_state ( qubits : Union [ int , Qubits ] ) -> State : N , qubits = qubits_count_tuple ( qubits ) ket = np . zeros ( shape = [ 2 ] * N ) ket [ ( 0 , ) * N ] = 1 return State ( ket , qubits )
Return the all - zero state on N qubits
70
10
228,718
def w_state ( qubits : Union [ int , Qubits ] ) -> State : N , qubits = qubits_count_tuple ( qubits ) ket = np . zeros ( shape = [ 2 ] * N ) for n in range ( N ) : idx = np . zeros ( shape = N , dtype = int ) idx [ n ] += 1 ket [ tuple ( idx ) ] = 1 / sqrt ( N ) return State ( ket , qubits )
Return a W state on N qubits
107
8
228,719
def ghz_state ( qubits : Union [ int , Qubits ] ) -> State : N , qubits = qubits_count_tuple ( qubits ) ket = np . zeros ( shape = [ 2 ] * N ) ket [ ( 0 , ) * N ] = 1 / sqrt ( 2 ) ket [ ( 1 , ) * N ] = 1 / sqrt ( 2 ) return State ( ket , qubits )
Return a GHZ state on N qubits
94
9
228,720
def random_state ( qubits : Union [ int , Qubits ] ) -> State : N , qubits = qubits_count_tuple ( qubits ) ket = np . random . normal ( size = ( [ 2 ] * N ) ) + 1j * np . random . normal ( size = ( [ 2 ] * N ) ) return State ( ket , qubits ) . normalize ( )
Return a random state from the space of N qubits
87
11
228,721
def join_states ( * states : State ) -> State : vectors = [ ket . vec for ket in states ] vec = reduce ( outer_product , vectors ) return State ( vec . tensor , vec . qubits )
Join two state vectors into a larger qubit state
47
10
228,722
def print_state ( state : State , file : TextIO = None ) -> None : state = state . vec . asarray ( ) for index , amplitude in np . ndenumerate ( state ) : ket = "" . join ( [ str ( n ) for n in index ] ) print ( ket , ":" , amplitude , file = file )
Print a state vector
74
4
228,723
def print_probabilities ( state : State , ndigits : int = 4 , file : TextIO = None ) -> None : prob = bk . evaluate ( state . probabilities ( ) ) for index , prob in np . ndenumerate ( prob ) : prob = round ( prob , ndigits ) if prob == 0.0 : continue ket = "" . join ( [ str ( n ) for n in index ] ) print ( ket , ":" , prob , file = file )
Pretty print state probabilities .
105
5
228,724
def mixed_density ( qubits : Union [ int , Qubits ] ) -> Density : N , qubits = qubits_count_tuple ( qubits ) matrix = np . eye ( 2 ** N ) / 2 ** N return Density ( matrix , qubits )
Returns the completely mixed density matrix
60
6
228,725
def join_densities ( * densities : Density ) -> Density : vectors = [ rho . vec for rho in densities ] vec = reduce ( outer_product , vectors ) memory = dict ( ChainMap ( * [ rho . memory for rho in densities ] ) ) # TESTME return Density ( vec . tensor , vec . qubits , memory )
Join two mixed states into a larger qubit state
83
10
228,726
def normalize ( self ) -> 'State' : tensor = self . tensor / bk . ccast ( bk . sqrt ( self . norm ( ) ) ) return State ( tensor , self . qubits , self . _memory )
Normalize the state
54
4
228,727
def sample ( self , trials : int ) -> np . ndarray : # TODO: Can we do this within backend? probs = np . real ( bk . evaluate ( self . probabilities ( ) ) ) res = np . random . multinomial ( trials , probs . ravel ( ) ) res = res . reshape ( probs . shape ) return res
Measure the state in the computational basis the the given number of trials and return the counts of each output configuration .
80
22
228,728
def expectation ( self , diag_hermitian : bk . TensorLike , trials : int = None ) -> bk . BKTensor : if trials is None : probs = self . probabilities ( ) else : probs = bk . real ( bk . astensorproduct ( self . sample ( trials ) / trials ) ) diag_hermitian = bk . astensorproduct ( diag_hermitian ) return bk . sum ( bk . real ( diag_hermitian ) * probs )
Return the expectation of a measurement . Since we can only measure our computer in the computational basis we only require the diagonal of the Hermitian in that basis .
116
32
228,729
def measure ( self ) -> np . ndarray : # TODO: Can we do this within backend? probs = np . real ( bk . evaluate ( self . probabilities ( ) ) ) indices = np . asarray ( list ( np . ndindex ( * [ 2 ] * self . qubit_nb ) ) ) res = np . random . choice ( probs . size , p = probs . ravel ( ) ) res = indices [ res ] return res
Measure the state in the computational basis .
102
8
228,730
def asdensity ( self ) -> 'Density' : matrix = bk . outer ( self . tensor , bk . conj ( self . tensor ) ) return Density ( matrix , self . qubits , self . _memory )
Convert a pure state to a density matrix
51
9
228,731
def benchmark ( N , gates ) : qubits = list ( range ( 0 , N ) ) ket = qf . zero_state ( N ) for n in range ( 0 , N ) : ket = qf . H ( n ) . run ( ket ) for _ in range ( 0 , ( gates - N ) // 3 ) : qubit0 , qubit1 = random . sample ( qubits , 2 ) ket = qf . X ( qubit0 ) . run ( ket ) ket = qf . T ( qubit1 ) . run ( ket ) ket = qf . CNOT ( qubit0 , qubit1 ) . run ( ket ) return ket . vec . tensor
Create and run a circuit with N qubits and given number of gates
148
14
228,732
def sandwich_decompositions ( coords0 , coords1 , samples = SAMPLES ) : decomps = [ ] for _ in range ( samples ) : circ = qf . Circuit ( ) circ += qf . CANONICAL ( * coords0 , 0 , 1 ) circ += qf . random_gate ( [ 0 ] ) circ += qf . random_gate ( [ 1 ] ) circ += qf . CANONICAL ( * coords1 , 0 , 1 ) gate = circ . asgate ( ) coords = qf . canonical_coords ( gate ) decomps . append ( coords ) return decomps
Create composite gates decompose and return a list of canonical coordinates
138
12
228,733
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
39
15
228,734
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
39
15
228,735
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
39
15
228,736
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
104
10
228,737
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 ] # Operator: X Y Z 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
210
10
228,738
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 # https://en.wikipedia.org/wiki/Exponentiation_by_squaring y = Pauli . identity ( ) x = pauli n = exponent while n > 1 : if n % 2 == 0 : # Even x = x * x n = n // 2 else : # Odd 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 .
160
17
228,739
def pauli_commuting_sets ( element : Pauli ) -> Tuple [ Pauli , ... ] : if len ( element ) < 2 : return ( element , ) groups : List [ Pauli ] = [ ] # typing: 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 .
132
15
228,740
def astensor ( array : TensorLike ) -> BKTensor : array = np . asarray ( array , dtype = CTYPE ) return array
Converts a numpy array to the backend s tensor object
32
13
228,741
def productdiag ( tensor : BKTensor ) -> BKTensor : # DOCME: Explain 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
89
9
228,742
def tensormul ( tensor0 : BKTensor , tensor1 : BKTensor , indices : typing . List [ int ] ) -> BKTensor : # Note: This method is the critical computational core of QuantumFlow # We currently have two implementations, one that uses einsum, the other # using matrix multiplication # # numpy: # einsum is much faster particularly for small numbers of qubits # tensorflow: # Little different is performance, but einsum would restrict the # maximum number of qubits to 26 (Because tensorflow only allows 26 # einsum subscripts at present] # torch: # einsum is slower than matmul 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 ) # print('>>>', K, N, subscripts) tensor = einsum ( subscripts , tensor0 , tensor1 ) return tensor
r Generalization of matrix multiplication to product tensors .
327
11
228,743
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 .
90
25
228,744
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 .
41
10
228,745
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 .
73
11
228,746
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 .
82
19
228,747
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 .
84
16
228,748
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 .
66
12
228,749
def pyquil_to_image ( program : pyquil . Program ) -> PIL . Image : # pragma: no cover circ = pyquil_to_circuit ( program ) latex = circuit_to_latex ( circ ) img = render_latex ( latex ) return img
Returns an image of a pyquil circuit .
64
10
228,750
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 : # FIXME: more informative error message raise ValueError ( 'Cannot convert operation to pyquil' ) return prog
Convert a QuantumFlow circuit to a pyQuil program
150
12
228,751
def pyquil_to_circuit ( program : pyquil . Program ) -> Circuit : circ = Circuit ( ) for inst in program . instructions : # print(type(inst)) if isinstance ( inst , pyquil . Declare ) : # Ignore continue if isinstance ( inst , pyquil . Halt ) : # Ignore continue if isinstance ( inst , pyquil . Pragma ) : # TODO Barrier? continue elif isinstance ( inst , pyquil . Measurement ) : circ += Measure ( inst . qubit . index ) # elif isinstance(inst, pyquil.ResetQubit): # TODO # continue 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
227
15
228,752
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
52
11
228,753
def state_to_wavefunction ( state : State ) -> pyquil . Wavefunction : # TODO: qubits? amplitudes = state . vec . asarray ( ) # pyQuil labels states backwards. amplitudes = amplitudes . transpose ( ) amplitudes = amplitudes . reshape ( [ amplitudes . size ] ) return pyquil . Wavefunction ( amplitudes )
Convert a QuantumFlow state to a pyQuil Wavefunction
83
13
228,754
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 .
71
15
228,755
def run ( self ) -> 'QuantumFlowQVM' : assert self . status in [ 'loaded' ] self . status = 'running' self . _ket = self . _prog . run ( ) # Should set state to 'done' after run complete. # Makes no sense to keep status at running. But pyQuil's # QuantumComputer calls wait() after run, which expects state to be # 'running', and whose only effect to is to set state to 'done' return self
Run a previously loaded program
105
5
228,756
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 .
48
9
228,757
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
130
7
228,758
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
48
9
228,759
def state_fidelity ( state0 : State , state1 : State ) -> bk . BKTensor : assert state0 . qubits == state1 . qubits # FIXME tensor = bk . absolute ( bk . inner ( state0 . tensor , state1 . tensor ) ) ** bk . fcast ( 2 ) return tensor
Return the quantum fidelity between pure states .
77
8
228,760
def state_angle ( ket0 : State , ket1 : State ) -> bk . BKTensor : return fubini_study_angle ( ket0 . vec , ket1 . vec )
The Fubini - Study angle between states .
42
10
228,761
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 .
44
8
228,762
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 .
73
11
228,763
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
108
9
228,764
def bures_angle ( rho0 : Density , rho1 : Density ) -> float : return np . arccos ( np . sqrt ( fidelity ( rho0 , rho1 ) ) )
Return the Bures angle between mixed quantum states
47
9
228,765
def density_angle ( rho0 : Density , rho1 : Density ) -> bk . BKTensor : return fubini_study_angle ( rho0 . vec , rho1 . vec )
The Fubini - Study angle between density matrices
48
11
228,766
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 .
51
9
228,767
def entropy ( rho : Density , base : float = None ) -> float : op = asarray ( rho . asoperator ( ) ) probs = np . linalg . eigvalsh ( op ) probs = np . maximum ( probs , 0.0 ) # Compensate for floating point errors return scipy . stats . entropy ( probs , base = base )
Returns the von - Neumann entropy of a mixed quantum state .
85
13
228,768
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 .
136
18
228,769
def gate_angle ( gate0 : Gate , gate1 : Gate ) -> bk . BKTensor : return fubini_study_angle ( gate0 . vec , gate1 . vec )
The Fubini - Study angle between gates
42
9
228,770
def channel_angle ( chan0 : Channel , chan1 : Channel ) -> bk . BKTensor : return fubini_study_angle ( chan0 . vec , chan1 . vec )
The Fubini - Study angle between channels
46
9
228,771
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 ) # Make sure qubits in same order return bk . inner ( vec0 . tensor , vec1 . tensor )
Hilbert - Schmidt inner product between qubit vectors
117
11
228,772
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 ) # Interleave (super)-operator axes # R = 1 perm = (0, 1) # R = 2 perm = (0, 2, 1, 3) # R = 4 perm = (0, 4, 1, 5, 2, 6, 3, 7) 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
312
6
228,773
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 .
109
13
228,774
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
47
9
228,775
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
57
10
228,776
def H ( self ) -> 'QubitVector' : N = self . qubit_nb R = self . rank # (super) operator transpose 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 .
123
12
228,777
def norm ( self ) -> bk . BKTensor : return bk . absolute ( bk . inner ( self . tensor , self . tensor ) )
Return the norm of this vector
35
6
228,778
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 ) # Only numpy's einsum works with repeated subscripts tensor = self . asarray ( ) tensor = np . einsum ( subscript_str , tensor ) return QubitVector ( tensor , new_qubits )
Return the partial trace over some subset of qubits
248
10
228,779
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 ( ) : """Loss""" 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 .
225
31
228,780
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 .
101
29
228,781
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
10
228,782
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
74
9
228,783
def evolve ( self , rho : Density ) -> Density : # TODO: implement without explicit channel creation? chan = self . aschannel ( ) return chan . evolve ( rho )
Apply the action of this gate upon a density
43
9
228,784
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
95
7
228,785
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 .
67
12
228,786
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
44
10
228,787
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
46
12
228,788
def sharp ( self ) -> 'Channel' : 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 .
98
11
228,789
def choi ( self ) -> bk . BKTensor : # Put superop axes in [ok, ib, ob, ik] and reshape to matrix N = self . qubit_nb return bk . reshape ( self . sharp . tensor , [ 2 ** ( N * 2 ) ] * 2 )
Return the Choi matrix representation of this super operator
69
9
228,790
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
113
9
228,791
def fcast ( value : float ) -> TensorLike : newvalue = tf . cast ( value , FTYPE ) if DEVICE == 'gpu' : newvalue = newvalue . gpu ( ) # Why is this needed? # pragma: no cover return newvalue
Cast to float tensor
58
5
228,792
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( array , dtype = CTYPE ) if DEVICE == 'gpu' : tensor = tensor . gpu ( ) # pragma: no cover # size = np.prod(np.array(tensor.get_shape().as_list())) N = int ( math . log2 ( size ( tensor ) ) ) tensor = tf . reshape ( tensor , ( [ 2 ] * N ) ) return tensor
Convert to product tensor
121
6
228,793
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
71
24
228,794
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 .
44
14
228,795
def qft_circuit ( qubits : Qubits ) -> Circuit : # Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py 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
141
7
228,796
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
61
7
228,797
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
71
12
228,798
def phase_estimation_circuit ( gate : Gate , outputs : Qubits ) -> Circuit : circ = Circuit ( ) circ += map_gate ( H ( ) , list ( zip ( outputs ) ) ) # Hadamard on all output qubits 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 .
98
8
228,799
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 .
72
17