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_child ( index ) . dump ( force = force ) else : child_dump = child [ 3 ] + child [ 4 ] + child [ 5 ] else : child_dump = child . dump ( force = force ) if info [ 2 ] and 'default' in info [ 2 ] : default_value = info [ 1 ] ( ** info [ 2 ] ) if default_value . dump ( ) == child_dump : continue contents . write ( child_dump ) self . _contents = contents . getvalue ( ) self . _header = None if self . _trailer != b'' : self . _trailer = b'' | 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 ( _build_id_tuple ( field [ 2 ] , field [ 1 ] ) ) if cls . _oid_pair is not None : cls . _oid_nums = ( cls . _field_map [ cls . _oid_pair [ 0 ] ] , cls . _field_map [ cls . _oid_pair [ 1 ] ] ) for index , field in enumerate ( cls . _fields ) : has_callback = cls . _spec_callbacks is not None and field [ 0 ] in cls . _spec_callbacks is_mapped_oid = cls . _oid_nums is not None and cls . _oid_nums [ 1 ] == index if has_callback or is_mapped_oid : cls . _precomputed_specs . append ( None ) else : cls . _precomputed_specs . append ( ( field [ 0 ] , field [ 1 ] , field [ 1 ] , field [ 2 ] , None ) ) | 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 spec_override . __class__ == tuple and len ( spec_override ) == 2 : field_spec , value_spec = spec_override if value_spec is None : value_spec = field_spec spec_override = None elif field_spec is None : field_spec = spec_override value_spec = field_spec spec_override = None else : value_spec = spec_override elif self . _oid_nums is not None and self . _oid_nums [ 1 ] == index : oid = self . _lazy_child ( self . _oid_nums [ 0 ] ) . native if oid in self . _oid_specs : spec_override = self . _oid_specs [ oid ] value_spec = spec_override return ( name , field_spec , value_spec , field_params , spec_override ) | 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 . _child_spec : child = parts + ( self . _child_spec , ) else : child = parts if recurse : child = _build ( * child ) if isinstance ( child , ( Sequence , SequenceOf ) ) : child . _parse_children ( recurse = True ) self . children . append ( child ) except ( ValueError , TypeError ) as e : self . children = None args = e . args [ 1 : ] e . args = ( e . args [ 0 ] + '\n while parsing %s' % type_name ( self ) , ) + args raise e | 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 TypeError ( 'method must be an integer, not %s' % type_name ( method ) ) if method < 0 or method > 1 : raise ValueError ( 'method must be 0 or 1, not %s' % method ) if not isinstance ( tag , int ) : raise TypeError ( 'tag must be an integer, not %s' % type_name ( tag ) ) if tag < 0 : raise ValueError ( 'tag must be greater than zero, not %s' % tag ) if not isinstance ( contents , byte_cls ) : raise TypeError ( 'contents must be a byte string, not %s' % type_name ( contents ) ) return _dump_header ( class_ , method , tag , contents ) + contents | 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 if tag == 31 : tag = 0 while True : num = ord ( encoded_data [ pointer ] ) if _PY2 else encoded_data [ pointer ] pointer += 1 tag *= 128 tag += num & 127 if num >> 7 == 0 : break length_octet = ord ( encoded_data [ pointer ] ) if _PY2 else encoded_data [ pointer ] pointer += 1 if length_octet >> 7 == 0 : if lengths_only : return ( pointer , pointer + ( length_octet & 127 ) ) contents_end = pointer + ( length_octet & 127 ) else : length_octets = length_octet & 127 if length_octets : pointer += length_octets contents_end = pointer + int_from_bytes ( encoded_data [ pointer - length_octets : pointer ] , signed = False ) if lengths_only : return ( pointer , contents_end ) else : contents_end = pointer if tag == 3 : contents_end += 1 while contents_end < data_len : sub_header_end , contents_end = _parse ( encoded_data , data_len , contents_end , lengths_only = True ) if contents_end == sub_header_end and encoded_data [ contents_end - 2 : contents_end ] == b'\x00\x00' : break if lengths_only : return ( pointer , contents_end ) if contents_end > data_len : raise ValueError ( _INSUFFICIENT_DATA_MESSAGE % ( contents_end , data_len ) ) return ( ( first_octet >> 6 , ( first_octet >> 5 ) & 1 , tag , encoded_data [ start : pointer ] , encoded_data [ pointer : contents_end - 2 ] , b'\x00\x00' ) , contents_end ) if contents_end > data_len : raise ValueError ( _INSUFFICIENT_DATA_MESSAGE % ( contents_end , data_len ) ) return ( ( first_octet >> 6 , ( first_octet >> 5 ) & 1 , tag , encoded_data [ start : pointer ] , encoded_data [ pointer : contents_end ] , b'' ) , contents_end ) | 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 += chr_cls ( id_num | tag ) length = len ( contents ) if length <= 127 : header += chr_cls ( length ) else : length_bytes = int_to_bytes ( length ) header += chr_cls ( 0x80 | len ( length_bytes ) ) header += length_bytes return 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 ( safe ) : unicode_string = unicode_string . replace ( safe_char , '%%%02x' % ord ( safe_char ) ) return unicode_string string = re . sub ( '(?:%[0-9a-fA-F]{2})+' , _try_unescape , string ) def _extract_escape ( match ) : escapes . append ( match . group ( 0 ) . encode ( 'ascii' ) ) return '\x00' string = re . sub ( '%[0-9a-fA-F]{2}' , _extract_escape , string ) output = urlquote ( string . encode ( 'utf-8' ) , safe = safe . encode ( 'utf-8' ) ) if not isinstance ( output , byte_cls ) : output = output . encode ( 'ascii' ) if len ( escapes ) > 0 : def _return_escape ( _ ) : return escapes . pop ( 0 ) output = re . sub ( b'%00' , _return_escape , output ) return output | 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 [ replacement ] = char byte_string = byte_string . replace ( char . encode ( 'ascii' ) , replacement . encode ( 'ascii' ) ) byte_string = unquote_to_bytes ( byte_string ) if remap : for char in remap : byte_string = byte_string . replace ( char . encode ( 'ascii' ) , ( '%%%02x' % ord ( char ) ) . encode ( 'ascii' ) ) output = byte_string . decode ( 'utf-8' , 'iriutf8' ) if preserve : for replacement , original in preserve_unmap . items ( ) : output = output . replace ( replacement , original ) return output | 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_argument ( '--width' , type = int , default = 50 , help = 'width of graph in characters default:50' ) parser . add_argument ( '--format' , default = '{:<5.2f}' , help = 'format specifier to use.' ) parser . add_argument ( '--suffix' , default = '' , help = 'string to add as a suffix to all data points.' ) parser . add_argument ( '--no-labels' , action = 'store_true' , help = 'Do not print the label column' ) parser . add_argument ( '--color' , nargs = '*' , choices = AVAILABLE_COLORS , help = 'Graph bar color( s )' ) parser . add_argument ( '--vertical' , action = 'store_true' , help = 'Vertical graph' ) parser . add_argument ( '--stacked' , action = 'store_true' , help = 'Stacked bar graph' ) parser . add_argument ( '--different-scale' , action = 'store_true' , help = 'Categories have different scales.' ) parser . add_argument ( '--calendar' , action = 'store_true' , help = 'Calendar Heatmap chart' ) parser . add_argument ( '--start-dt' , help = 'Start date for Calendar chart' ) parser . add_argument ( '--custom-tick' , default = '' , help = 'Custom tick mark, emoji approved' ) parser . add_argument ( '--delim' , default = '' , help = 'Custom delimiter, default , or space' ) parser . add_argument ( '--verbose' , action = 'store_true' , help = 'Verbose output, helpful for debugging' ) parser . add_argument ( '--version' , action = 'store_true' , help = 'Display version and exit' ) if len ( sys . argv ) == 1 : if sys . stdin . isatty ( ) : parser . print_usage ( ) sys . exit ( 2 ) args = vars ( parser . parse_args ( ) ) if args [ 'custom_tick' ] != '' : global TICK , SM_TICK TICK = args [ 'custom_tick' ] SM_TICK = '' if args [ 'delim' ] != '' : global DELIM DELIM = args [ 'delim' ] return args | 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_factor = width / float ( max_dat ) normal_dat = [ ] for dat in off_data : normal_dat . append ( [ _v * norm_factor for _v in dat ] ) return normal_dat | 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 range ( len ( values ) ) : if j > 0 : len_label = len ( label ) label = ' ' * len_label tail = ' {}{}' . format ( args [ 'format' ] . format ( values [ j ] ) , args [ 'suffix' ] ) if colors : color = colors [ j ] else : color = None if not args [ 'vertical' ] : print ( label , end = "" ) yield ( values [ j ] , int ( num_blocks [ j ] ) , val_min , color ) if not args [ 'vertical' ] : print ( tail ) | 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 [ i ] num_blocks = normal_data [ i ] for j in range ( len ( values ) ) : print_row ( values [ j ] , int ( num_blocks [ j ] ) , val_min , colors [ j ] ) tail = ' {}{}' . format ( args [ 'format' ] . format ( sum ( values ) ) , args [ 'suffix' ] ) print ( tail ) | 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 , fillvalue = ' ' ) : zipped_list . append ( row ) counter , result_list = 0 , [ ] for i in reversed ( zipped_list ) : result_list . append ( i ) counter += 1 if maxi == args [ 'width' ] : if counter == ( args [ 'width' ] ) : break else : if counter == maxi : break return result_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 ( " " . join ( value ) ) if args [ 'no_labels' ] == False : print ( "-" * len ( row ) + "Labels" + "-" * len ( row ) ) for label in zip_longest ( * labels , fillvalue = '' ) : print ( " " . join ( label ) ) | 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 args [ 'different_scale' ] : for i in range ( len_categories ) : cat_data = [ ] for dat in data : cat_data . append ( [ dat [ i ] ] ) normal_cat_data = normalize ( cat_data , args [ 'width' ] ) for row in horiz_rows ( labels , cat_data , normal_cat_data , args , [ colors [ i ] ] ) : if not args [ 'vertical' ] : print_row ( * row ) else : vertic = vertically ( * row , args = args ) if args [ 'vertical' ] : print_vertical ( vertic , labels , colors [ i ] , args ) print ( ) value_list . clear ( ) , zipped_list . clear ( ) , vertical_list . clear ( ) return if not args [ 'stacked' ] : normal_dat = normalize ( data , args [ 'width' ] ) for row in horiz_rows ( labels , data , normal_dat , args , colors ) : if not args [ 'vertical' ] : print_row ( * row ) else : vertic = vertically ( * row , args = args ) if args [ 'vertical' ] and len_categories == 1 : if colors : color = colors [ 0 ] else : color = None print_vertical ( vertic , labels , color , args ) print ( ) | 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 = [ ] if args [ 'color' ] is not None : if len ( args [ 'color' ] ) != len_categories : print ( ">> Error: Color and category array sizes don't match" ) sys . exit ( 1 ) for color in args [ 'color' ] : colors . append ( AVAILABLE_COLORS . get ( color ) ) if args [ 'vertical' ] and len_categories > 1 and not args [ 'different_scale' ] : print ( ">> Error: Vertical graph for multiple series of same " "scale is not supported yet." ) sys . exit ( 1 ) if args [ 'stacked' ] and not colors : colors = [ v for v in list ( AVAILABLE_COLORS . values ( ) ) [ : len_categories ] ] return 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 = sys . stdin if stdin else open ( filename , "r" ) for line in f : line = line . strip ( ) if line : if not line . startswith ( '#' ) : if line . find ( DELIM ) > 0 : cols = line . split ( DELIM ) else : cols = line . split ( ) if line . startswith ( '@' ) : cols [ 0 ] = cols [ 0 ] . replace ( "@ " , "" ) categories = cols else : labels . append ( cols [ 0 ] . strip ( ) ) data_points = [ ] for i in range ( 1 , len ( cols ) ) : data_points . append ( float ( cols [ i ] . strip ( ) ) ) data . append ( data_points ) f . close ( ) colors = check_data ( labels , data , args ) if categories : print_categories ( categories , colors ) return categories , labels , data , colors | 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_1 = "░" tick_2 = "▒" tick_3 = "▓" tick_4 = "█" if args [ 'custom_tick' ] : tick_1 = tick_2 = tick_3 = tick_4 = args [ 'custom_tick' ] if args [ 'start_dt' ] : start_dt = datetime . strptime ( args [ 'start_dt' ] , '%Y-%m-%d' ) else : start = datetime . now ( ) start_dt = datetime ( year = start . year - 1 , month = start . month , day = start . day ) start_dt = start_dt - timedelta ( start_dt . weekday ( ) ) sys . stdout . write ( " " ) for month in range ( 13 ) : month_dt = datetime ( year = start_dt . year , month = start_dt . month , day = 1 ) + timedelta ( days = month * 31 ) sys . stdout . write ( month_dt . strftime ( "%b" ) + " " ) if args [ 'custom_tick' ] : sys . stdout . write ( " " ) sys . stdout . write ( '\n' ) for day in range ( 7 ) : sys . stdout . write ( DAYS [ day ] + ': ' ) for week in range ( 53 ) : day_ = start_dt + timedelta ( days = day + week * 7 ) day_str = day_ . strftime ( "%Y-%m-%d" ) if day_str in dt_dict : if dt_dict [ day_str ] > max_val * 0.75 : tick = tick_4 elif dt_dict [ day_str ] > max_val * 0.50 : tick = tick_3 elif dt_dict [ day_str ] > max_val * 0.25 : tick = tick_2 else : tick = tick_1 else : tick = ' ' if colornum : sys . stdout . write ( f'\033[{colornum}m' ) sys . stdout . write ( tick ) if colornum : sys . stdout . write ( '\033[0m' ) sys . stdout . write ( '\n' ) | 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." , func . __name__ , type ( e ) , e . errno , exc_info = True ) return - e . errno else : log . error ( "FUSE operation %s raised an OSError with negative " "errno %s, returning errno.EINVAL." , func . __name__ , e . errno , exc_info = True ) return - errno . EINVAL except Exception : log . error ( "Uncaught exception from FUSE operation %s, " "returning errno.EINVAL." , func . __name__ , exc_info = True ) return - errno . EINVAL except BaseException as e : self . __critical_exception = e log . critical ( "Uncaught critical exception from FUSE operation %s, aborting." , func . __name__ , exc_info = True ) fuse_exit ( ) return - errno . EFAULT | 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_program . inst ( state_prep ) state_tomography_program . inst ( tomography_program ) state_tomography_program . inst ( Pragma ( "END_PRESERVE_BLOCK" ) ) yield state_tomography_program | 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 tomography is only implemented for two-level systems." ) n_kj = np . asarray ( histograms ) c_jk_m = _prepare_c_jk_m ( readout_povm , pauli_basis , channel_ops ) rho_m = cvxpy . Variable ( pauli_basis . dim ) p_jk = c_jk_m * rho_m obj = - n_kj . ravel ( ) * cvxpy . log ( p_jk ) p_jk_mat = cvxpy . reshape ( p_jk , pi_basis . dim , len ( channel_ops ) ) constraints = [ p_jk >= 0 , np . matrix ( np . ones ( ( 1 , pi_basis . dim ) ) ) * p_jk_mat == 1 , ] rho_m_real_imag = sum ( ( rm * o_ut . to_realimag ( Pm ) for ( rm , Pm ) in ut . izip ( rho_m , pauli_basis . ops ) ) , 0 ) if POSITIVE in settings . constraints : if tomography . _SDP_SOLVER . is_functional ( ) : constraints . append ( rho_m_real_imag >> 0 ) else : _log . warning ( "No convex solver capable of semi-definite problems installed.\n" "Dropping the positivity constraint on the density matrix." ) if UNIT_TRACE in settings . constraints : constraints . append ( rho_m [ 0 , 0 ] == 1. / pauli_basis . ops [ 0 ] . tr ( ) . real ) prob = cvxpy . Problem ( cvxpy . Minimize ( obj ) , constraints ) _log . info ( "Starting convex solver" ) prob . solve ( solver = tomography . SOLVER , ** settings . solver_kwargs ) if prob . status != cvxpy . OPTIMAL : _log . warning ( "Problem did not converge to optimal solution. " "Solver settings: {}" . format ( settings . solver_kwargs ) ) return StateTomography ( np . array ( rho_m . value ) . ravel ( ) , pauli_basis , settings ) | 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 ( self . computational_qubits , dj_ro ) ] executable = qc . compile ( prog ) returned_bitstring = qc . run ( executable ) bitstring = np . array ( returned_bitstring , dtype = int ) constant = all ( [ bit == 0 for bit in bitstring ] ) return constant | 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 - 1 ) : unitary_funct = np . zeros ( shape = ( 2 ** num_qubits , 2 ** num_qubits ) ) index_lists = [ list ( range ( 2 ** ( num_qubits - 1 ) ) ) , list ( range ( 2 ** ( num_qubits - 1 ) , 2 ** num_qubits ) ) ] for j in range ( 2 ** num_qubits ) : bitstring = np . binary_repr ( j , num_qubits ) value = int ( mappings [ bitstring ] ) mappings . pop ( bitstring ) i = index_lists [ value ] . pop ( ) unitary_funct [ i , j ] = 1 return np . kron ( np . identity ( 2 ) , unitary_funct ) elif bitsum == 2 ** num_qubits : x_gate = np . array ( [ [ 0 , 1 ] , [ 1 , 0 ] ] ) return np . kron ( SWAP_MATRIX , np . identity ( 2 ** ( num_qubits - 1 ) ) ) . dot ( np . kron ( x_gate , np . identity ( 2 ** num_qubits ) ) ) else : raise ValueError ( "f(x) must be constant or balanced" ) | 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 oracle_prog else : bitflip_prog = Program ( ) for i , qubit in enumerate ( qubits ) : if bitstring [ i ] == '0' : bitflip_prog . inst ( X ( qubit ) ) oracle_prog += bitflip_prog controls = qubits [ : - 1 ] target = qubits [ - 1 ] operation = np . array ( [ [ 1 , 0 ] , [ 0 , - 1 ] ] ) gate_name = 'Z' n_qubit_controlled_z = ( ControlledProgramBuilder ( ) . with_controls ( controls ) . with_target ( target ) . with_operation ( operation ) . with_gate_name ( gate_name ) . build ( ) ) oracle_prog += n_qubit_controlled_z oracle_prog += bitflip_prog return oracle_prog | 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 ( confusion_rate_matrix ) ) if not ( confusion_rate_matrix >= 0 ) . all ( ) or not ( confusion_rate_matrix <= 1 ) . all ( ) : raise CRMValueError ( "Confusion matrix must have values in [0, 1]:" "\n{}" . format ( confusion_rate_matrix ) ) ops = [ sum ( ( pi_j * pjk for ( pi_j , pjk ) in izip ( pi_basis . ops , pjs ) ) , 0 ) for pjs in confusion_rate_matrix ] return DiagonalPOVM ( pi_basis = pi_basis , confusion_rate_matrix = confusion_rate_matrix , ops = ops ) | 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 ) < EPS return spnorm ( operator . H - operator ) / spnorm ( operator ) < EPS | 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 = sum ( ( pauli_tm [ jj , kk ] * sbasis . ops [ jj + kk * D ] for jj in range ( D ) for kk in range ( D ) ) ) choi . superrep = CHOI return 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 OperatorBasis ( labels_ops ) | 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" , jj , A * asset_list [ jj ] ) ] ) ) ref_operators . append ( PauliSum ( [ PauliTerm ( "X" , ii , - 1.0 ) ] ) ) cost_operators . append ( PauliSum ( [ PauliTerm ( "I" , 0 , len ( asset_list ) ) ] ) ) if minimizer_kwargs is None : minimizer_kwargs = { 'method' : 'Nelder-Mead' , 'options' : { 'ftol' : 1.0e-2 , 'xtol' : 1.0e-2 , 'disp' : True } } qc = get_qc ( f"{len(asset_list)}q-qvm" ) qaoa_inst = QAOA ( qc , list ( range ( len ( asset_list ) ) ) , steps = steps , cost_ham = cost_operators , ref_ham = ref_operators , store_basis = True , minimizer = minimize , minimizer_kwargs = minimizer_kwargs , vqe_options = { 'disp' : print } ) return qaoa_inst | 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_qubits())}q-qvm" ) p_gradient . wrap_in_numshots_loop ( n_measurements ) executable = qc . compiler . native_quil_to_executable ( p_gradient ) measurements = qc . run ( executable ) bf_estimate = perturbation_sign * measurements_to_bf ( measurements ) bf_explicit = '{0:.16f}' . format ( bf_estimate ) deci_estimate = binary_float_to_decimal_float ( bf_explicit ) deci_estimate *= gradient_max return deci_estimate | 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_post_rotation in post_rotation_generator ( * qubits ) : process_tomography_program = Program ( Pragma ( "PRESERVE_BLOCK" ) ) process_tomography_program . inst ( tomographic_pre_rotation ) process_tomography_program . inst ( process ) process_tomography_program . inst ( tomography_post_rotation ) process_tomography_program . inst ( Pragma ( "END_PRESERVE_BLOCK" ) ) yield process_tomography_program | 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 ValueError ( "Currently tomography is only implemented for two-level systems" ) rho0 = grove . tomography . operator_utils . n_qubit_ground_state ( nqc ) n_lkj = np . asarray ( histograms ) b_jkl_mn = _prepare_b_jkl_mn ( readout_povm , pauli_basis , pre_channel_ops , post_channel_ops , rho0 ) r_mn = cvxpy . Variable ( pauli_basis . dim ** 2 ) p_jkl = b_jkl_mn . real * r_mn obj = - np . matrix ( n_lkj . ravel ( ) ) * cvxpy . log ( p_jkl ) p_jkl_mat = cvxpy . reshape ( p_jkl , pi_basis . dim , len ( pre_channel_ops ) * len ( post_channel_ops ) ) constraints = [ p_jkl >= 0 , np . matrix ( np . ones ( ( 1 , pi_basis . dim ) ) ) * p_jkl_mat == 1 ] r_mn_mat = cvxpy . reshape ( r_mn , pauli_basis . dim , pauli_basis . dim ) super_pauli_basis = pauli_basis . super_basis ( ) choi_real_imag = sum ( ( r_mn_mat [ jj , kk ] * o_ut . to_realimag ( super_pauli_basis . ops [ jj + kk * pauli_basis . dim ] ) for jj in range ( pauli_basis . dim ) for kk in range ( pauli_basis . dim ) ) , 0 ) if COMPLETELY_POSITIVE in settings . constraints : if tomography . _SDP_SOLVER . is_functional ( ) : constraints . append ( choi_real_imag >> 0 ) else : _log . warning ( "No convex solver capable of semi-definite problems installed.\n" "Dropping the complete positivity constraint on the process" ) if TRACE_PRESERVING in settings . constraints : constraints . append ( r_mn_mat [ 0 , 0 ] == 1 ) constraints . append ( r_mn_mat [ 0 , 1 : ] == 0 ) prob = cvxpy . Problem ( cvxpy . Minimize ( obj ) , constraints ) _ = prob . solve ( solver = tomography . SOLVER , ** settings . solver_kwargs ) r_mn_est = r_mn . value . reshape ( ( pauli_basis . dim , pauli_basis . dim ) ) . transpose ( ) return ProcessTomography ( r_mn_est , pauli_basis , settings ) | 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 ) else : tm_other = csr_matrix ( reference_unitary ) dimension = self . pauli_basis . ops [ 0 ] . shape [ 0 ] return np . trace ( tm_other . T * self . r_est ) . real / dimension ** 2 | 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 = np . identity ( len ( state_vector ) , dtype = complex ) for i in range ( len ( state_vector ) ) : mat [ i , 0 ] = state_vector [ i ] U = np . linalg . qr ( mat ) [ 0 ] zero_state = np . zeros ( len ( U ) ) zero_state [ 0 ] = 1 if np . allclose ( U . dot ( zero_state ) , state_vector ) : return U else : return - 1 * U | 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 ( [ H ( i ) for i in self . computational_qubits ] ) full_bv_circuit . inst ( tuple ( [ "BV-ORACLE" ] + sorted ( self . computational_qubits + [ self . ancilla ] , reverse = True ) ) ) full_bv_circuit . inst ( [ H ( i ) for i in self . computational_qubits ] ) return full_bv_circuit | 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 = self . _create_bv_circuit ( bitstring_map ) full_circuit = Program ( ) full_ro = full_circuit . declare ( 'ro' , 'BIT' , len ( self . computational_qubits ) + 1 ) full_circuit += self . bv_circuit full_circuit += [ MEASURE ( qubit , ro ) for qubit , ro in zip ( self . computational_qubits , full_ro ) ] full_executable = qc . compile ( full_circuit ) full_results = qc . run ( full_executable ) bv_vector = full_results [ 0 ] [ : : - 1 ] ancilla_circuit = Program ( ) ancilla_ro = ancilla_circuit . declare ( 'ro' , 'BIT' , len ( self . computational_qubits ) + 1 ) ancilla_circuit += self . bv_circuit ancilla_circuit += [ MEASURE ( self . ancilla , ancilla_ro [ self . ancilla ] ) ] ancilla_executable = qc . compile ( ancilla_circuit ) ancilla_results = qc . run ( ancilla_executable ) bv_bias = ancilla_results [ 0 ] [ 0 ] self . solution = '' . join ( [ str ( b ) for b in bv_vector ] ) , str ( bv_bias ) return self | 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 ] ) : return False return True | 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 ( x ) ) , qubit_ops ) ) ) | 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 ] diagonalizing_term = get_diagonalizing_basis ( updated_pauli_set ) if len ( diagonalizing_term ) > len ( key ) : del diagonal_sets [ key ] new_key = tuple ( sorted ( diagonalizing_term . _ops . items ( ) , key = lambda x : x [ 0 ] ) ) diagonal_sets [ new_key ] = updated_pauli_set else : diagonal_sets [ key ] = updated_pauli_set return diagonal_sets else : new_key = tuple ( sorted ( pauli_term . _ops . items ( ) , key = lambda x : x [ 0 ] ) ) diagonal_sets [ new_key ] = [ pauli_term ] return diagonal_sets | 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 ( [ term ] ) continue for k , group in enumerate ( group_terms ) : if commutation_check ( group , term ) : group_inds [ k ] += [ ( i , j ) ] group_terms [ k ] += [ term ] break else : group_inds . append ( [ ( i , j ) ] ) group_terms . append ( [ term ] ) return group_inds | 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_group in commuting_terms : if check_trivial_commutation ( term_group , term ) : term_group . append ( term ) break else : commuting_terms . append ( [ term ] ) return commuting_terms | 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 ] = None , vqe_option : Dict [ str , Union [ bool , int ] ] = None ) -> Tuple [ List [ int ] , Union [ int , float ] , Program ] : if num_steps == 0 : num_steps = 2 * len ( h ) n_nodes = len ( h ) cost_operators = [ ] driver_operators = [ ] for i , j in J . keys ( ) : cost_operators . append ( PauliSum ( [ PauliTerm ( "Z" , i , J [ ( i , j ) ] ) * PauliTerm ( "Z" , j ) ] ) ) for i in range ( n_nodes ) : cost_operators . append ( PauliSum ( [ PauliTerm ( "Z" , i , h [ i ] ) ] ) ) driver_operators . append ( PauliSum ( [ PauliTerm ( "X" , i , - 1.0 ) ] ) ) if connection is None : qubits = list ( sum ( J . keys ( ) , ( ) ) ) connection = get_qc ( f"{len(qubits)}q-qvm" ) if minimizer_kwargs is None : minimizer_kwargs = { 'method' : 'Nelder-Mead' , 'options' : { 'fatol' : 1.0e-2 , 'xatol' : 1.0e-2 , 'disp' : False } } if vqe_option is None : vqe_option = { 'disp' : print , 'return_all' : True , 'samples' : samples } if not verbose : vqe_option [ 'disp' ] = None qaoa_inst = QAOA ( connection , list ( range ( n_nodes ) ) , steps = num_steps , init_betas = initial_beta , init_gammas = initial_gamma , cost_ham = cost_operators , ref_ham = driver_operators , minimizer = minimize , minimizer_kwargs = minimizer_kwargs , rand_seed = rand_seed , vqe_options = vqe_option , store_basis = True ) betas , gammas = qaoa_inst . get_angles ( ) most_freq_string , sampling_results = qaoa_inst . get_string ( betas , gammas ) most_freq_string_ising = [ ising_trans ( it ) for it in most_freq_string ] energy_ising = energy_value ( h , J , most_freq_string_ising ) param_prog = qaoa_inst . get_parameterized_program ( ) circuit = param_prog ( np . hstack ( ( betas , gammas ) ) ) return most_freq_string_ising , energy_ising , circuit | 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 be list" ) if not isinstance ( register_b , list ) : raise TypeError ( "Register B needs to be a list" ) if ancilla is None : ancilla = max ( register_a + register_b ) + 1 swap_program = Program ( ) swap_program += H ( ancilla ) for a , b in zip ( register_a , register_b ) : swap_program += CSWAP ( ancilla , a , b ) swap_program += H ( ancilla ) return swap_program | 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 . ref_ham : for term in driver_pauli_sum . terms : driver_list . append ( exponential_map ( term ) ) cost_para_programs . append ( cost_list ) driver_para_programs . append ( driver_list ) def psi_ref ( params ) : if len ( params ) != 2 * self . steps : raise ValueError ( "params doesn't match the number of parameters set by `steps`" ) betas = params [ : self . steps ] gammas = params [ self . steps : ] prog = Program ( ) prog += self . ref_state_prep for idx in range ( self . steps ) : for fprog in cost_para_programs [ idx ] : prog += fprog ( gammas [ idx ] ) for fprog in driver_para_programs [ idx ] : prog += fprog ( betas [ idx ] ) return prog return psi_ref | 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_prog = self . get_parameterized_program ( ) result = vqe . vqe_run ( param_prog , cost_ham , stacked_params , qc = self . qc , ** self . vqe_options ) self . result = result betas = result . x [ : self . steps ] gammas = result . x [ self . steps : ] return betas , gammas | 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 ( ) . wavefunction ( prog ) wf = wf . amplitudes . reshape ( ( - 1 , 1 ) ) probs = np . zeros_like ( wf ) for xx in range ( 2 ** len ( self . qubits ) ) : probs [ xx ] = np . conj ( wf [ xx ] ) * wf [ xx ] return probs | 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 ) ) sampling_prog = Program ( ) ro = sampling_prog . declare ( 'ro' , 'BIT' , len ( self . qubits ) ) sampling_prog += param_prog ( stacked_params ) sampling_prog += [ MEASURE ( qubit , r ) for qubit , r in zip ( self . qubits , ro ) ] sampling_prog . wrap_in_numshots_loop ( samples ) executable = self . qc . compile ( sampling_prog ) bitstring_samples = self . qc . run ( executable ) bitstring_tuples = list ( map ( tuple , bitstring_samples ) ) freq = Counter ( bitstring_tuples ) most_frequent_bit_string = max ( freq , key = lambda x : freq [ x ] ) return most_frequent_bit_string , freq | 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 [ pad_str ] oracle_matrix [ b , b ] = phase_factor return oracle_matrix | 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 ) ) ) ) self . _construct_grover_circuit ( ) | 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 ) ] executable = qc . compile ( self . grover_circuit ) sampled_bitstring = qc . run ( executable ) return "" . join ( [ str ( bit ) for bit in sampled_bitstring [ 0 ] ] ) | 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 ( uniform_superimposer , oracle , qubits , num_iter ) return amp_prog | 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.