idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
11,400 | def _copy ( self , other , copy_func ) : super ( OctetString , self ) . _copy ( other , copy_func ) self . _bytes = other . _bytes | Copies the contents of another OctetString object to itself |
11,401 | def _copy ( self , other , copy_func ) : super ( ParsableOctetString , self ) . _copy ( other , copy_func ) self . _bytes = other . _bytes self . _parsed = copy_func ( other . _parsed ) | Copies the contents of another ParsableOctetString object to itself |
11,402 | def _lazy_child ( self , index ) : child = self . children [ index ] if child . __class__ == tuple : child = self . children [ index ] = _build ( * child ) return child | Builds a child object if the child has only been parsed into a tuple so far |
11,403 | def _set_contents ( self , force = False ) : if self . children is None : self . _parse_children ( ) contents = BytesIO ( ) for index , info in enumerate ( self . _fields ) : child = self . children [ index ] if child is None : child_dump = b'' elif child . __class__ == tuple : if force : child_dump = self . _lazy_chil... | Updates the . contents attribute of the value with the encoded value of all of the child objects |
11,404 | def _setup ( self ) : cls = self . __class__ cls . _field_map = { } cls . _field_ids = [ ] cls . _precomputed_specs = [ ] for index , field in enumerate ( cls . _fields ) : if len ( field ) < 3 : field = field + ( { } , ) cls . _fields [ index ] = field cls . _field_map [ field [ 0 ] ] = index cls . _field_ids . append... | Generates _field_map _field_ids and _oid_nums for use in parsing |
11,405 | def _determine_spec ( self , index ) : name , field_spec , field_params = self . _fields [ index ] value_spec = field_spec spec_override = None if self . _spec_callbacks is not None and name in self . _spec_callbacks : callback = self . _spec_callbacks [ name ] spec_override = callback ( self ) if spec_override : if sp... | Determine how a value for a field should be constructed |
11,406 | def _copy ( self , other , copy_func ) : super ( Sequence , self ) . _copy ( other , copy_func ) if self . children is not None : self . children = [ ] for child in other . children : if child . __class__ == tuple : self . children . append ( child ) else : self . children . append ( child . copy ( ) ) | Copies the contents of another Sequence object to itself |
11,407 | def append ( self , value ) : if self . children is None : self . _parse_children ( ) self . children . append ( self . _make_value ( value ) ) if self . _native is not None : self . _native . append ( self . children [ - 1 ] . native ) self . _mutated = True | Allows adding a child to the end of the sequence |
11,408 | def _set_contents ( self , force = False ) : if self . children is None : self . _parse_children ( ) contents = BytesIO ( ) for child in self : contents . write ( child . dump ( force = force ) ) self . _contents = contents . getvalue ( ) self . _header = None if self . _trailer != b'' : self . _trailer = b'' | Encodes all child objects into the contents for this object |
11,409 | def _parse_children ( self , recurse = False ) : try : self . children = [ ] if self . _contents is None : return contents_length = len ( self . _contents ) child_pointer = 0 while child_pointer < contents_length : parts , child_pointer = _parse ( self . _contents , contents_length , pointer = child_pointer ) if self .... | Parses the contents and generates Asn1Value objects based on the definitions from _child_spec . |
11,410 | def type_name ( value ) : if inspect . isclass ( value ) : cls = value else : cls = value . __class__ if cls . __module__ in set ( [ 'builtins' , '__builtin__' ] ) : return cls . __name__ return '%s.%s' % ( cls . __module__ , cls . __name__ ) | Returns a user - readable name for the type of an object |
11,411 | def emit ( class_ , method , tag , contents ) : if not isinstance ( class_ , int ) : raise TypeError ( 'class_ must be an integer, not %s' % type_name ( class_ ) ) if class_ < 0 or class_ > 3 : raise ValueError ( 'class_ must be one of 0, 1, 2 or 3, not %s' % class_ ) if not isinstance ( method , int ) : raise TypeErro... | Constructs a byte string of an ASN . 1 DER - encoded value |
11,412 | def _parse ( encoded_data , data_len , pointer = 0 , lengths_only = False ) : if data_len < pointer + 2 : raise ValueError ( _INSUFFICIENT_DATA_MESSAGE % ( 2 , data_len - pointer ) ) start = pointer first_octet = ord ( encoded_data [ pointer ] ) if _PY2 else encoded_data [ pointer ] pointer += 1 tag = first_octet & 31 ... | Parses a byte string into component parts |
11,413 | def _dump_header ( class_ , method , tag , contents ) : header = b'' id_num = 0 id_num |= class_ << 6 id_num |= method << 5 if tag >= 31 : header += chr_cls ( id_num | 31 ) while tag > 0 : continuation_bit = 0x80 if tag > 0x7F else 0 header += chr_cls ( continuation_bit | ( tag & 0x7F ) ) tag = tag >> 7 else : header +... | Constructs the header bytes for an ASN . 1 object |
11,414 | def _iri_utf8_errors_handler ( exc ) : bytes_as_ints = bytes_to_list ( exc . object [ exc . start : exc . end ] ) replacements = [ '%%%02x' % num for num in bytes_as_ints ] return ( '' . join ( replacements ) , exc . end ) | Error handler for decoding UTF - 8 parts of a URI into an IRI . Leaves byte sequences encoded in %XX format but as part of a unicode string . |
11,415 | def _urlquote ( string , safe = '' ) : if string is None or string == '' : return None escapes = [ ] if re . search ( '%[0-9a-fA-F]{2}' , string ) : def _try_unescape ( match ) : byte_string = unquote_to_bytes ( match . group ( 0 ) ) unicode_string = byte_string . decode ( 'utf-8' , 'iriutf8' ) for safe_char in list ( ... | Quotes a unicode string for use in a URL |
11,416 | def _urlunquote ( byte_string , remap = None , preserve = None ) : if byte_string is None : return byte_string if byte_string == b'' : return '' if preserve : replacements = [ '\x1A' , '\x1C' , '\x1D' , '\x1E' , '\x1F' ] preserve_unmap = { } for char in remap : replacement = replacements . pop ( 0 ) preserve_unmap [ re... | Unquotes a URI portion from a byte string into unicode using UTF - 8 |
11,417 | def init_args ( ) : parser = argparse . ArgumentParser ( description = 'draw basic graphs on terminal' ) parser . add_argument ( 'filename' , nargs = '?' , default = "-" , help = 'data file name (comma or space separated). Defaults to stdin.' ) parser . add_argument ( '--title' , help = 'Title of graph' ) parser . add_... | Parse and return the arguments . |
11,418 | def find_max_label_length ( labels ) : length = 0 for i in range ( len ( labels ) ) : if len ( labels [ i ] ) > length : length = len ( labels [ i ] ) return length | Return the maximum length for the labels . |
11,419 | def normalize ( data , width ) : min_dat = find_min ( data ) off_data = [ ] if min_dat < 0 : min_dat = abs ( min_dat ) for dat in data : off_data . append ( [ _d + min_dat for _d in dat ] ) else : off_data = data min_dat = find_min ( off_data ) max_dat = find_max ( off_data ) if max_dat < width : return off_data norm_f... | Normalize the data and return it . |
11,420 | def horiz_rows ( labels , data , normal_dat , args , colors ) : val_min = find_min ( data ) for i in range ( len ( labels ) ) : if args [ 'no_labels' ] : label = '' else : label = "{:<{x}}: " . format ( labels [ i ] , x = find_max_label_length ( labels ) ) values = data [ i ] num_blocks = normal_dat [ i ] for j in rang... | Prepare the horizontal graph . Each row is printed through the print_row function . |
11,421 | def print_row ( value , num_blocks , val_min , color ) : if color : sys . stdout . write ( f'\033[{color}m' ) if num_blocks < 1 and ( value > val_min or value > 0 ) : sys . stdout . write ( SM_TICK ) else : for _ in range ( num_blocks ) : sys . stdout . write ( TICK ) if color : sys . stdout . write ( '\033[0m' ) | A method to print a row for a horizontal graphs . |
11,422 | def stacked_graph ( labels , data , normal_data , len_categories , args , colors ) : val_min = find_min ( data ) for i in range ( len ( labels ) ) : if args [ 'no_labels' ] : label = '' else : label = "{:<{x}}: " . format ( labels [ i ] , x = find_max_label_length ( labels ) ) print ( label , end = "" ) values = data [... | Prepare the horizontal stacked graph . Each row is printed through the print_row function . |
11,423 | def vertically ( value , num_blocks , val_min , color , args ) : global maxi , value_list value_list . append ( str ( value ) ) if maxi < num_blocks : maxi = num_blocks if num_blocks > 0 : vertical_list . append ( ( TICK * num_blocks ) ) else : vertical_list . append ( SM_TICK ) for row in zip_longest ( * vertical_list... | Prepare the vertical graph . The whole graph is printed through the print_vertical function . |
11,424 | def print_vertical ( vertical_rows , labels , color , args ) : if color : sys . stdout . write ( f'\033[{color}m' ) for row in vertical_rows : print ( * row ) sys . stdout . write ( '\033[0m' ) print ( "-" * len ( row ) + "Values" + "-" * len ( row ) ) for value in zip_longest ( * value_list , fillvalue = ' ' ) : print... | Print the whole vertical graph . |
11,425 | def chart ( colors , data , args , labels ) : len_categories = len ( data [ 0 ] ) if len_categories > 1 : if args [ 'stacked' ] : normal_dat = normalize ( data , args [ 'width' ] ) stacked_graph ( labels , data , normal_dat , len_categories , args , colors ) return if not colors : colors = [ None ] * len_categories if ... | Handle the normalization of data and the printing of the graph . |
11,426 | def check_data ( labels , data , args ) : len_categories = len ( data [ 0 ] ) if len ( labels ) != len ( data ) : print ( ">> Error: Label and data array sizes don't match" ) sys . exit ( 1 ) for dat in data : if len ( dat ) != len_categories : print ( ">> Error: There are missing values" ) sys . exit ( 1 ) colors = [ ... | Check that all data were inserted correctly . Return the colors . |
11,427 | def print_categories ( categories , colors ) : for i in range ( len ( categories ) ) : if colors : sys . stdout . write ( f'\033[{colors[i]}m' ) sys . stdout . write ( TICK + ' ' + categories [ i ] + ' ' ) if colors : sys . stdout . write ( '\033[0m' ) print ( '\n\n' ) | Print a tick and the category s name for each category above the graph . |
11,428 | def read_data ( args ) : filename = args [ 'filename' ] stdin = filename == '-' if args [ 'verbose' ] : print ( f'>> Reading data from {( "stdin" if stdin else filename )}' ) print ( '' ) if args [ 'title' ] : print ( '# ' + args [ 'title' ] + '\n' ) categories , labels , data , colors = ( [ ] for i in range ( 4 ) ) f ... | Read data from a file or stdin and returns it . |
11,429 | def calendar_heatmap ( data , labels , args ) : if args [ 'color' ] : colornum = AVAILABLE_COLORS . get ( args [ 'color' ] [ 0 ] ) else : colornum = AVAILABLE_COLORS . get ( 'blue' ) dt_dict = { } for i in range ( len ( labels ) ) : dt_dict [ labels [ i ] ] = data [ i ] [ 0 ] max_val = float ( max ( data ) [ 0 ] ) tick... | Print a calendar heatmap . |
11,430 | def _wrapper ( func , * args , ** kwargs ) : 'Decorator for the methods that follow' try : if func . __name__ == "init" : return func ( * args , ** kwargs ) or 0 else : try : return func ( * args , ** kwargs ) or 0 except OSError as e : if e . errno > 0 : log . debug ( "FUSE operation %s raised a %s, returning errno %s... | Decorator for the methods that follow |
11,431 | def lookup ( self , req , parent , name ) : self . reply_err ( req , errno . ENOENT ) | Look up a directory entry by name and get its attributes . |
11,432 | def getattr ( self , req , ino , fi ) : if ino == 1 : attr = { 'st_ino' : 1 , 'st_mode' : S_IFDIR | 0o755 , 'st_nlink' : 2 } self . reply_attr ( req , attr , 1.0 ) else : self . reply_err ( req , errno . ENOENT ) | Get file attributes |
11,433 | def setattr ( self , req , ino , attr , to_set , fi ) : self . reply_err ( req , errno . EROFS ) | Set file attributes |
11,434 | def mknod ( self , req , parent , name , mode , rdev ) : self . reply_err ( req , errno . EROFS ) | Create file node |
11,435 | def unlink ( self , req , parent , name ) : self . reply_err ( req , errno . EROFS ) | Remove a file |
11,436 | def rmdir ( self , req , parent , name ) : self . reply_err ( req , errno . EROFS ) | Remove a directory |
11,437 | def rename ( self , req , parent , name , newparent , newname ) : self . reply_err ( req , errno . EROFS ) | Rename a file |
11,438 | def link ( self , req , ino , newparent , newname ) : self . reply_err ( req , errno . EROFS ) | Create a hard link |
11,439 | def listxattr ( self , req , ino , size ) : self . reply_err ( req , errno . ENOSYS ) | List extended attribute names |
11,440 | def removexattr ( self , req , ino , name ) : self . reply_err ( req , errno . ENOSYS ) | Remove an extended attribute |
11,441 | def access ( self , req , ino , mask ) : self . reply_err ( req , errno . ENOSYS ) | Check file access permissions |
11,442 | def create ( self , req , parent , name , mode , fi ) : self . reply_err ( req , errno . ENOSYS ) | Create and open a file |
11,443 | def state_tomography_programs ( state_prep , qubits = None , rotation_generator = tomography . default_rotations ) : if qubits is None : qubits = state_prep . get_qubits ( ) for tomography_program in rotation_generator ( * qubits ) : state_tomography_program = Program ( Pragma ( "PRESERVE_BLOCK" ) ) state_tomography_pr... | Yield tomographic sequences that prepare a state with Quil program state_prep and then append tomographic rotations on the specified qubits . If qubits is None it assumes all qubits in the program should be tomographically rotated . |
11,444 | def do_state_tomography ( preparation_program , nsamples , cxn , qubits = None , use_run = False ) : return tomography . _do_tomography ( preparation_program , nsamples , cxn , qubits , tomography . MAX_QUBITS_STATE_TOMO , StateTomography , state_tomography_programs , DEFAULT_STATE_TOMO_SETTINGS , use_run = use_run ) | Method to perform both a QPU and QVM state tomography and use the latter as as reference to calculate the fidelity of the former . |
11,445 | def estimate_from_ssr ( histograms , readout_povm , channel_ops , settings ) : nqc = len ( channel_ops [ 0 ] . dims [ 0 ] ) pauli_basis = grove . tomography . operator_utils . PAULI_BASIS ** nqc pi_basis = readout_povm . pi_basis if not histograms . shape [ 1 ] == pi_basis . dim : raise ValueError ( "Currently tomograp... | Estimate a density matrix from single shot histograms obtained by measuring bitstrings in the Z - eigenbasis after application of given channel operators . |
11,446 | def plot_state_histogram ( self , ax ) : title = "Estimated state" nqc = int ( round ( np . log2 ( self . rho_est . data . shape [ 0 ] ) ) ) labels = ut . basis_labels ( nqc ) return ut . state_histogram ( self . rho_est , ax , title ) | Visualize the complex matrix elements of the estimated state . |
11,447 | def plot ( self ) : width = 10 height = width / 1.618 f = plt . figure ( figsize = ( width , height ) ) ax = f . add_subplot ( 111 , projection = "3d" ) self . plot_state_histogram ( ax ) return f | Visualize the state . |
11,448 | def is_constant ( self , qc : QuantumComputer , bitstring_map : Dict [ str , str ] ) -> bool : self . _init_attr ( bitstring_map ) prog = Program ( ) dj_ro = prog . declare ( 'ro' , 'BIT' , len ( self . computational_qubits ) ) prog += self . deutsch_jozsa_circuit prog += [ MEASURE ( qubit , ro ) for qubit , ro in zip ... | Computes whether bitstring_map represents a constant function given that it is constant or balanced . Constant means all inputs map to the same value balanced means half of the inputs maps to one value and half to the other . |
11,449 | def unitary_function ( mappings : Dict [ str , str ] ) -> np . ndarray : num_qubits = int ( np . log2 ( len ( mappings ) ) ) bitsum = sum ( [ int ( bit ) for bit in mappings . values ( ) ] ) if bitsum == 0 : return np . kron ( SWAP_MATRIX , np . identity ( 2 ** ( num_qubits - 1 ) ) ) elif bitsum == 2 ** ( num_qubits - ... | Creates a unitary transformation that maps each state to the values specified in mappings . |
11,450 | def basis_selector_oracle ( qubits : List [ int ] , bitstring : str ) -> Program : if len ( qubits ) != len ( bitstring ) : raise ValueError ( "The bitstring should be the same length as the number of qubits." ) oracle_prog = Program ( ) if len ( bitstring ) == 1 : oracle_prog . inst ( Z ( qubits [ 0 ] ) ) return oracl... | Defines an oracle that selects the ith element of the computational basis . |
11,451 | def make_diagonal_povm ( pi_basis , confusion_rate_matrix ) : confusion_rate_matrix = np . asarray ( confusion_rate_matrix ) if not np . allclose ( confusion_rate_matrix . sum ( axis = 0 ) , np . ones ( confusion_rate_matrix . shape [ 1 ] ) ) : raise CRMUnnormalizedError ( "Unnormalized confusion matrix:\n{}" . format ... | Create a DiagonalPOVM from a pi_basis and the confusion_rate_matrix associated with a readout . |
11,452 | def is_hermitian ( operator ) : if isinstance ( operator , qt . Qobj ) : return ( operator . dag ( ) - operator ) . norm ( FROBENIUS ) / operator . norm ( FROBENIUS ) < EPS if isinstance ( operator , np . ndarray ) : return np . linalg . norm ( operator . T . conj ( ) - operator ) / np . linalg . norm ( operator ) < EP... | Check if matrix or operator is hermitian . |
11,453 | def is_projector ( operator ) : return ( is_hermitian ( operator ) and ( operator * operator - operator ) . norm ( FROBENIUS ) / operator . norm ( FROBENIUS ) < EPS ) | Check if operator is a projector . |
11,454 | def choi_matrix ( pauli_tm , basis ) : if not basis . is_orthonormal ( ) : raise ValueError ( "Need an orthonormal operator basis." ) if not all ( ( is_hermitian ( op ) for op in basis . ops ) ) : raise ValueError ( "Need an operator basis of hermitian operators." ) sbasis = basis . super_basis ( ) D = basis . dim choi... | Compute the Choi matrix for a quantum process from its Pauli Transfer Matrix . |
11,455 | def metric ( self ) : if self . _metric is None : _log . debug ( "Computing and caching operator basis metric" ) self . _metric = np . matrix ( [ [ ( j . dag ( ) * k ) . tr ( ) for k in self . ops ] for j in self . ops ] ) return self . _metric | Compute a matrix of Hilbert - Schmidt inner products for the basis operators update self . _metric and return the value . |
11,456 | def is_orthonormal ( self ) : if self . _is_orthonormal is None : _log . debug ( "Testing and caching if operator basis is orthonormal" ) self . _is_orthonormal = np . allclose ( self . metric ( ) , np . eye ( self . dim ) ) return self . _is_orthonormal | Compute a matrix of Hilbert - Schmidt inner products for the basis operators and see if they are orthonormal . If they are return True else False . |
11,457 | def all_hermitian ( self ) : if self . _all_hermitian is None : _log . debug ( "Testing and caching if all basis operator are hermitian" ) self . _all_hermitian = all ( ( is_hermitian ( op ) for op in self . ops ) ) return self . _all_hermitian | Check if all basis operators are hermitian . |
11,458 | def product ( self , * bases ) : if len ( bases ) > 1 : basis_rest = bases [ 0 ] . product ( * bases [ 1 : ] ) else : assert len ( bases ) == 1 basis_rest = bases [ 0 ] labels_ops = [ ( b1l + b2l , qt . tensor ( b1 , b2 ) ) for ( b1l , b1 ) , ( b2l , b2 ) in itertools . product ( self , basis_rest ) ] return OperatorBa... | Compute the tensor product with another basis . |
11,459 | def super_basis ( self ) : labels_ops = [ ( bnl + "^T (x) " + bml , qt . sprepost ( bm , bn ) ) for ( bnl , bn ) , ( bml , bm ) in itertools . product ( self , self ) ] return OperatorBasis ( labels_ops ) | Generate the superoperator basis in which the Choi matrix can be represented . |
11,460 | def project_op ( self , op ) : if not self . is_orthonormal ( ) : raise ValueError ( "project_op only implemented for orthonormal operator bases" ) return self . basis_transform . H * qt . operator_to_vector ( op ) . data | Project an operator onto the basis . |
11,461 | def is_unitary ( matrix : np . ndarray ) -> bool : rows , cols = matrix . shape if rows != cols : return False return np . allclose ( np . eye ( rows ) , matrix . dot ( matrix . T . conj ( ) ) ) | A helper function that checks if a matrix is unitary . |
11,462 | def most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ] | A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right . |
11,463 | def bitwise_xor ( bs0 : str , bs1 : str ) -> str : if len ( bs0 ) != len ( bs1 ) : raise ValueError ( "Bit strings are not of equal length" ) n_bits = len ( bs0 ) return PADDED_BINARY_BIT_STRING . format ( xor ( int ( bs0 , 2 ) , int ( bs1 , 2 ) ) , n_bits ) | A helper to calculate the bitwise XOR of two bit string |
11,464 | def numpart_qaoa ( asset_list , A = 1.0 , minimizer_kwargs = None , steps = 1 ) : cost_operators = [ ] ref_operators = [ ] for ii in range ( len ( asset_list ) ) : for jj in range ( ii + 1 , len ( asset_list ) ) : cost_operators . append ( PauliSum ( [ PauliTerm ( "Z" , ii , 2 * asset_list [ ii ] ) * PauliTerm ( "Z" , ... | generate number partition driver and cost functions |
11,465 | def estimate_gradient ( f_h : float , precision : int , gradient_max : int = 1 , n_measurements : int = 50 , qc : QuantumComputer = None ) -> float : f_h *= 1. / gradient_max perturbation_sign = np . sign ( f_h ) p_gradient = gradient_program ( f_h , precision ) if qc is None : qc = get_qc ( f"{len(p_gradient.get_qubit... | Estimate the gradient using function evaluation at perturbation h . |
11,466 | def process_tomography_programs ( process , qubits = None , pre_rotation_generator = tomography . default_rotations , post_rotation_generator = tomography . default_rotations ) : if qubits is None : qubits = process . get_qubits ( ) for tomographic_pre_rotation in pre_rotation_generator ( * qubits ) : for tomography_po... | Generator that yields tomographic sequences that wrap a process encoded by a QUIL program proc in tomographic rotations on the specified qubits . |
11,467 | def do_process_tomography ( process , nsamples , cxn , qubits = None , use_run = False ) : return tomography . _do_tomography ( process , nsamples , cxn , qubits , tomography . MAX_QUBITS_PROCESS_TOMO , ProcessTomography , process_tomography_programs , DEFAULT_PROCESS_TOMO_SETTINGS , use_run = use_run ) | Method to perform a process tomography . |
11,468 | def estimate_from_ssr ( histograms , readout_povm , pre_channel_ops , post_channel_ops , settings ) : nqc = len ( pre_channel_ops [ 0 ] . dims [ 0 ] ) pauli_basis = grove . tomography . operator_utils . PAULI_BASIS ** nqc pi_basis = readout_povm . pi_basis if not histograms . shape [ - 1 ] == pi_basis . dim : raise Val... | Estimate a quantum process from single shot histograms obtained by preparing specific input states and measuring bitstrings in the Z - eigenbasis after application of given channel operators . |
11,469 | def process_fidelity ( self , reference_unitary ) : if isinstance ( reference_unitary , qt . Qobj ) : if not reference_unitary . issuper or reference_unitary . superrep != "super" : sother = qt . to_super ( reference_unitary ) else : sother = reference_unitary tm_other = self . pauli_basis . transfer_matrix ( sother ) ... | Compute the quantum process fidelity of the estimated state with respect to a unitary process . For non - sparse reference_unitary this implementation this will be expensive in higher dimensions . |
11,470 | def to_kraus ( self ) : return [ k . data . toarray ( ) for k in qt . to_kraus ( self . sop ) ] | Compute the Kraus operator representation of the estimated process . |
11,471 | def plot_pauli_transfer_matrix ( self , ax ) : title = "Estimated process" ut . plot_pauli_transfer_matrix ( self . r_est , ax , self . pauli_basis . labels , title ) | Plot the elements of the Pauli transfer matrix . |
11,472 | def plot ( self ) : fig , ( ax1 ) = plt . subplots ( 1 , 1 , figsize = ( 10 , 8 ) ) self . plot_pauli_transfer_matrix ( ax1 ) return fig | Visualize the process . |
11,473 | def bit_reversal ( qubits : List [ int ] ) -> Program : p = Program ( ) n = len ( qubits ) for i in range ( int ( n / 2 ) ) : p . inst ( SWAP ( qubits [ i ] , qubits [ - i - 1 ] ) ) return p | Generate a circuit to do bit reversal . |
11,474 | def qft ( qubits : List [ int ] ) -> Program : p = Program ( ) . inst ( _core_qft ( qubits , 1 ) ) return p + bit_reversal ( qubits ) | Generate a program to compute the quantum Fourier transform on a set of qubits . |
11,475 | def inverse_qft ( qubits : List [ int ] ) -> Program : qft_result = Program ( ) . inst ( _core_qft ( qubits , - 1 ) ) qft_result += bit_reversal ( qubits ) inverse_qft = Program ( ) while len ( qft_result ) > 0 : new_inst = qft_result . pop ( ) inverse_qft . inst ( new_inst ) return inverse_qft | Generate a program to compute the inverse quantum Fourier transform on a set of qubits . |
11,476 | def unitary_operator ( state_vector ) : if not np . allclose ( [ np . linalg . norm ( state_vector ) ] , [ 1 ] ) : raise ValueError ( "Vector must be normalized" ) if 2 ** get_bits_needed ( len ( state_vector ) ) != len ( state_vector ) : raise ValueError ( "Vector length must be a power of two and at least two" ) mat ... | Uses QR factorization to create a unitary operator that can encode an arbitrary normalized vector into the wavefunction of a quantum state . |
11,477 | def fix_norm_and_length ( vector ) : norm_vector = vector / np . linalg . norm ( vector ) num_bits = get_bits_needed ( len ( vector ) ) state_vector = np . zeros ( 2 ** num_bits , dtype = complex ) for i in range ( len ( vector ) ) : state_vector [ i ] = norm_vector [ i ] return state_vector | Create a normalized and zero padded version of vector . |
11,478 | def _create_bv_circuit ( self , bit_map : Dict [ str , str ] ) -> Program : unitary , _ = self . _compute_unitary_oracle_matrix ( bit_map ) full_bv_circuit = Program ( ) full_bv_circuit . defgate ( "BV-ORACLE" , unitary ) full_bv_circuit . inst ( X ( self . ancilla ) , H ( self . ancilla ) ) full_bv_circuit . inst ( [ ... | Implementation of the Bernstein - Vazirani Algorithm . |
11,479 | def run ( self , qc : QuantumComputer , bitstring_map : Dict [ str , str ] ) -> 'BernsteinVazirani' : self . input_bitmap = bitstring_map self . n_qubits = len ( list ( bitstring_map . keys ( ) ) [ 0 ] ) self . computational_qubits = list ( range ( self . n_qubits ) ) self . ancilla = self . n_qubits self . bv_circuit ... | Runs the Bernstein - Vazirani algorithm . |
11,480 | def get_solution ( self ) -> Tuple [ str , str ] : if self . solution is None : raise AssertionError ( "You need to `run` this algorithm first" ) return self . solution | Returns the solution of the BV algorithm |
11,481 | def check_solution ( self ) -> bool : if self . solution is None : raise AssertionError ( "You need to `run` this algorithm first" ) assert_map = create_bv_bitmap ( * self . solution ) return all ( [ assert_map [ k ] == v for k , v in self . input_bitmap . items ( ) ] ) | Checks if the the found solution correctly reproduces the input . |
11,482 | def diagonal_basis_commutes ( pauli_a , pauli_b ) : overlapping_active_qubits = set ( pauli_a . get_qubits ( ) ) & set ( pauli_b . get_qubits ( ) ) for qubit_index in overlapping_active_qubits : if ( pauli_a [ qubit_index ] != 'I' and pauli_b [ qubit_index ] != 'I' and pauli_a [ qubit_index ] != pauli_b [ qubit_index ]... | Test if pauli_a and pauli_b share a diagonal basis |
11,483 | def get_diagonalizing_basis ( list_of_pauli_terms ) : qubit_ops = set ( reduce ( lambda x , y : x + y , [ list ( term . _ops . items ( ) ) for term in list_of_pauli_terms ] ) ) qubit_ops = sorted ( list ( qubit_ops ) , key = lambda x : x [ 0 ] ) return PauliTerm . from_list ( list ( map ( lambda x : tuple ( reversed ( ... | Find the Pauli Term with the most non - identity terms |
11,484 | def _max_key_overlap ( pauli_term , diagonal_sets ) : for key in list ( diagonal_sets . keys ( ) ) : pauli_from_key = PauliTerm . from_list ( list ( map ( lambda x : tuple ( reversed ( x ) ) , key ) ) ) if diagonal_basis_commutes ( pauli_term , pauli_from_key ) : updated_pauli_set = diagonal_sets [ key ] + [ pauli_term... | Calculate the max overlap of a pauli term ID with keys of diagonal_sets |
11,485 | def commuting_sets_by_zbasis ( pauli_sums ) : diagonal_sets = { } for term in pauli_sums : diagonal_sets = _max_key_overlap ( term , diagonal_sets ) return diagonal_sets | Computes commuting sets based on terms having the same diagonal basis |
11,486 | def check_trivial_commutation ( pauli_list , single_pauli_term ) : if not isinstance ( pauli_list , list ) : raise TypeError ( "pauli_list should be a list" ) for term in pauli_list : if not _commutes ( term , single_pauli_term ) : return False return True | Check if a PauliTerm trivially commutes with a list of other terms . |
11,487 | def commuting_sets_by_indices ( pauli_sums , commutation_check ) : assert isinstance ( pauli_sums , list ) group_inds = [ ] group_terms = [ ] for i , pauli_sum in enumerate ( pauli_sums ) : for j , term in enumerate ( pauli_sum ) : if len ( group_inds ) == 0 : group_inds . append ( [ ( i , j ) ] ) group_terms . append ... | For a list of pauli sums find commuting sets and keep track of which pauli sum they came from . |
11,488 | def commuting_sets_trivial ( pauli_sum ) : if not isinstance ( pauli_sum , ( PauliTerm , PauliSum ) ) : raise TypeError ( "This method can only group PauliTerm or PauliSum objects" ) if isinstance ( pauli_sum , PauliTerm ) : pauli_sum = PauliSum ( [ pauli_sum ] ) commuting_terms = [ ] for term in pauli_sum : for term_g... | Group a pauli term into commuting sets using trivial check |
11,489 | def ising ( h : List [ int ] , J : Dict [ Tuple [ int , int ] , int ] , num_steps : int = 0 , verbose : bool = True , rand_seed : int = None , connection : QuantumComputer = None , samples : int = None , initial_beta : List [ float ] = None , initial_gamma : List [ float ] = None , minimizer_kwargs : Dict [ str , Any ]... | Ising set up method |
11,490 | def swap_circuit_generator ( register_a : List [ int ] , register_b : List [ int ] , ancilla : int ) -> Program : if len ( register_a ) != len ( register_b ) : raise RegisterSizeMismatch ( "registers involve different numbers of qubits" ) if not isinstance ( register_a , list ) : raise TypeError ( "Register A needs to ... | Generate the swap test circuit primitive . |
11,491 | def get_parameterized_program ( self ) : cost_para_programs = [ ] driver_para_programs = [ ] for idx in range ( self . steps ) : cost_list = [ ] driver_list = [ ] for cost_pauli_sum in self . cost_ham : for term in cost_pauli_sum . terms : cost_list . append ( exponential_map ( term ) ) for driver_pauli_sum in self . r... | Return a function that accepts parameters and returns a new Quil program . |
11,492 | def get_angles ( self ) -> Tuple [ List [ float ] , List [ float ] ] : stacked_params = np . hstack ( ( self . betas , self . gammas ) ) vqe = VQE ( self . minimizer , minimizer_args = self . minimizer_args , minimizer_kwargs = self . minimizer_kwargs ) cost_ham = reduce ( lambda x , y : x + y , self . cost_ham ) param... | Finds optimal angles with the quantum variational eigensolver method . |
11,493 | def probabilities ( self , angles : List [ float ] ) -> np . ndarray : if isinstance ( angles , list ) : angles = np . array ( angles ) assert angles . shape [ 0 ] == 2 * self . steps , "angles must be 2 * steps" param_prog = self . get_parameterized_program ( ) prog = param_prog ( angles ) wf = WavefunctionSimulator (... | Computes the probability of each state given a particular set of angles . |
11,494 | def get_string ( self , betas : List [ float ] , gammas : List [ float ] , samples : int = 100 ) : if samples <= 0 and not isinstance ( samples , int ) : raise ValueError ( "samples variable must be positive integer" ) param_prog = self . get_parameterized_program ( ) stacked_params = np . hstack ( ( betas , gammas ) )... | Compute the most probable string . |
11,495 | def _compute_grover_oracle_matrix ( bitstring_map : Dict [ str , int ] ) -> np . ndarray : n_bits = len ( list ( bitstring_map . keys ( ) ) [ 0 ] ) oracle_matrix = np . zeros ( shape = ( 2 ** n_bits , 2 ** n_bits ) ) for b in range ( 2 ** n_bits ) : pad_str = np . binary_repr ( b , n_bits ) phase_factor = bitstring_map... | Computes the unitary matrix that encodes the oracle function for Grover s algorithm |
11,496 | def _construct_grover_circuit ( self ) -> None : oracle = Program ( ) oracle_name = "GROVER_ORACLE" oracle . defgate ( oracle_name , self . unitary_function_mapping ) oracle . inst ( tuple ( [ oracle_name ] + self . qubits ) ) self . grover_circuit = self . oracle_grover ( oracle , self . qubits ) | Constructs an instance of Grover s Algorithm using initialized values . |
11,497 | def _init_attr ( self , bitstring_map : Dict [ str , int ] ) -> None : self . bit_map = bitstring_map self . unitary_function_mapping = self . _compute_grover_oracle_matrix ( bitstring_map ) self . n_qubits = self . unitary_function_mapping . shape [ 0 ] self . qubits = list ( range ( int ( np . log2 ( self . n_qubits ... | Initializes an instance of Grover s Algorithm given a bitstring_map . |
11,498 | def find_bitstring ( self , qc : QuantumComputer , bitstring_map : Dict [ str , int ] ) -> str : self . _init_attr ( bitstring_map ) ro = self . grover_circuit . declare ( 'ro' , 'BIT' , len ( self . qubits ) ) self . grover_circuit += [ MEASURE ( qubit , ro [ idx ] ) for idx , qubit in enumerate ( self . qubits ) ] ex... | Runs Grover s Algorithm to find the bitstring that is designated by bistring_map . |
11,499 | def oracle_grover ( oracle : Program , qubits : List [ int ] , num_iter : int = None ) -> Program : if num_iter is None : num_iter = int ( round ( np . pi * 2 ** ( len ( qubits ) / 2.0 - 2.0 ) ) ) uniform_superimposer = Program ( ) . inst ( [ H ( qubit ) for qubit in qubits ] ) amp_prog = amplification_circuit ( unifor... | Implementation of Grover s Algorithm for a given oracle . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.