idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
18,000 | def available_metadata ( self ) : url = self . base_url + 'metadata/types' headers = { 'Authorization' : 'Bearer {}' . format ( self . auth ( ) ) } r = requests . get ( url , headers = headers ) return pd . read_json ( r . content , orient = 'records' ) [ 'name' ] | List all scenario metadata indicators available in the connected data source | 80 | 11 |
18,001 | def metadata ( self , default = True ) : # at present this reads in all data for all scenarios, it could be sped # up in the future to try to query a subset default = 'true' if default else 'false' add_url = 'runs?getOnlyDefaultRuns={}&includeMetadata=true' url = self . base_url + add_url . format ( default ) headers = { 'Authorization' : 'Bearer {}' . format ( self . auth ( ) ) } r = requests . get ( url , headers = headers ) df = pd . read_json ( r . content , orient = 'records' ) def extract ( row ) : return ( pd . concat ( [ row [ [ 'model' , 'scenario' ] ] , pd . Series ( row . metadata ) ] ) . to_frame ( ) . T . set_index ( [ 'model' , 'scenario' ] ) ) return pd . concat ( [ extract ( row ) for idx , row in df . iterrows ( ) ] , sort = False ) . reset_index ( ) | Metadata of scenarios in the connected data source | 241 | 9 |
18,002 | def variables ( self ) : url = self . base_url + 'ts' headers = { 'Authorization' : 'Bearer {}' . format ( self . auth ( ) ) } r = requests . get ( url , headers = headers ) df = pd . read_json ( r . content , orient = 'records' ) return pd . Series ( df [ 'variable' ] . unique ( ) , name = 'variable' ) | All variables in the connected data source | 95 | 7 |
18,003 | def query ( self , * * kwargs ) : headers = { 'Authorization' : 'Bearer {}' . format ( self . auth ( ) ) , 'Content-Type' : 'application/json' , } data = json . dumps ( self . _query_post_data ( * * kwargs ) ) url = self . base_url + 'runs/bulk/ts' r = requests . post ( url , headers = headers , data = data ) # refactor returned json object to be castable to an IamDataFrame df = ( pd . read_json ( r . content , orient = 'records' ) . drop ( columns = 'runId' ) . rename ( columns = { 'time' : 'subannual' } ) ) # check if returned dataframe has subannual disaggregation, drop if not if pd . Series ( [ i in [ - 1 , 'year' ] for i in df . subannual ] ) . all ( ) : df . drop ( columns = 'subannual' , inplace = True ) # check if there are multiple version for any model/scenario lst = ( df [ META_IDX + [ 'version' ] ] . drop_duplicates ( ) . groupby ( META_IDX ) . count ( ) . version ) if max ( lst ) > 1 : raise ValueError ( 'multiple versions for {}' . format ( lst [ lst > 1 ] . index . to_list ( ) ) ) df . drop ( columns = 'version' , inplace = True ) return df | Query the data source subselecting data . Available keyword arguments include | 345 | 13 |
18,004 | def reindex ( self , copy = True ) : ret = deepcopy ( self ) if copy else self ret . stats = ret . stats . reindex ( index = ret . _idx , level = 0 ) if ret . idx_depth == 2 : ret . stats = ret . stats . reindex ( index = ret . _sub_idx , level = 1 ) if ret . rows is not None : ret . stats = ret . stats . reindex ( index = ret . rows , level = ret . idx_depth ) ret . stats = ret . stats . reindex ( columns = ret . _headers , level = 0 ) ret . stats = ret . stats . reindex ( columns = ret . _subheaders , level = 1 ) ret . stats = ret . stats . reindex ( columns = ret . _describe_cols , level = 2 ) if copy : return ret | Reindex the summary statistics dataframe | 190 | 7 |
18,005 | def summarize ( self , center = 'mean' , fullrange = None , interquartile = None , custom_format = '{:.2f}' ) : # call `reindex()` to reorder index and columns self . reindex ( copy = False ) center = 'median' if center == '50%' else center if fullrange is None and interquartile is None : fullrange = True return self . stats . apply ( format_rows , center = center , fullrange = fullrange , interquartile = interquartile , custom_format = custom_format , axis = 1 , raw = False ) | Format the compiled statistics to a concise string output | 134 | 9 |
18,006 | def reset_default_props ( * * kwargs ) : global _DEFAULT_PROPS pcycle = plt . rcParams [ 'axes.prop_cycle' ] _DEFAULT_PROPS = { 'color' : itertools . cycle ( _get_standard_colors ( * * kwargs ) ) if len ( kwargs ) > 0 else itertools . cycle ( [ x [ 'color' ] for x in pcycle ] ) , 'marker' : itertools . cycle ( [ 'o' , 'x' , '.' , '+' , '*' ] ) , 'linestyle' : itertools . cycle ( [ '-' , '--' , '-.' , ':' ] ) , } | Reset properties to initial cycle point | 167 | 7 |
18,007 | def default_props ( reset = False , * * kwargs ) : global _DEFAULT_PROPS if _DEFAULT_PROPS is None or reset : reset_default_props ( * * kwargs ) return _DEFAULT_PROPS | Return current default properties | 56 | 4 |
18,008 | def assign_style_props ( df , color = None , marker = None , linestyle = None , cmap = None ) : if color is None and cmap is not None : raise ValueError ( '`cmap` must be provided with the `color` argument' ) # determine color, marker, and linestyle for each line n = len ( df [ color ] . unique ( ) ) if color in df . columns else len ( df [ list ( set ( df . columns ) & set ( IAMC_IDX ) ) ] . drop_duplicates ( ) ) defaults = default_props ( reset = True , num_colors = n , colormap = cmap ) props = { } rc = run_control ( ) kinds = [ ( 'color' , color ) , ( 'marker' , marker ) , ( 'linestyle' , linestyle ) ] for kind , var in kinds : rc_has_kind = kind in rc if var in df . columns : rc_has_var = rc_has_kind and var in rc [ kind ] props_for_kind = { } for val in df [ var ] . unique ( ) : if rc_has_var and val in rc [ kind ] [ var ] : props_for_kind [ val ] = rc [ kind ] [ var ] [ val ] # cycle any way to keep defaults the same next ( defaults [ kind ] ) else : props_for_kind [ val ] = next ( defaults [ kind ] ) props [ kind ] = props_for_kind # update for special properties only if they exist in props if 'color' in props : d = props [ 'color' ] values = list ( d . values ( ) ) # find if any colors in our properties corresponds with special colors # we know about overlap_idx = np . in1d ( values , list ( PYAM_COLORS . keys ( ) ) ) if overlap_idx . any ( ) : # some exist in our special set keys = np . array ( list ( d . keys ( ) ) ) [ overlap_idx ] values = np . array ( values ) [ overlap_idx ] # translate each from pyam name, like AR6-SSP2-45 to proper color # designation for k , v in zip ( keys , values ) : d [ k ] = PYAM_COLORS [ v ] # replace props with updated dict without special colors props [ 'color' ] = d return props | Assign the style properties for a plot | 530 | 8 |
18,009 | def reshape_line_plot ( df , x , y ) : idx = list ( df . columns . drop ( y ) ) if df . duplicated ( idx ) . any ( ) : warnings . warn ( 'Duplicated index found.' ) df = df . drop_duplicates ( idx , keep = 'last' ) df = df . set_index ( idx ) [ y ] . unstack ( x ) . T return df | Reshape data from long form to line plot form . | 98 | 12 |
18,010 | def reshape_bar_plot ( df , x , y , bars ) : idx = [ bars , x ] if df . duplicated ( idx ) . any ( ) : warnings . warn ( 'Duplicated index found.' ) df = df . drop_duplicates ( idx , keep = 'last' ) df = df . set_index ( idx ) [ y ] . unstack ( x ) . T return df | Reshape data from long form to bar plot form . | 94 | 12 |
18,011 | def read_shapefile ( fname , region_col = None , * * kwargs ) : gdf = gpd . read_file ( fname , * * kwargs ) if region_col is not None : gdf = gdf . rename ( columns = { region_col : 'region' } ) if 'region' not in gdf . columns : raise IOError ( 'Must provide a region column' ) gdf [ 'region' ] = gdf [ 'region' ] . str . upper ( ) return gdf | Read a shapefile for use in regional plots . Shapefiles must have a column denoted as region . | 116 | 21 |
18,012 | def add_net_values_to_bar_plot ( axs , color = 'k' ) : axs = axs if isinstance ( axs , Iterable ) else [ axs ] for ax in axs : box_args = _get_boxes ( ax ) for x , args in box_args . items ( ) : rect = mpatches . Rectangle ( * args , color = color ) ax . add_patch ( rect ) | Add net values next to an existing vertical stacked bar chart | 97 | 11 |
18,013 | def scatter ( df , x , y , ax = None , legend = None , title = None , color = None , marker = 'o' , linestyle = None , cmap = None , groupby = [ 'model' , 'scenario' ] , with_lines = False , * * kwargs ) : if ax is None : fig , ax = plt . subplots ( ) # assign styling properties props = assign_style_props ( df , color = color , marker = marker , linestyle = linestyle , cmap = cmap ) # group data groups = df . groupby ( groupby ) # loop over grouped dataframe, plot data legend_data = [ ] for name , group in groups : pargs = { } labels = [ ] for key , kind , var in [ ( 'c' , 'color' , color ) , ( 'marker' , 'marker' , marker ) , ( 'linestyle' , 'linestyle' , linestyle ) ] : if kind in props : label = group [ var ] . values [ 0 ] pargs [ key ] = props [ kind ] [ group [ var ] . values [ 0 ] ] labels . append ( repr ( label ) . lstrip ( "u'" ) . strip ( "'" ) ) else : pargs [ key ] = var if len ( labels ) > 0 : legend_data . append ( ' ' . join ( labels ) ) else : legend_data . append ( ' ' . join ( name ) ) kwargs . update ( pargs ) if with_lines : ax . plot ( group [ x ] , group [ y ] , * * kwargs ) else : kwargs . pop ( 'linestyle' ) # scatter() can't take a linestyle ax . scatter ( group [ x ] , group [ y ] , * * kwargs ) # build legend handles and labels handles , labels = ax . get_legend_handles_labels ( ) if legend_data != [ '' ] * len ( legend_data ) : labels = sorted ( list ( set ( tuple ( legend_data ) ) ) ) idxs = [ legend_data . index ( d ) for d in labels ] handles = [ handles [ i ] for i in idxs ] if legend is None and len ( labels ) < 13 or legend is not False : _add_legend ( ax , handles , labels , legend ) # add labels and title ax . set_xlabel ( x ) ax . set_ylabel ( y ) if title : ax . set_title ( title ) return ax | Plot data as a scatter chart . | 551 | 7 |
18,014 | def logger ( ) : global _LOGGER if _LOGGER is None : logging . basicConfig ( ) _LOGGER = logging . getLogger ( ) _LOGGER . setLevel ( 'INFO' ) return _LOGGER | Access global logger | 48 | 3 |
18,015 | def nodes ( self ) : if not hasattr ( self , '_nodes' ) : base_url = "{}/{}" . format ( NodeBalancerConfig . api_endpoint , NodeBalancerNode . derived_url_path ) result = self . _client . _get_objects ( base_url , NodeBalancerNode , model = self , parent_id = ( self . id , self . nodebalancer_id ) ) self . _set ( '_nodes' , result ) return self . _nodes | This is a special derived_class relationship because NodeBalancerNode is the only api object that requires two parent_ids | 115 | 24 |
18,016 | def attach ( self , to_linode , config = None ) : result = self . _client . post ( '{}/attach' . format ( Volume . api_endpoint ) , model = self , data = { "linode_id" : to_linode . id if issubclass ( type ( to_linode ) , Base ) else to_linode , "config" : None if not config else config . id if issubclass ( type ( config ) , Base ) else config , } ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when attaching volume!' , json = result ) self . _populate ( result ) return True | Attaches this Volume to the given Linode | 148 | 9 |
18,017 | def detach ( self ) : self . _client . post ( '{}/detach' . format ( Volume . api_endpoint ) , model = self ) return True | Detaches this Volume if it is attached | 37 | 8 |
18,018 | def resize ( self , size ) : result = self . _client . post ( '{}/resize' . format ( Volume . api_endpoint , model = self , data = { "size" : size } ) ) self . _populate ( result . json ) return True | Resizes this Volume | 61 | 4 |
18,019 | def clone ( self , label ) : result = self . _client . post ( '{}/clone' . format ( Volume . api_endpoint ) , model = self , data = { 'label' : label } ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response cloning volume!' ) return Volume ( self . _client , result [ 'id' ] , result ) | Clones this volume to a new volume in the same region with the given label | 87 | 16 |
18,020 | def _get_raw_objects ( self ) : if not hasattr ( self , '_raw_objects' ) : result = self . _client . get ( type ( self ) . api_endpoint , model = self ) # I want to cache this to avoid making duplicate requests, but I don't # want it in the __init__ self . _raw_objects = result # pylint: disable=attribute-defined-outside-init return self . _raw_objects | Helper function to populate the first page of raw objects for this tag . This has the side effect of creating the _raw_objects attribute of this object . | 102 | 31 |
18,021 | def objects ( self ) : data = self . _get_raw_objects ( ) return PaginatedList . make_paginated_list ( data , self . _client , TaggedObjectProxy , page_url = type ( self ) . api_endpoint . format ( * * vars ( self ) ) ) | Returns a list of objects with this Tag . This list may contain any taggable object type . | 68 | 20 |
18,022 | def make_instance ( cls , id , client , parent_id = None , json = None ) : make_cls = CLASS_MAP . get ( id ) # in this case, ID is coming in as the type if make_cls is None : # we don't recognize this entity type - do nothing? return None # discard the envelope real_json = json [ 'data' ] real_id = real_json [ 'id' ] # make the real object type return Base . make ( real_id , client , make_cls , parent_id = None , json = real_json ) | Overrides Base s make_instance to allow dynamic creation of objects based on the defined type in the response json . | 130 | 24 |
18,023 | def resize ( self , new_size ) : self . _client . post ( '{}/resize' . format ( Disk . api_endpoint ) , model = self , data = { "size" : new_size } ) return True | Resizes this disk . The Linode Instance this disk belongs to must have sufficient space available to accommodate the new size and must be offline . | 53 | 29 |
18,024 | def _populate ( self , json ) : from . volume import Volume DerivedBase . _populate ( self , json ) devices = { } for device_index , device in json [ 'devices' ] . items ( ) : if not device : devices [ device_index ] = None continue dev = None if 'disk_id' in device and device [ 'disk_id' ] : # this is a disk dev = Disk . make_instance ( device [ 'disk_id' ] , self . _client , parent_id = self . linode_id ) else : dev = Volume . make_instance ( device [ 'volume_id' ] , self . _client , parent_id = self . linode_id ) devices [ device_index ] = dev self . _set ( 'devices' , MappedObject ( * * devices ) ) | Map devices more nicely while populating . | 182 | 8 |
18,025 | def ips ( self ) : if not hasattr ( self , '_ips' ) : result = self . _client . get ( "{}/ips" . format ( Instance . api_endpoint ) , model = self ) if not "ipv4" in result : raise UnexpectedResponseError ( 'Unexpected response loading IPs' , json = result ) v4pub = [ ] for c in result [ 'ipv4' ] [ 'public' ] : i = IPAddress ( self . _client , c [ 'address' ] , c ) v4pub . append ( i ) v4pri = [ ] for c in result [ 'ipv4' ] [ 'private' ] : i = IPAddress ( self . _client , c [ 'address' ] , c ) v4pri . append ( i ) shared_ips = [ ] for c in result [ 'ipv4' ] [ 'shared' ] : i = IPAddress ( self . _client , c [ 'address' ] , c ) shared_ips . append ( i ) slaac = IPAddress ( self . _client , result [ 'ipv6' ] [ 'slaac' ] [ 'address' ] , result [ 'ipv6' ] [ 'slaac' ] ) link_local = IPAddress ( self . _client , result [ 'ipv6' ] [ 'link_local' ] [ 'address' ] , result [ 'ipv6' ] [ 'link_local' ] ) pools = [ ] for p in result [ 'ipv6' ] [ 'global' ] : pools . append ( IPv6Pool ( self . _client , p [ 'range' ] ) ) ips = MappedObject ( * * { "ipv4" : { "public" : v4pub , "private" : v4pri , "shared" : shared_ips , } , "ipv6" : { "slaac" : slaac , "link_local" : link_local , "pools" : pools , } , } ) self . _set ( '_ips' , ips ) return self . _ips | The ips related collection is not normalized like the others so we have to make an ad - hoc object to return for its response | 473 | 26 |
18,026 | def available_backups ( self ) : if not hasattr ( self , '_avail_backups' ) : result = self . _client . get ( "{}/backups" . format ( Instance . api_endpoint ) , model = self ) if not 'automatic' in result : raise UnexpectedResponseError ( 'Unexpected response loading available backups!' , json = result ) automatic = [ ] for a in result [ 'automatic' ] : cur = Backup ( self . _client , a [ 'id' ] , self . id , a ) automatic . append ( cur ) snap = None if result [ 'snapshot' ] [ 'current' ] : snap = Backup ( self . _client , result [ 'snapshot' ] [ 'current' ] [ 'id' ] , self . id , result [ 'snapshot' ] [ 'current' ] ) psnap = None if result [ 'snapshot' ] [ 'in_progress' ] : psnap = Backup ( self . _client , result [ 'snapshot' ] [ 'in_progress' ] [ 'id' ] , self . id , result [ 'snapshot' ] [ 'in_progress' ] ) self . _set ( '_avail_backups' , MappedObject ( * * { "automatic" : automatic , "snapshot" : { "current" : snap , "in_progress" : psnap , } } ) ) return self . _avail_backups | The backups response contains what backups are available to be restored . | 317 | 12 |
18,027 | def invalidate ( self ) : if hasattr ( self , '_avail_backups' ) : del self . _avail_backups if hasattr ( self , '_ips' ) : del self . _ips Base . invalidate ( self ) | Clear out cached properties | 56 | 4 |
18,028 | def config_create ( self , kernel = None , label = None , devices = [ ] , disks = [ ] , volumes = [ ] , * * kwargs ) : from . volume import Volume hypervisor_prefix = 'sd' if self . hypervisor == 'kvm' else 'xvd' device_names = [ hypervisor_prefix + string . ascii_lowercase [ i ] for i in range ( 0 , 8 ) ] device_map = { device_names [ i ] : None for i in range ( 0 , len ( device_names ) ) } if devices and ( disks or volumes ) : raise ValueError ( 'You may not call config_create with "devices" and ' 'either of "disks" or "volumes" specified!' ) if not devices : if not isinstance ( disks , list ) : disks = [ disks ] if not isinstance ( volumes , list ) : volumes = [ volumes ] devices = [ ] for d in disks : if d is None : devices . append ( None ) elif isinstance ( d , Disk ) : devices . append ( d ) else : devices . append ( Disk ( self . _client , int ( d ) , self . id ) ) for v in volumes : if v is None : devices . append ( None ) elif isinstance ( v , Volume ) : devices . append ( v ) else : devices . append ( Volume ( self . _client , int ( v ) ) ) if not devices : raise ValueError ( 'Must include at least one disk or volume!' ) for i , d in enumerate ( devices ) : if d is None : pass elif isinstance ( d , Disk ) : device_map [ device_names [ i ] ] = { 'disk_id' : d . id } elif isinstance ( d , Volume ) : device_map [ device_names [ i ] ] = { 'volume_id' : d . id } else : raise TypeError ( 'Disk or Volume expected!' ) params = { 'kernel' : kernel . id if issubclass ( type ( kernel ) , Base ) else kernel , 'label' : label if label else "{}_config_{}" . format ( self . label , len ( self . configs ) ) , 'devices' : device_map , } params . update ( kwargs ) result = self . _client . post ( "{}/configs" . format ( Instance . api_endpoint ) , model = self , data = params ) self . invalidate ( ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response creating config!' , json = result ) c = Config ( self . _client , result [ 'id' ] , self . id , result ) return c | Creates a Linode Config with the given attributes . | 588 | 11 |
18,029 | def enable_backups ( self ) : self . _client . post ( "{}/backups/enable" . format ( Instance . api_endpoint ) , model = self ) self . invalidate ( ) return True | Enable Backups for this Instance . When enabled we will automatically backup your Instance s data so that it can be restored at a later date . For more information on Instance s Backups service and pricing see our Backups Page _ | 48 | 48 |
18,030 | def mutate ( self ) : self . _client . post ( '{}/mutate' . format ( Instance . api_endpoint ) , model = self ) return True | Upgrades this Instance to the latest generation type | 39 | 10 |
18,031 | def initiate_migration ( self ) : self . _client . post ( '{}/migrate' . format ( Instance . api_endpoint ) , model = self ) | Initiates a pending migration that is already scheduled for this Linode Instance | 39 | 16 |
18,032 | def clone ( self , to_linode = None , region = None , service = None , configs = [ ] , disks = [ ] , label = None , group = None , with_backups = None ) : if to_linode and region : raise ValueError ( 'You may only specify one of "to_linode" and "region"' ) if region and not service : raise ValueError ( 'Specifying a region requires a "service" as well' ) if not isinstance ( configs , list ) and not isinstance ( configs , PaginatedList ) : configs = [ configs ] if not isinstance ( disks , list ) and not isinstance ( disks , PaginatedList ) : disks = [ disks ] cids = [ c . id if issubclass ( type ( c ) , Base ) else c for c in configs ] dids = [ d . id if issubclass ( type ( d ) , Base ) else d for d in disks ] params = { "linode_id" : to_linode . id if issubclass ( type ( to_linode ) , Base ) else to_linode , "region" : region . id if issubclass ( type ( region ) , Base ) else region , "type" : service . id if issubclass ( type ( service ) , Base ) else service , "configs" : cids if cids else None , "disks" : dids if dids else None , "label" : label , "group" : group , "with_backups" : with_backups , } result = self . _client . post ( '{}/clone' . format ( Instance . api_endpoint ) , model = self , data = params ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response cloning Instance!' , json = result ) l = Instance ( self . _client , result [ 'id' ] , result ) return l | Clones this linode into a new linode or into a new linode in the given region | 425 | 20 |
18,033 | def stats ( self ) : # TODO - this would be nicer if we formatted the stats return self . _client . get ( '{}/stats' . format ( Instance . api_endpoint ) , model = self ) | Returns the JSON stats for this Instance | 49 | 8 |
18,034 | def stats_for ( self , dt ) : # TODO - this would be nicer if we formatted the stats if not isinstance ( dt , datetime ) : raise TypeError ( 'stats_for requires a datetime object!' ) return self . _client . get ( '{}/stats/' . format ( dt . strftime ( '%Y/%m' ) ) ) | Returns stats for the month containing the given datetime | 85 | 10 |
18,035 | def _populate ( self , json ) : Base . _populate ( self , json ) mapped_udfs = [ ] for udf in self . user_defined_fields : t = UserDefinedFieldType . text choices = None if hasattr ( udf , 'oneof' ) : t = UserDefinedFieldType . select_one choices = udf . oneof . split ( ',' ) elif hasattr ( udf , 'manyof' ) : t = UserDefinedFieldType . select_many choices = udf . manyof . split ( ',' ) mapped_udfs . append ( UserDefinedField ( udf . name , udf . label if hasattr ( udf , 'label' ) else None , udf . example if hasattr ( udf , 'example' ) else None , t , choices = choices ) ) self . _set ( 'user_defined_fields' , mapped_udfs ) ndist = [ Image ( self . _client , d ) for d in self . images ] self . _set ( 'images' , ndist ) | Override the populate method to map user_defined_fields to fancy values | 236 | 14 |
18,036 | def _populate ( self , json ) : super ( InvoiceItem , self ) . _populate ( json ) self . from_date = datetime . strptime ( json [ 'from' ] , DATE_FORMAT ) self . to_date = datetime . strptime ( json [ 'to' ] , DATE_FORMAT ) | Allows population of from_date from the returned from attribute which is a reserved word in python . Also populates to_date to be complete . | 77 | 29 |
18,037 | def reset_secret ( self ) : result = self . _client . post ( "{}/reset_secret" . format ( OAuthClient . api_endpoint ) , model = self ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when resetting secret!' , json = result ) self . _populate ( result ) return self . secret | Resets the client secret for this client . | 81 | 9 |
18,038 | def thumbnail ( self , dump_to = None ) : headers = { "Authorization" : "token {}" . format ( self . _client . token ) } result = requests . get ( '{}/{}/thumbnail' . format ( self . _client . base_url , OAuthClient . api_endpoint . format ( id = self . id ) ) , headers = headers ) if not result . status_code == 200 : raise ApiError ( 'No thumbnail found for OAuthClient {}' . format ( self . id ) ) if dump_to : with open ( dump_to , 'wb+' ) as f : f . write ( result . content ) return result . content | This returns binary data that represents a 128x128 image . If dump_to is given attempts to write the image to a file at the given location . | 151 | 31 |
18,039 | def set_thumbnail ( self , thumbnail ) : headers = { "Authorization" : "token {}" . format ( self . _client . token ) , "Content-type" : "image/png" , } # TODO this check needs to be smarter - python2 doesn't do it right if not isinstance ( thumbnail , bytes ) : with open ( thumbnail , 'rb' ) as f : thumbnail = f . read ( ) result = requests . put ( '{}/{}/thumbnail' . format ( self . _client . base_url , OAuthClient . api_endpoint . format ( id = self . id ) ) , headers = headers , data = thumbnail ) if not result . status_code == 200 : errors = [ ] j = result . json ( ) if 'errors' in j : errors = [ e [ 'reason' ] for e in j [ 'errors' ] ] raise ApiError ( '{}: {}' . format ( result . status_code , errors ) , json = j ) return True | Sets the thumbnail for this OAuth Client . If thumbnail is bytes uploads it as a png . Otherwise assumes thumbnail is a path to the thumbnail and reads it in as bytes before uploading . | 223 | 40 |
18,040 | def grants ( self ) : from linode_api4 . objects . account import UserGrants if not hasattr ( self , '_grants' ) : resp = self . _client . get ( UserGrants . api_endpoint . format ( username = self . username ) ) grants = UserGrants ( self . _client , self . username , resp ) self . _set ( '_grants' , grants ) return self . _grants | Retrieves the grants for this user . If the user is unrestricted this will result in an ApiError . This is smart and will only fetch from the api once unless the object is invalidated . | 97 | 41 |
18,041 | def save ( self ) : resp = self . _client . put ( type ( self ) . api_endpoint , model = self , data = self . _serialize ( ) ) if 'error' in resp : return False return True | Send this object s mutable values to the server in a PUT request | 50 | 15 |
18,042 | def delete ( self ) : resp = self . _client . delete ( type ( self ) . api_endpoint , model = self ) if 'error' in resp : return False self . invalidate ( ) return True | Sends a DELETE request for this object | 46 | 10 |
18,043 | def invalidate ( self ) : for key in [ k for k in type ( self ) . properties . keys ( ) if not type ( self ) . properties [ k ] . identifier ] : self . _set ( key , None ) self . _set ( '_populated' , False ) | Invalidates all non - identifier Properties this object has locally causing the next access to re - fetch them from the server | 62 | 23 |
18,044 | def _serialize ( self ) : result = { a : getattr ( self , a ) for a in type ( self ) . properties if type ( self ) . properties [ a ] . mutable } for k , v in result . items ( ) : if isinstance ( v , Base ) : result [ k ] = v . id return result | A helper method to build a dict of all mutable Properties of this object | 73 | 15 |
18,045 | def _api_get ( self ) : json = self . _client . get ( type ( self ) . api_endpoint , model = self ) self . _populate ( json ) | A helper method to GET this object from the server | 40 | 10 |
18,046 | def _populate ( self , json ) : if not json : return # hide the raw JSON away in case someone needs it self . _set ( '_raw_json' , json ) for key in json : if key in ( k for k in type ( self ) . properties . keys ( ) if not type ( self ) . properties [ k ] . identifier ) : if type ( self ) . properties [ key ] . relationship and not json [ key ] is None : if isinstance ( json [ key ] , list ) : objs = [ ] for d in json [ key ] : if not 'id' in d : continue new_class = type ( self ) . properties [ key ] . relationship obj = new_class . make_instance ( d [ 'id' ] , getattr ( self , '_client' ) ) if obj : obj . _populate ( d ) objs . append ( obj ) self . _set ( key , objs ) else : if isinstance ( json [ key ] , dict ) : related_id = json [ key ] [ 'id' ] else : related_id = json [ key ] new_class = type ( self ) . properties [ key ] . relationship obj = new_class . make_instance ( related_id , getattr ( self , '_client' ) ) if obj and isinstance ( json [ key ] , dict ) : obj . _populate ( json [ key ] ) self . _set ( key , obj ) elif type ( self ) . properties [ key ] . slug_relationship and not json [ key ] is None : # create an object of the expected type with the given slug self . _set ( key , type ( self ) . properties [ key ] . slug_relationship ( self . _client , json [ key ] ) ) elif type ( json [ key ] ) is dict : self . _set ( key , MappedObject ( * * json [ key ] ) ) elif type ( json [ key ] ) is list : # we're going to use MappedObject's behavior with lists to # expand these, then grab the resulting value to set mapping = MappedObject ( _list = json [ key ] ) self . _set ( key , mapping . _list ) # pylint: disable=no-member elif type ( self ) . properties [ key ] . is_datetime : try : t = time . strptime ( json [ key ] , DATE_FORMAT ) self . _set ( key , datetime . fromtimestamp ( time . mktime ( t ) ) ) except : #TODO - handle this better (or log it?) self . _set ( key , json [ key ] ) else : self . _set ( key , json [ key ] ) self . _set ( '_populated' , True ) self . _set ( '_last_updated' , datetime . now ( ) ) | A helper method that given a JSON object representing this object assigns values based on the properties dict and the attributes of its Properties . | 623 | 25 |
18,047 | def make ( id , client , cls , parent_id = None , json = None ) : from . dbase import DerivedBase if issubclass ( cls , DerivedBase ) : return cls ( client , id , parent_id , json ) else : return cls ( client , id , json ) | Makes an api object based on an id and class . | 68 | 12 |
18,048 | def make_instance ( cls , id , client , parent_id = None , json = None ) : return Base . make ( id , client , cls , parent_id = parent_id , json = json ) | Makes an instance of the class this is called on and returns it . | 47 | 15 |
18,049 | def to ( self , linode ) : from . linode import Instance if not isinstance ( linode , Instance ) : raise ValueError ( "IP Address can only be assigned to a Linode!" ) return { "address" : self . address , "linode_id" : linode . id } | This is a helper method for ip - assign and should not be used outside of that context . It s used to cleanly build an IP Assign request with pretty python syntax . | 67 | 36 |
18,050 | def token_create ( self , label = None , expiry = None , scopes = None , * * kwargs ) : if label : kwargs [ 'label' ] = label if expiry : if isinstance ( expiry , datetime ) : expiry = datetime . strftime ( expiry , "%Y-%m-%dT%H:%M:%S" ) kwargs [ 'expiry' ] = expiry if scopes : kwargs [ 'scopes' ] = scopes result = self . client . post ( '/profile/tokens' , data = kwargs ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when creating Personal Access ' 'Token!' , json = result ) token = PersonalAccessToken ( self . client , result [ 'id' ] , result ) return token | Creates and returns a new Personal Access Token | 190 | 9 |
18,051 | def ssh_key_upload ( self , key , label ) : if not key . startswith ( SSH_KEY_TYPES ) : # this might be a file path - look for it path = os . path . expanduser ( key ) if os . path . isfile ( path ) : with open ( path ) as f : key = f . read ( ) . strip ( ) if not key . startswith ( SSH_KEY_TYPES ) : raise ValueError ( 'Invalid SSH Public Key' ) params = { 'ssh_key' : key , 'label' : label , } result = self . client . post ( '/profile/sshkeys' , data = params ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when uploading SSH Key!' , json = result ) ssh_key = SSHKey ( self . client , result [ 'id' ] , result ) return ssh_key | Uploads a new SSH Public Key to your profile This key can be used in later Linode deployments . | 200 | 21 |
18,052 | def client_create ( self , label = None ) : result = self . client . post ( '/longview/clients' , data = { "label" : label } ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when creating Longivew ' 'Client!' , json = result ) c = LongviewClient ( self . client , result [ 'id' ] , result ) return c | Creates a new LongviewClient optionally with a given label . | 91 | 13 |
18,053 | def events_mark_seen ( self , event ) : last_seen = event if isinstance ( event , int ) else event . id self . client . post ( '{}/seen' . format ( Event . api_endpoint ) , model = Event ( self . client , last_seen ) ) | Marks event as the last event we have seen . If event is an int it is treated as an event_id otherwise it should be an event object whose id will be used . | 65 | 37 |
18,054 | def settings ( self ) : result = self . client . get ( '/account/settings' ) if not 'managed' in result : raise UnexpectedResponseError ( 'Unexpected response when getting account settings!' , json = result ) s = AccountSettings ( self . client , result [ 'managed' ] , result ) return s | Resturns the account settings data for this acocunt . This is not a listing endpoint . | 68 | 20 |
18,055 | def oauth_client_create ( self , name , redirect_uri , * * kwargs ) : params = { "label" : name , "redirect_uri" : redirect_uri , } params . update ( kwargs ) result = self . client . post ( '/account/oauth-clients' , data = params ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when creating OAuth Client!' , json = result ) c = OAuthClient ( self . client , result [ 'id' ] , result ) return c | Make a new OAuth Client and return it | 124 | 9 |
18,056 | def transfer ( self ) : result = self . client . get ( '/account/transfer' ) if not 'used' in result : raise UnexpectedResponseError ( 'Unexpected response when getting Transfer Pool!' ) return MappedObject ( * * result ) | Returns a MappedObject containing the account s transfer pool data | 53 | 12 |
18,057 | def ip_allocate ( self , linode , public = True ) : result = self . client . post ( '/networking/ipv4/' , data = { "linode_id" : linode . id if isinstance ( linode , Base ) else linode , "type" : "ipv4" , "public" : public , } ) if not 'address' in result : raise UnexpectedResponseError ( 'Unexpected response when adding IPv4 address!' , json = result ) ip = IPAddress ( self . client , result [ 'address' ] , result ) return ip | Allocates an IP to a Instance you own . Additional IPs must be requested by opening a support ticket first . | 129 | 25 |
18,058 | def load ( self , target_type , target_id , target_parent_id = None ) : result = target_type . make_instance ( target_id , self , parent_id = target_parent_id ) result . _api_get ( ) return result | Constructs and immediately loads the object circumventing the lazy - loading scheme by immediately making an API request . Does not load related objects . | 58 | 27 |
18,059 | def _api_call ( self , endpoint , model = None , method = None , data = None , filters = None ) : if not self . token : raise RuntimeError ( "You do not have an API token!" ) if not method : raise ValueError ( "Method is required for API calls!" ) if model : endpoint = endpoint . format ( * * vars ( model ) ) url = '{}{}' . format ( self . base_url , endpoint ) headers = { 'Authorization' : "Bearer {}" . format ( self . token ) , 'Content-Type' : 'application/json' , 'User-Agent' : self . _user_agent , } if filters : headers [ 'X-Filter' ] = json . dumps ( filters ) body = None if data is not None : body = json . dumps ( data ) response = method ( url , headers = headers , data = body ) warning = response . headers . get ( 'Warning' , None ) if warning : logger . warning ( 'Received warning from server: {}' . format ( warning ) ) if 399 < response . status_code < 600 : j = None error_msg = '{}: ' . format ( response . status_code ) try : j = response . json ( ) if 'errors' in j . keys ( ) : for e in j [ 'errors' ] : error_msg += '{}; ' . format ( e [ 'reason' ] ) if 'reason' in e . keys ( ) else '' except : pass raise ApiError ( error_msg , status = response . status_code , json = j ) if response . status_code != 204 : j = response . json ( ) else : j = None # handle no response body return j | Makes a call to the linode api . Data should only be given if the method is POST or PUT and should be a dictionary | 374 | 28 |
18,060 | def image_create ( self , disk , label = None , description = None ) : params = { "disk_id" : disk . id if issubclass ( type ( disk ) , Base ) else disk , } if label is not None : params [ "label" ] = label if description is not None : params [ "description" ] = description result = self . post ( '/images' , data = params ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when creating an ' 'Image from disk {}' . format ( disk ) ) return Image ( self , result [ 'id' ] , result ) | Creates a new Image from a disk you own . | 136 | 11 |
18,061 | def nodebalancer_create ( self , region , * * kwargs ) : params = { "region" : region . id if isinstance ( region , Base ) else region , } params . update ( kwargs ) result = self . post ( '/nodebalancers' , data = params ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when creating Nodebalaner!' , json = result ) n = NodeBalancer ( self , result [ 'id' ] , result ) return n | Creates a new NodeBalancer in the given Region . | 113 | 12 |
18,062 | def domain_create ( self , domain , master = True , * * kwargs ) : params = { 'domain' : domain , 'type' : 'master' if master else 'slave' , } params . update ( kwargs ) result = self . post ( '/domains' , data = params ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when creating Domain!' , json = result ) d = Domain ( self , result [ 'id' ] , result ) return d | Registers a new Domain on the acting user s account . Make sure to point your registrar to Linode s nameservers so that Linode s DNS manager will correctly serve your domain . | 111 | 39 |
18,063 | def tag_create ( self , label , instances = None , domains = None , nodebalancers = None , volumes = None , entities = [ ] ) : linode_ids , nodebalancer_ids , domain_ids , volume_ids = [ ] , [ ] , [ ] , [ ] # filter input into lists of ids sorter = zip ( ( linode_ids , nodebalancer_ids , domain_ids , volume_ids ) , ( instances , nodebalancers , domains , volumes ) ) for id_list , input_list in sorter : # if we got something, we need to find its ID if input_list is not None : for cur in input_list : if isinstance ( cur , int ) : id_list . append ( cur ) else : id_list . append ( cur . id ) # filter entities into id lists too type_map = { Instance : linode_ids , NodeBalancer : nodebalancer_ids , Domain : domain_ids , Volume : volume_ids , } for e in entities : if type ( e ) in type_map : type_map [ type ( e ) ] . append ( e . id ) else : raise ValueError ( 'Unsupported entity type {}' . format ( type ( e ) ) ) # finally, omit all id lists that are empty params = { 'label' : label , 'linodes' : linode_ids or None , 'nodebalancers' : nodebalancer_ids or None , 'domains' : domain_ids or None , 'volumes' : volume_ids or None , } result = self . post ( '/tags' , data = params ) if not 'label' in result : raise UnexpectedResponseError ( 'Unexpected response when creating Tag!' , json = result ) t = Tag ( self , result [ 'label' ] , result ) return t | Creates a new Tag and optionally applies it to the given entities . | 399 | 14 |
18,064 | def volume_create ( self , label , region = None , linode = None , size = 20 , * * kwargs ) : if not ( region or linode ) : raise ValueError ( 'region or linode required!' ) params = { "label" : label , "size" : size , "region" : region . id if issubclass ( type ( region ) , Base ) else region , "linode_id" : linode . id if issubclass ( type ( linode ) , Base ) else linode , } params . update ( kwargs ) result = self . post ( '/volumes' , data = params ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when creating volume!' , json = result ) v = Volume ( self , result [ 'id' ] , result ) return v | Creates a new Block Storage Volume either in the given Region or attached to the given Instance . | 183 | 20 |
18,065 | def expire_token ( self , token ) : r = requests . post ( self . _login_uri ( "/oauth/token/expire" ) , data = { "client_id" : self . client_id , "client_secret" : self . client_secret , "token" : token , } ) if r . status_code != 200 : raise ApiError ( "Failed to expire token!" , r ) return True | Given a token makes a request to the authentication server to expire it immediately . This is considered a responsible way to log out a user . If you simply remove the session your application has for the user without expiring their token the user is not _really_ logged out . | 95 | 54 |
18,066 | def grants ( self ) : from linode_api4 . objects . account import UserGrants resp = self . _client . get ( '/profile/grants' ) # use special endpoint for restricted users grants = None if resp is not None : # if resp is None, we're unrestricted and do not have grants grants = UserGrants ( self . _client , self . username , resp ) return grants | Returns grants for the current user | 85 | 6 |
18,067 | def add_whitelist_entry ( self , address , netmask , note = None ) : result = self . _client . post ( "{}/whitelist" . format ( Profile . api_endpoint ) , data = { "address" : address , "netmask" : netmask , "note" : note , } ) if not 'id' in result : raise UnexpectedResponseError ( "Unexpected response creating whitelist entry!" ) return WhitelistEntry ( result [ 'id' ] , self . _client , json = result ) | Adds a new entry to this user s IP whitelist if enabled | 118 | 13 |
18,068 | def confirm_login_allowed ( self , user ) : if not user . is_active : raise forms . ValidationError ( self . error_messages [ 'inactive' ] , code = 'inactive' , ) | Controls whether the given User may log in . This is a policy setting independent of end - user authentication . This default behavior is to allow login by active users and reject login by inactive users . | 48 | 39 |
18,069 | def broken_chains ( samples , chains ) : samples = np . asarray ( samples ) if samples . ndim != 2 : raise ValueError ( "expected samples to be a numpy 2D array" ) num_samples , num_variables = samples . shape num_chains = len ( chains ) broken = np . zeros ( ( num_samples , num_chains ) , dtype = bool , order = 'F' ) for cidx , chain in enumerate ( chains ) : if isinstance ( chain , set ) : chain = list ( chain ) chain = np . asarray ( chain ) if chain . ndim > 1 : raise ValueError ( "chains should be 1D array_like objects" ) # chains of length 1, or 0 cannot be broken if len ( chain ) <= 1 : continue all_ = ( samples [ : , chain ] == 1 ) . all ( axis = 1 ) any_ = ( samples [ : , chain ] == 1 ) . any ( axis = 1 ) broken [ : , cidx ] = np . bitwise_xor ( all_ , any_ ) return broken | Find the broken chains . | 240 | 5 |
18,070 | def discard ( samples , chains ) : samples = np . asarray ( samples ) if samples . ndim != 2 : raise ValueError ( "expected samples to be a numpy 2D array" ) num_samples , num_variables = samples . shape num_chains = len ( chains ) broken = broken_chains ( samples , chains ) unbroken_idxs , = np . where ( ~ broken . any ( axis = 1 ) ) chain_variables = np . fromiter ( ( np . asarray ( tuple ( chain ) ) [ 0 ] if isinstance ( chain , set ) else np . asarray ( chain ) [ 0 ] for chain in chains ) , count = num_chains , dtype = int ) return samples [ np . ix_ ( unbroken_idxs , chain_variables ) ] , unbroken_idxs | Discard broken chains . | 181 | 5 |
18,071 | def majority_vote ( samples , chains ) : samples = np . asarray ( samples ) if samples . ndim != 2 : raise ValueError ( "expected samples to be a numpy 2D array" ) num_samples , num_variables = samples . shape num_chains = len ( chains ) unembedded = np . empty ( ( num_samples , num_chains ) , dtype = 'int8' , order = 'F' ) # determine if spin or binary. If samples are all 1, then either method works, so we use spin # because it is faster if samples . all ( ) : # spin-valued for cidx , chain in enumerate ( chains ) : # we just need the sign for spin. We don't use np.sign because in that can return 0 # and fixing the 0s is slow. unembedded [ : , cidx ] = 2 * ( samples [ : , chain ] . sum ( axis = 1 ) >= 0 ) - 1 else : # binary-valued for cidx , chain in enumerate ( chains ) : mid = len ( chain ) / 2 unembedded [ : , cidx ] = ( samples [ : , chain ] . sum ( axis = 1 ) >= mid ) return unembedded , np . arange ( num_samples ) | Use the most common element in broken chains . | 282 | 9 |
18,072 | def weighted_random ( samples , chains ) : samples = np . asarray ( samples ) if samples . ndim != 2 : raise ValueError ( "expected samples to be a numpy 2D array" ) # it sufficies to choose a random index from each chain and use that to construct the matrix idx = [ np . random . choice ( chain ) for chain in chains ] num_samples , num_variables = samples . shape return samples [ : , idx ] , np . arange ( num_samples ) | Determine the sample values of chains by weighed random choice . | 113 | 13 |
18,073 | def validate_anneal_schedule ( self , anneal_schedule ) : if 'anneal_schedule' not in self . parameters : raise RuntimeError ( "anneal_schedule is not an accepted parameter for this sampler" ) properties = self . properties try : min_anneal_time , max_anneal_time = properties [ 'annealing_time_range' ] max_anneal_schedule_points = properties [ 'max_anneal_schedule_points' ] except KeyError : raise RuntimeError ( "annealing_time_range and max_anneal_schedule_points are not properties of this solver" ) # The number of points must be >= 2. # The upper bound is system-dependent; check the max_anneal_schedule_points property if not isinstance ( anneal_schedule , list ) : raise TypeError ( "anneal_schedule should be a list" ) elif len ( anneal_schedule ) < 2 or len ( anneal_schedule ) > max_anneal_schedule_points : msg = ( "anneal_schedule must contain between 2 and {} points (contains {})" ) . format ( max_anneal_schedule_points , len ( anneal_schedule ) ) raise ValueError ( msg ) try : t_list , s_list = zip ( * anneal_schedule ) except ValueError : raise ValueError ( "anneal_schedule should be a list of 2-tuples" ) # Time t must increase for all points in the schedule. if not all ( tail_t < lead_t for tail_t , lead_t in zip ( t_list , t_list [ 1 : ] ) ) : raise ValueError ( "Time t must increase for all points in the schedule" ) # max t cannot exceed max_anneal_time if t_list [ - 1 ] > max_anneal_time : raise ValueError ( "schedule cannot be longer than the maximum anneal time of {}" . format ( max_anneal_time ) ) start_s , end_s = s_list [ 0 ] , s_list [ - 1 ] if end_s != 1 : raise ValueError ( "In the final point, anneal fraction s must equal 1." ) if start_s == 1 : # reverse annealing pass elif start_s == 0 : # forward annealing, s must monotonically increase. if not all ( tail_s <= lead_s for tail_s , lead_s in zip ( s_list , s_list [ 1 : ] ) ) : raise ValueError ( "For forward anneals, anneal fraction s must monotonically increase" ) else : msg = ( "In the first point, anneal fraction s must equal 0 for forward annealing or " "1 for reverse annealing" ) raise ValueError ( msg ) # finally check the slope abs(slope) < 1/min_anneal_time max_slope = 1.0 / min_anneal_time for ( t0 , s0 ) , ( t1 , s1 ) in zip ( anneal_schedule , anneal_schedule [ 1 : ] ) : if abs ( ( s0 - s1 ) / ( t0 - t1 ) ) > max_slope : raise ValueError ( "the maximum slope cannot exceed {}" . format ( max_slope ) ) | Raise an exception if the specified schedule is invalid for the sampler . | 760 | 15 |
18,074 | def target_to_source ( target_adjacency , embedding ) : # the nodes in the source adjacency are just the keys of the embedding source_adjacency = { v : set ( ) for v in embedding } # we need the mapping from each node in the target to its source node reverse_embedding = { } for v , chain in iteritems ( embedding ) : for u in chain : if u in reverse_embedding : raise ValueError ( "target node {} assigned to more than one source node" . format ( u ) ) reverse_embedding [ u ] = v # v is node in target, n node in source for v , n in iteritems ( reverse_embedding ) : neighbors = target_adjacency [ v ] # u is node in target for u in neighbors : # some nodes might not be assigned to chains if u not in reverse_embedding : continue # m is node in source m = reverse_embedding [ u ] if m == n : continue source_adjacency [ n ] . add ( m ) source_adjacency [ m ] . add ( n ) return source_adjacency | Derive the source adjacency from an embedding and target adjacency . | 248 | 17 |
18,075 | def chain_to_quadratic ( chain , target_adjacency , chain_strength ) : quadratic = { } # we will be adding the edges that make the chain here # do a breadth first search seen = set ( ) try : next_level = { next ( iter ( chain ) ) } except StopIteration : raise ValueError ( "chain must have at least one variable" ) while next_level : this_level = next_level next_level = set ( ) for v in this_level : if v not in seen : seen . add ( v ) for u in target_adjacency [ v ] : if u not in chain : continue next_level . add ( u ) if u != v and ( u , v ) not in quadratic : quadratic [ ( v , u ) ] = - chain_strength if len ( chain ) != len ( seen ) : raise ValueError ( '{} is not a connected chain' . format ( chain ) ) return quadratic | Determine the quadratic biases that induce the given chain . | 215 | 14 |
18,076 | def chain_break_frequency ( samples_like , embedding ) : if isinstance ( samples_like , dimod . SampleSet ) : labels = samples_like . variables samples = samples_like . record . sample num_occurrences = samples_like . record . num_occurrences else : samples , labels = dimod . as_samples ( samples_like ) num_occurrences = np . ones ( samples . shape [ 0 ] ) if not all ( v == idx for idx , v in enumerate ( labels ) ) : labels_to_idx = { v : idx for idx , v in enumerate ( labels ) } embedding = { v : { labels_to_idx [ u ] for u in chain } for v , chain in embedding . items ( ) } if not embedding : return { } variables , chains = zip ( * embedding . items ( ) ) broken = broken_chains ( samples , chains ) return { v : float ( np . average ( broken [ : , cidx ] , weights = num_occurrences ) ) for cidx , v in enumerate ( variables ) } | Determine the frequency of chain breaks in the given samples . | 249 | 13 |
18,077 | def edgelist_to_adjacency ( edgelist ) : adjacency = dict ( ) for u , v in edgelist : if u in adjacency : adjacency [ u ] . add ( v ) else : adjacency [ u ] = { v } if v in adjacency : adjacency [ v ] . add ( u ) else : adjacency [ v ] = { u } return adjacency | Converts an iterator of edges to an adjacency dict . | 96 | 13 |
18,078 | def sample ( self , bqm , * * kwargs ) : # apply the embeddings to the given problem to tile it across the child sampler embedded_bqm = dimod . BinaryQuadraticModel . empty ( bqm . vartype ) __ , __ , target_adjacency = self . child . structure for embedding in self . embeddings : embedded_bqm . update ( dwave . embedding . embed_bqm ( bqm , embedding , target_adjacency ) ) # solve the problem on the child system tiled_response = self . child . sample ( embedded_bqm , * * kwargs ) responses = [ ] for embedding in self . embeddings : embedding = { v : chain for v , chain in embedding . items ( ) if v in bqm . variables } responses . append ( dwave . embedding . unembed_sampleset ( tiled_response , embedding , bqm ) ) return dimod . concatenate ( responses ) | Sample from the specified binary quadratic model . | 230 | 10 |
18,079 | def cache_connect ( database = None ) : if database is None : database = cache_file ( ) if os . path . isfile ( database ) : # just connect to the database as-is conn = sqlite3 . connect ( database ) else : # we need to populate the database conn = sqlite3 . connect ( database ) conn . executescript ( schema ) with conn as cur : # turn on foreign keys, allows deletes to cascade. cur . execute ( "PRAGMA foreign_keys = ON;" ) conn . row_factory = sqlite3 . Row return conn | Returns a connection object to a sqlite database . | 124 | 10 |
18,080 | def insert_chain ( cur , chain , encoded_data = None ) : if encoded_data is None : encoded_data = { } if 'nodes' not in encoded_data : encoded_data [ 'nodes' ] = json . dumps ( sorted ( chain ) , separators = ( ',' , ':' ) ) if 'chain_length' not in encoded_data : encoded_data [ 'chain_length' ] = len ( chain ) insert = "INSERT OR IGNORE INTO chain(chain_length, nodes) VALUES (:chain_length, :nodes);" cur . execute ( insert , encoded_data ) | Insert a chain into the cache . | 137 | 7 |
18,081 | def iter_chain ( cur ) : select = "SELECT nodes FROM chain" for nodes , in cur . execute ( select ) : yield json . loads ( nodes ) | Iterate over all of the chains in the database . | 34 | 11 |
18,082 | def insert_system ( cur , system_name , encoded_data = None ) : if encoded_data is None : encoded_data = { } if 'system_name' not in encoded_data : encoded_data [ 'system_name' ] = system_name insert = "INSERT OR IGNORE INTO system(system_name) VALUES (:system_name);" cur . execute ( insert , encoded_data ) | Insert a system name into the cache . | 91 | 8 |
18,083 | def insert_flux_bias ( cur , chain , system , flux_bias , chain_strength , encoded_data = None ) : if encoded_data is None : encoded_data = { } insert_chain ( cur , chain , encoded_data ) insert_system ( cur , system , encoded_data ) if 'flux_bias' not in encoded_data : encoded_data [ 'flux_bias' ] = _encode_real ( flux_bias ) if 'chain_strength' not in encoded_data : encoded_data [ 'chain_strength' ] = _encode_real ( chain_strength ) if 'insert_time' not in encoded_data : encoded_data [ 'insert_time' ] = datetime . datetime . now ( ) insert = """ INSERT OR REPLACE INTO flux_bias(chain_id, system_id, insert_time, flux_bias, chain_strength) SELECT chain.id, system.id, :insert_time, :flux_bias, :chain_strength FROM chain, system WHERE chain.chain_length = :chain_length AND chain.nodes = :nodes AND system.system_name = :system_name; """ cur . execute ( insert , encoded_data ) | Insert a flux bias offset into the cache . | 278 | 9 |
18,084 | def get_flux_biases_from_cache ( cur , chains , system_name , chain_strength , max_age = 3600 ) : select = """ SELECT flux_bias FROM flux_bias_view WHERE chain_length = :chain_length AND nodes = :nodes AND chain_strength = :chain_strength AND system_name = :system_name AND insert_time >= :time_limit; """ encoded_data = { 'chain_strength' : _encode_real ( chain_strength ) , 'system_name' : system_name , 'time_limit' : datetime . datetime . now ( ) + datetime . timedelta ( seconds = - max_age ) } flux_biases = { } for chain in chains : encoded_data [ 'chain_length' ] = len ( chain ) encoded_data [ 'nodes' ] = json . dumps ( sorted ( chain ) , separators = ( ',' , ':' ) ) row = cur . execute ( select , encoded_data ) . fetchone ( ) if row is None : raise MissingFluxBias flux_bias = _decode_real ( * row ) if flux_bias == 0 : continue flux_biases . update ( { v : flux_bias for v in chain } ) return flux_biases | Determine the flux biases for all of the the given chains system and chain strength . | 287 | 18 |
18,085 | def insert_graph ( cur , nodelist , edgelist , encoded_data = None ) : if encoded_data is None : encoded_data = { } if 'num_nodes' not in encoded_data : encoded_data [ 'num_nodes' ] = len ( nodelist ) if 'num_edges' not in encoded_data : encoded_data [ 'num_edges' ] = len ( edgelist ) if 'edges' not in encoded_data : encoded_data [ 'edges' ] = json . dumps ( edgelist , separators = ( ',' , ':' ) ) insert = """ INSERT OR IGNORE INTO graph(num_nodes, num_edges, edges) VALUES (:num_nodes, :num_edges, :edges); """ cur . execute ( insert , encoded_data ) | Insert a graph into the cache . | 188 | 7 |
18,086 | def select_embedding_from_tag ( cur , embedding_tag , target_nodelist , target_edgelist ) : encoded_data = { 'num_nodes' : len ( target_nodelist ) , 'num_edges' : len ( target_edgelist ) , 'edges' : json . dumps ( target_edgelist , separators = ( ',' , ':' ) ) , 'tag' : embedding_tag } select = """ SELECT source_node, chain FROM embedding_component_view WHERE embedding_tag = :tag AND target_edges = :edges AND target_num_nodes = :num_nodes AND target_num_edges = :num_edges """ embedding = { v : json . loads ( chain ) for v , chain in cur . execute ( select , encoded_data ) } return embedding | Select an embedding from the given tag and target graph . | 194 | 12 |
18,087 | def select_embedding_from_source ( cur , source_nodelist , source_edgelist , target_nodelist , target_edgelist ) : encoded_data = { 'target_num_nodes' : len ( target_nodelist ) , 'target_num_edges' : len ( target_edgelist ) , 'target_edges' : json . dumps ( target_edgelist , separators = ( ',' , ':' ) ) , 'source_num_nodes' : len ( source_nodelist ) , 'source_num_edges' : len ( source_edgelist ) , 'source_edges' : json . dumps ( source_edgelist , separators = ( ',' , ':' ) ) } select = """ SELECT source_node, chain FROM embedding_component_view WHERE source_num_edges = :source_num_edges AND source_edges = :source_edges AND source_num_nodes = :source_num_nodes AND target_num_edges = :target_num_edges AND target_edges = :target_edges AND target_num_nodes = :target_num_nodes """ embedding = { v : json . loads ( chain ) for v , chain in cur . execute ( select , encoded_data ) } return embedding | Select an embedding from the source graph and target graph . | 302 | 12 |
18,088 | def draw_chimera_bqm ( bqm , width = None , height = None ) : linear = bqm . linear . keys ( ) quadratic = bqm . quadratic . keys ( ) if width is None and height is None : # Create a graph large enough to fit the input networkx graph. graph_size = ceil ( sqrt ( ( max ( linear ) + 1 ) / 8.0 ) ) width = graph_size height = graph_size if not width or not height : raise Exception ( "Both dimensions must be defined, not just one." ) # A background image of the same size is created to show the complete graph. G0 = chimera_graph ( height , width , 4 ) G = chimera_graph ( height , width , 4 ) # Check if input graph is chimera graph shaped, by making sure that no edges are invalid. # Invalid edges can also appear if the size of the chimera graph is incompatible with the input graph in cell dimensions. non_chimera_nodes = [ ] non_chimera_edges = [ ] for node in linear : if not node in G . nodes : non_chimera_nodes . append ( node ) for edge in quadratic : if not edge in G . edges : non_chimera_edges . append ( edge ) linear_set = set ( linear ) g_node_set = set ( G . nodes ) quadratic_set = set ( map ( frozenset , quadratic ) ) g_edge_set = set ( map ( frozenset , G . edges ) ) non_chimera_nodes = linear_set - g_node_set non_chimera_edges = quadratic_set - g_edge_set if non_chimera_nodes or non_chimera_edges : raise Exception ( "Input graph is not a chimera graph: Nodes: %s Edges: %s" % ( non_chimera_nodes , non_chimera_edges ) ) # Get lists of nodes and edges to remove from the complete graph to turn the complete graph into your graph. remove_nodes = list ( g_node_set - linear_set ) remove_edges = list ( g_edge_set - quadratic_set ) # Remove the nodes and edges from the graph. for edge in remove_edges : G . remove_edge ( * edge ) for node in remove_nodes : G . remove_node ( node ) node_size = 100 # Draw the complete chimera graph as the background. draw_chimera ( G0 , node_size = node_size * 0.5 , node_color = 'black' , edge_color = 'black' ) # Draw your graph over the complete graph to show the connectivity. draw_chimera ( G , node_size = node_size , linear_biases = bqm . linear , quadratic_biases = bqm . quadratic , width = 3 ) return | Draws a Chimera Graph representation of a Binary Quadratic Model . | 666 | 14 |
18,089 | def embed_bqm ( source_bqm , embedding , target_adjacency , chain_strength = 1.0 , smear_vartype = None ) : if smear_vartype is dimod . SPIN and source_bqm . vartype is dimod . BINARY : return embed_bqm ( source_bqm . spin , embedding , target_adjacency , chain_strength = chain_strength , smear_vartype = None ) . binary elif smear_vartype is dimod . BINARY and source_bqm . vartype is dimod . SPIN : return embed_bqm ( source_bqm . binary , embedding , target_adjacency , chain_strength = chain_strength , smear_vartype = None ) . spin # create a new empty binary quadratic model with the same class as source_bqm target_bqm = source_bqm . empty ( source_bqm . vartype ) # add the offset target_bqm . add_offset ( source_bqm . offset ) # start with the linear biases, spreading the source bias equally over the target variables in # the chain for v , bias in iteritems ( source_bqm . linear ) : if v in embedding : chain = embedding [ v ] else : raise MissingChainError ( v ) if any ( u not in target_adjacency for u in chain ) : raise InvalidNodeError ( v , next ( u not in target_adjacency for u in chain ) ) b = bias / len ( chain ) target_bqm . add_variables_from ( { u : b for u in chain } ) # next up the quadratic biases, spread the quadratic biases evenly over the available # interactions for ( u , v ) , bias in iteritems ( source_bqm . quadratic ) : available_interactions = { ( s , t ) for s in embedding [ u ] for t in embedding [ v ] if s in target_adjacency [ t ] } if not available_interactions : raise MissingEdgeError ( u , v ) b = bias / len ( available_interactions ) target_bqm . add_interactions_from ( ( u , v , b ) for u , v in available_interactions ) for chain in itervalues ( embedding ) : # in the case where the chain has length 1, there are no chain quadratic biases, but we # none-the-less want the chain variables to appear in the target_bqm if len ( chain ) == 1 : v , = chain target_bqm . add_variable ( v , 0.0 ) continue quadratic_chain_biases = chain_to_quadratic ( chain , target_adjacency , chain_strength ) target_bqm . add_interactions_from ( quadratic_chain_biases , vartype = dimod . SPIN ) # these are spin # add the energy for satisfied chains to the offset energy_diff = - sum ( itervalues ( quadratic_chain_biases ) ) target_bqm . add_offset ( energy_diff ) return target_bqm | Embed a binary quadratic model onto a target graph . | 719 | 13 |
18,090 | def embed_ising ( source_h , source_J , embedding , target_adjacency , chain_strength = 1.0 ) : source_bqm = dimod . BinaryQuadraticModel . from_ising ( source_h , source_J ) target_bqm = embed_bqm ( source_bqm , embedding , target_adjacency , chain_strength = chain_strength ) target_h , target_J , __ = target_bqm . to_ising ( ) return target_h , target_J | Embed an Ising problem onto a target graph . | 122 | 11 |
18,091 | def embed_qubo ( source_Q , embedding , target_adjacency , chain_strength = 1.0 ) : source_bqm = dimod . BinaryQuadraticModel . from_qubo ( source_Q ) target_bqm = embed_bqm ( source_bqm , embedding , target_adjacency , chain_strength = chain_strength ) target_Q , __ = target_bqm . to_qubo ( ) return target_Q | Embed a QUBO onto a target graph . | 109 | 10 |
18,092 | def unembed_sampleset ( target_sampleset , embedding , source_bqm , chain_break_method = None , chain_break_fraction = False ) : if chain_break_method is None : chain_break_method = majority_vote variables = list ( source_bqm ) try : chains = [ embedding [ v ] for v in variables ] except KeyError : raise ValueError ( "given bqm does not match the embedding" ) chain_idxs = [ [ target_sampleset . variables . index [ v ] for v in chain ] for chain in chains ] record = target_sampleset . record unembedded , idxs = chain_break_method ( record . sample , chain_idxs ) # dev note: this is a bug in dimod that empty unembedded is not handled, # in the future this try-except can be removed try : energies = source_bqm . energies ( ( unembedded , variables ) ) except ValueError : datatypes = [ ( 'sample' , np . dtype ( np . int8 ) , ( len ( variables ) , ) ) , ( 'energy' , np . float ) ] datatypes . extend ( ( name , record [ name ] . dtype , record [ name ] . shape [ 1 : ] ) for name in record . dtype . names if name not in { 'sample' , 'energy' } ) if chain_break_fraction : datatypes . append ( ( 'chain_break_fraction' , np . float64 ) ) # there are no samples so everything is empty data = np . rec . array ( np . empty ( 0 , dtype = datatypes ) ) return dimod . SampleSet ( data , variables , target_sampleset . info . copy ( ) , target_sampleset . vartype ) reserved = { 'sample' , 'energy' } vectors = { name : record [ name ] [ idxs ] for name in record . dtype . names if name not in reserved } if chain_break_fraction : vectors [ 'chain_break_fraction' ] = broken_chains ( record . sample , chain_idxs ) . mean ( axis = 1 ) [ idxs ] return dimod . SampleSet . from_samples ( ( unembedded , variables ) , target_sampleset . vartype , energy = energies , info = target_sampleset . info . copy ( ) , * * vectors ) | Unembed the samples set . | 540 | 6 |
18,093 | def sample ( self , bqm , chain_strength = 1.0 , chain_break_fraction = True , * * parameters ) : if self . embedding is None : # Find embedding child = self . child # Solve the problem on the child system __ , target_edgelist , target_adjacency = child . structure source_edgelist = list ( bqm . quadratic ) + [ ( v , v ) for v in bqm . linear ] # Add self-loops for single variables embedding = minorminer . find_embedding ( source_edgelist , target_edgelist ) # Initialize properties that need embedding super ( LazyFixedEmbeddingComposite , self ) . _set_graph_related_init ( embedding = embedding ) return super ( LazyFixedEmbeddingComposite , self ) . sample ( bqm , chain_strength = chain_strength , chain_break_fraction = chain_break_fraction , * * parameters ) | Sample the binary quadratic model . | 225 | 8 |
18,094 | def _accumulate_random ( count , found , oldthing , newthing ) : if randint ( 1 , count + found ) <= found : return count + found , newthing else : return count + found , oldthing | This performs on - line random selection . | 48 | 8 |
18,095 | def _bulk_to_linear ( M , N , L , qubits ) : return [ 2 * L * N * x + 2 * L * y + L * u + k for x , y , u , k in qubits ] | Converts a list of chimera coordinates to linear indices . | 52 | 12 |
18,096 | def _to_linear ( M , N , L , q ) : ( x , y , u , k ) = q return 2 * L * N * x + 2 * L * y + L * u + k | Converts a qubit in chimera coordinates to its linear index . | 46 | 14 |
18,097 | def _bulk_to_chimera ( M , N , L , qubits ) : return [ ( q // N // L // 2 , ( q // L // 2 ) % N , ( q // L ) % 2 , q % L ) for q in qubits ] | Converts a list of linear indices to chimera coordinates . | 60 | 12 |
18,098 | def _to_chimera ( M , N , L , q ) : return ( q // N // L // 2 , ( q // L // 2 ) % N , ( q // L ) % 2 , q % L ) | Converts a qubit s linear index to chimera coordinates . | 49 | 13 |
18,099 | def _compute_vline_scores ( self ) : M , N , L = self . M , self . N , self . L vline_score = { } for x in range ( M ) : laststart = [ 0 if ( x , 0 , 1 , k ) in self else None for k in range ( L ) ] for y in range ( N ) : block = [ 0 ] * ( y + 1 ) for k in range ( L ) : if ( x , y , 1 , k ) not in self : laststart [ k ] = None elif laststart [ k ] is None : laststart [ k ] = y block [ y ] += 1 elif y and ( x , y , 1 , k ) not in self [ x , y - 1 , 1 , k ] : laststart [ k ] = y else : for y1 in range ( laststart [ k ] , y + 1 ) : block [ y1 ] += 1 for y1 in range ( y + 1 ) : vline_score [ x , y1 , y ] = block [ y1 ] self . _vline_score = vline_score | Does the hard work to prepare vline_score . | 246 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.