idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
23,700
def relabel_variables ( self , mapping , inplace = True ) : if not inplace : return self . copy ( ) . relabel_variables ( mapping , inplace = True ) try : old_labels = set ( mapping ) new_labels = set ( mapping . values ( ) ) except TypeError : raise ValueError ( "mapping targets must be hashable objects" ) variables =...
Relabel variables of a binary polynomial as specified by mapping .
23,701
def scale ( self , scalar , ignored_terms = None ) : if ignored_terms is None : ignored_terms = set ( ) else : ignored_terms = { asfrozenset ( term ) for term in ignored_terms } for term in self : if term not in ignored_terms : self [ term ] *= scalar
Multiply the polynomial by the given scalar .
23,702
def from_hising ( cls , h , J , offset = None ) : poly = { ( k , ) : v for k , v in h . items ( ) } poly . update ( J ) if offset is not None : poly [ frozenset ( [ ] ) ] = offset return cls ( poly , Vartype . SPIN )
Construct a binary polynomial from a higher - order Ising problem .
23,703
def to_hising ( self ) : if self . vartype is Vartype . BINARY : return self . to_spin ( ) . to_hising ( ) h = { } J = { } offset = 0 for term , bias in self . items ( ) : if len ( term ) == 0 : offset += bias elif len ( term ) == 1 : v , = term h [ v ] = bias else : J [ tuple ( term ) ] = bias return h , J , offset
Construct a higher - order Ising problem from a binary polynomial .
23,704
def greedy_coloring ( adj ) : coloring = { } colors = { } possible_colors = { n : set ( range ( len ( adj ) ) ) for n in adj } while possible_colors : n = min ( possible_colors , key = lambda n : len ( possible_colors [ n ] ) ) color = min ( possible_colors [ n ] ) coloring [ n ] = color if color not in colors : colors...
Determines a vertex coloring .
23,705
def sample ( self , bqm , beta_range = None , num_reads = 10 , num_sweeps = 1000 ) : if not isinstance ( num_reads , int ) : raise TypeError ( "'samples' should be a positive integer" ) if num_reads < 1 : raise ValueError ( "'samples' should be a positive integer" ) h , J , offset = bqm . to_ising ( ) samples = [ ] ene...
Sample from low - energy spin states using simulated annealing .
23,706
def _scale_back_response ( bqm , response , scalar , ignored_interactions , ignored_variables , ignore_offset ) : if len ( ignored_interactions ) + len ( ignored_variables ) + ignore_offset == 0 : response . record . energy = np . divide ( response . record . energy , scalar ) else : response . record . energy = bqm . ...
Helper function to scale back the response of sample method
23,707
def _check_params ( ignored_variables , ignored_interactions ) : if ignored_variables is None : ignored_variables = set ( ) elif not isinstance ( ignored_variables , abc . Container ) : ignored_variables = set ( ignored_variables ) if ignored_interactions is None : ignored_interactions = set ( ) elif not isinstance ( i...
Helper for sample methods
23,708
def _calc_norm_coeff ( h , J , bias_range , quadratic_range , ignored_variables , ignored_interactions ) : if ignored_variables is None or ignored_interactions is None : raise ValueError ( 'ignored interactions or variables cannot be None' ) def parse_range ( r ) : if isinstance ( r , Number ) : return - abs ( r ) , ab...
Helper function to calculate normalization coefficient
23,709
def _scaled_bqm ( bqm , scalar , bias_range , quadratic_range , ignored_variables , ignored_interactions , ignore_offset ) : bqm_copy = bqm . copy ( ) if scalar is None : scalar = _calc_norm_coeff ( bqm_copy . linear , bqm_copy . quadratic , bias_range , quadratic_range , ignored_variables , ignored_interactions ) bqm_...
Helper function of sample for scaling
23,710
def sample ( self , bqm , scalar = None , bias_range = 1 , quadratic_range = None , ignored_variables = None , ignored_interactions = None , ignore_offset = False , ** parameters ) : ignored_variables , ignored_interactions = _check_params ( ignored_variables , ignored_interactions ) child = self . child bqm_copy = _sc...
Scale and sample from the provided binary quadratic model .
23,711
def sample_ising ( self , h , J , offset = 0 , scalar = None , bias_range = 1 , quadratic_range = None , ignored_variables = None , ignored_interactions = None , ignore_offset = False , ** parameters ) : if any ( len ( inter ) > 2 for inter in J ) : import warnings msg = ( "Support for higher order Ising models in Scal...
Scale and sample from the problem provided by h J offset
23,712
def chimera_anticluster ( m , n = None , t = 4 , multiplier = 3.0 , cls = BinaryQuadraticModel , subgraph = None , seed = None ) : if seed is None : seed = numpy . random . randint ( 2 ** 32 , dtype = np . uint32 ) r = numpy . random . RandomState ( seed ) m = int ( m ) if n is None : n = m else : n = int ( n ) t = int...
Generate an anticluster problem on a Chimera lattice .
23,713
def dump ( bqm , fp , vartype_header = False ) : for triplet in _iter_triplets ( bqm , vartype_header ) : fp . write ( '%s\n' % triplet )
Dump a binary quadratic model to a string in COOrdinate format .
23,714
def loads ( s , cls = BinaryQuadraticModel , vartype = None ) : return load ( s . split ( '\n' ) , cls = cls , vartype = vartype )
Load a COOrdinate formatted binary quadratic model from a string .
23,715
def load ( fp , cls = BinaryQuadraticModel , vartype = None ) : pattern = re . compile ( _LINE_REGEX ) vartype_pattern = re . compile ( _VARTYPE_HEADER_REGEX ) triplets = [ ] for line in fp : triplets . extend ( pattern . findall ( line ) ) vt = vartype_pattern . findall ( line ) if vt : if vartype is None : vartype = ...
Load a COOrdinate formatted binary quadratic model from a file .
23,716
def remove_variable ( self , v ) : if v not in self : return adj = self . adj while adj [ v ] : self . remove_interaction ( v , next ( iter ( adj [ v ] ) ) ) del self . linear [ v ] try : del self . _counterpart if self . vartype is not Vartype . BINARY and hasattr ( self , '_binary' ) : del self . _binary elif self . ...
Remove variable v and all its interactions from a binary quadratic model .
23,717
def remove_interaction ( self , u , v ) : try : del self . quadratic [ ( u , v ) ] except KeyError : return try : del self . _counterpart if self . vartype is not Vartype . BINARY and hasattr ( self , '_binary' ) : del self . _binary elif self . vartype is not Vartype . SPIN and hasattr ( self , '_spin' ) : del self . ...
Remove interaction of variables u v from a binary quadratic model .
23,718
def remove_interactions_from ( self , interactions ) : for u , v in interactions : self . remove_interaction ( u , v )
Remove all specified interactions from the binary quadratic model .
23,719
def add_offset ( self , offset ) : self . offset += offset try : self . _counterpart . add_offset ( offset ) except AttributeError : pass
Add specified value to the offset of a binary quadratic model .
23,720
def scale ( self , scalar , ignored_variables = None , ignored_interactions = None , ignore_offset = False ) : if ignored_variables is None : ignored_variables = set ( ) elif not isinstance ( ignored_variables , abc . Container ) : ignored_variables = set ( ignored_variables ) if ignored_interactions is None : ignored_...
Multiply by the specified scalar all the biases and offset of a binary quadratic model .
23,721
def fix_variable ( self , v , value ) : adj = self . adj linear = self . linear if value not in self . vartype . value : raise ValueError ( "expected value to be in {}, received {} instead" . format ( self . vartype . value , value ) ) removed_interactions = [ ] for u in adj [ v ] : self . add_variable ( u , value * ad...
Fix the value of a variable and remove it from a binary quadratic model .
23,722
def fix_variables ( self , fixed ) : for v , val in fixed . items ( ) : self . fix_variable ( v , val )
Fix the value of the variables and remove it from a binary quadratic model .
23,723
def flip_variable ( self , v ) : adj = self . adj linear = self . linear quadratic = self . quadratic if v not in adj : return if self . vartype is Vartype . SPIN : linear [ v ] *= - 1. for u in adj [ v ] : adj [ v ] [ u ] *= - 1. adj [ u ] [ v ] *= - 1. if ( u , v ) in quadratic : quadratic [ ( u , v ) ] *= - 1. elif ...
Flip variable v in a binary quadratic model .
23,724
def update ( self , bqm , ignore_info = True ) : self . add_variables_from ( bqm . linear , vartype = bqm . vartype ) self . add_interactions_from ( bqm . quadratic , vartype = bqm . vartype ) self . add_offset ( bqm . offset ) if not ignore_info : self . info . update ( bqm . info )
Update one binary quadratic model from another .
23,725
def contract_variables ( self , u , v ) : adj = self . adj if u not in adj : raise ValueError ( "{} is not a variable in the binary quadratic model" . format ( u ) ) if v not in adj : raise ValueError ( "{} is not a variable in the binary quadratic model" . format ( v ) ) if v in adj [ u ] : if self . vartype is Vartyp...
Enforce u v being the same variable in a binary quadratic model .
23,726
def relabel_variables ( self , mapping , inplace = True ) : try : old_labels = set ( mapping ) new_labels = set ( itervalues ( mapping ) ) except TypeError : raise ValueError ( "mapping targets must be hashable objects" ) for v in new_labels : if v in self . linear and v not in old_labels : raise ValueError ( ( 'A vari...
Relabel variables of a binary quadratic model as specified by mapping .
23,727
def change_vartype ( self , vartype , inplace = True ) : if not inplace : new_model = BinaryQuadraticModel ( { } , { } , 0.0 , vartype ) new_model . add_variables_from ( self . linear , vartype = self . vartype ) new_model . add_interactions_from ( self . quadratic , vartype = self . vartype ) new_model . add_offset ( ...
Create a binary quadratic model with the specified vartype .
23,728
def spin_to_binary ( linear , quadratic , offset ) : new_linear = { v : 2. * bias for v , bias in iteritems ( linear ) } new_quadratic = { } for ( u , v ) , bias in iteritems ( quadratic ) : new_quadratic [ ( u , v ) ] = 4. * bias new_linear [ u ] -= 2. * bias new_linear [ v ] -= 2. * bias offset += sum ( itervalues ( ...
convert linear quadratic and offset from spin to binary . Does no checking of vartype . Copies all of the values into new objects .
23,729
def binary_to_spin ( linear , quadratic , offset ) : h = { } J = { } linear_offset = 0.0 quadratic_offset = 0.0 for u , bias in iteritems ( linear ) : h [ u ] = .5 * bias linear_offset += bias for ( u , v ) , bias in iteritems ( quadratic ) : J [ ( u , v ) ] = .25 * bias h [ u ] += .25 * bias h [ v ] += .25 * bias quad...
convert linear quadratic and offset from binary to spin . Does no checking of vartype . Copies all of the values into new objects .
23,730
def copy ( self ) : return BinaryQuadraticModel ( self . linear , self . quadratic , self . offset , self . vartype , ** self . info )
Create a copy of a BinaryQuadraticModel .
23,731
def energy ( self , sample ) : linear = self . linear quadratic = self . quadratic if isinstance ( sample , SampleView ) : sample = dict ( sample ) en = self . offset en += sum ( linear [ v ] * sample [ v ] for v in linear ) en += sum ( sample [ u ] * sample [ v ] * quadratic [ ( u , v ) ] for u , v in quadratic ) retu...
Determine the energy of the specified sample of a binary quadratic model .
23,732
def energies ( self , samples_like , dtype = np . float ) : samples , labels = as_samples ( samples_like ) if all ( v == idx for idx , v in enumerate ( labels ) ) : ldata , ( irow , icol , qdata ) , offset = self . to_numpy_vectors ( dtype = dtype ) else : ldata , ( irow , icol , qdata ) , offset = self . to_numpy_vect...
Determine the energies of the given samples .
23,733
def to_coo ( self , fp = None , vartype_header = False ) : import dimod . serialization . coo as coo if fp is None : return coo . dumps ( self , vartype_header ) else : coo . dump ( self , fp , vartype_header )
Serialize the binary quadratic model to a COOrdinate_ format encoding .
23,734
def from_coo ( cls , obj , vartype = None ) : import dimod . serialization . coo as coo if isinstance ( obj , str ) : return coo . loads ( obj , cls = cls , vartype = vartype ) return coo . load ( obj , cls = cls , vartype = vartype )
Deserialize a binary quadratic model from a COOrdinate_ format encoding .
23,735
def to_serializable ( self , use_bytes = False , bias_dtype = np . float32 , bytes_type = bytes ) : from dimod . package_info import __version__ schema_version = "2.0.0" try : variables = sorted ( self . variables ) except TypeError : variables = list ( self . variables ) num_variables = len ( variables ) index_dtype =...
Convert the binary quadratic model to a serializable object .
23,736
def from_serializable ( cls , obj ) : if obj . get ( "version" , { "bqm_schema" : "1.0.0" } ) [ "bqm_schema" ] != "2.0.0" : return cls . _from_serializable_v1 ( obj ) variables = [ tuple ( v ) if isinstance ( v , list ) else v for v in obj [ "variable_labels" ] ] if obj [ "use_bytes" ] : ldata = bytes2array ( obj [ "li...
Deserialize a binary quadratic model .
23,737
def to_networkx_graph ( self , node_attribute_name = 'bias' , edge_attribute_name = 'bias' ) : import networkx as nx BQM = nx . Graph ( ) BQM . add_nodes_from ( ( ( v , { node_attribute_name : bias , 'vartype' : self . vartype } ) for v , bias in iteritems ( self . linear ) ) ) BQM . add_edges_from ( ( ( u , v , { edge...
Convert a binary quadratic model to NetworkX graph format .
23,738
def from_networkx_graph ( cls , G , vartype = None , node_attribute_name = 'bias' , edge_attribute_name = 'bias' ) : if vartype is None : if not hasattr ( G , 'vartype' ) : msg = ( "either 'vartype' argument must be provided or " "the given graph should have a vartype attribute." ) raise ValueError ( msg ) vartype = G ...
Create a binary quadratic model from a NetworkX graph .
23,739
def to_ising ( self ) : return dict ( self . spin . linear ) , dict ( self . spin . quadratic ) , self . spin . offset
Converts a binary quadratic model to Ising format .
23,740
def from_ising ( cls , h , J , offset = 0.0 ) : if isinstance ( h , abc . Sequence ) : h = dict ( enumerate ( h ) ) return cls ( h , J , offset , Vartype . SPIN )
Create a binary quadratic model from an Ising problem .
23,741
def to_qubo ( self ) : qubo = dict ( self . binary . quadratic ) qubo . update ( ( ( v , v ) , bias ) for v , bias in iteritems ( self . binary . linear ) ) return qubo , self . binary . offset
Convert a binary quadratic model to QUBO format .
23,742
def from_qubo ( cls , Q , offset = 0.0 ) : linear = { } quadratic = { } for ( u , v ) , bias in iteritems ( Q ) : if u == v : linear [ u ] = bias else : quadratic [ ( u , v ) ] = bias return cls ( linear , quadratic , offset , Vartype . BINARY )
Create a binary quadratic model from a QUBO model .
23,743
def to_numpy_matrix ( self , variable_order = None ) : import numpy as np if variable_order is None : num_variables = len ( self ) mat = np . zeros ( ( num_variables , num_variables ) , dtype = float ) try : for v , bias in iteritems ( self . binary . linear ) : mat [ v , v ] = bias except IndexError : raise ValueError...
Convert a binary quadratic model to NumPy 2D array .
23,744
def from_numpy_matrix ( cls , mat , variable_order = None , offset = 0.0 , interactions = None ) : import numpy as np if mat . ndim != 2 : raise ValueError ( "expected input mat to be a square 2D numpy array" ) num_row , num_col = mat . shape if num_col != num_row : raise ValueError ( "expected input mat to be a square...
Create a binary quadratic model from a NumPy array .
23,745
def to_numpy_vectors ( self , variable_order = None , dtype = np . float , index_dtype = np . int64 , sort_indices = False ) : linear = self . linear quadratic = self . quadratic num_variables = len ( linear ) num_interactions = len ( quadratic ) irow = np . empty ( num_interactions , dtype = index_dtype ) icol = np . ...
Convert a binary quadratic model to numpy arrays .
23,746
def from_numpy_vectors ( cls , linear , quadratic , offset , vartype , variable_order = None ) : try : heads , tails , values = quadratic except ValueError : raise ValueError ( "quadratic should be a 3-tuple" ) if not len ( heads ) == len ( tails ) == len ( values ) : raise ValueError ( "row, col, and bias should be of...
Create a binary quadratic model from vectors .
23,747
def to_pandas_dataframe ( self ) : import pandas as pd try : variable_order = sorted ( self . linear ) except TypeError : variable_order = list ( self . linear ) return pd . DataFrame ( self . to_numpy_matrix ( variable_order = variable_order ) , index = variable_order , columns = variable_order )
Convert a binary quadratic model to pandas DataFrame format .
23,748
def from_pandas_dataframe ( cls , bqm_df , offset = 0.0 , interactions = None ) : if interactions is None : interactions = [ ] bqm = cls ( { } , { } , offset , Vartype . BINARY ) for u , row in bqm_df . iterrows ( ) : for v , bias in row . iteritems ( ) : if u == v : bqm . add_variable ( u , bias ) elif bias : bqm . ad...
Create a binary quadratic model from a QUBO model formatted as a pandas DataFrame .
23,749
def ising_energy ( sample , h , J , offset = 0.0 ) : for v in h : offset += h [ v ] * sample [ v ] for v0 , v1 in J : offset += J [ ( v0 , v1 ) ] * sample [ v0 ] * sample [ v1 ] return offset
Calculate the energy for the specified sample of an Ising model .
23,750
def qubo_energy ( sample , Q , offset = 0.0 ) : for v0 , v1 in Q : offset += sample [ v0 ] * sample [ v1 ] * Q [ ( v0 , v1 ) ] return offset
Calculate the energy for the specified sample of a QUBO model .
23,751
def ising_to_qubo ( h , J , offset = 0.0 ) : q = { ( v , v ) : 2. * bias for v , bias in iteritems ( h ) } for ( u , v ) , bias in iteritems ( J ) : if bias == 0.0 : continue q [ ( u , v ) ] = 4. * bias q [ ( u , u ) ] -= 2. * bias q [ ( v , v ) ] -= 2. * bias offset += sum ( itervalues ( J ) ) - sum ( itervalues ( h )...
Convert an Ising problem to a QUBO problem .
23,752
def qubo_to_ising ( Q , offset = 0.0 ) : h = { } J = { } linear_offset = 0.0 quadratic_offset = 0.0 for ( u , v ) , bias in iteritems ( Q ) : if u == v : if u in h : h [ u ] += .5 * bias else : h [ u ] = .5 * bias linear_offset += bias else : if bias != 0.0 : J [ ( u , v ) ] = .25 * bias if u in h : h [ u ] += .25 * bi...
Convert a QUBO problem to an Ising problem .
23,753
def resolve_label_conflict ( mapping , old_labels = None , new_labels = None ) : if old_labels is None : old_labels = set ( mapping ) if new_labels is None : new_labels = set ( itervalues ( mapping ) ) counter = itertools . count ( 2 * len ( mapping ) ) old_to_intermediate = { } intermediate_to_new = { } for old , new ...
Resolve a self - labeling conflict by creating an intermediate labeling .
23,754
def fix_variables ( bqm , sampling_mode = True ) : try : from dimod . roof_duality . _fix_variables import fix_variables_wrapper except ImportError : raise ImportError ( "c++ extension roof_duality is not built" ) if sampling_mode : method = 2 else : method = 1 linear = bqm . linear if all ( v in linear for v in range ...
Determine assignments for some variables of a binary quadratic model .
23,755
def dimod_object_hook ( obj ) : if _is_sampleset_v2 ( obj ) : return SampleSet . from_serializable ( obj ) elif _is_bqm_v2 ( obj ) : return BinaryQuadraticModel . from_serializable ( obj ) return obj
JSON - decoding for dimod objects .
23,756
def _decode_label ( label ) : if isinstance ( label , list ) : return tuple ( _decode_label ( v ) for v in label ) return label
Convert a list label into a tuple . Works recursively on nested lists .
23,757
def _encode_label ( label ) : if isinstance ( label , tuple ) : return [ _encode_label ( v ) for v in label ] return label
Convert a tuple label into a list . Works recursively on nested tuples .
23,758
def make_quadratic ( poly , strength , vartype = None , bqm = None ) : if bqm is None : if vartype is None : raise ValueError ( "one of vartype and bqm must be provided" ) bqm = BinaryQuadraticModel . empty ( vartype ) else : if not isinstance ( bqm , BinaryQuadraticModel ) : raise TypeError ( 'create_using must be a B...
Create a binary quadratic model from a higher order polynomial .
23,759
def _reduce_degree ( bqm , poly , vartype , scale ) : if all ( len ( term ) <= 2 for term in poly ) : bqm . add_interactions_from ( poly ) return bqm paircounter = Counter ( ) for term in poly : if len ( term ) > 2 : for u , v in itertools . combinations ( term , 2 ) : pair = frozenset ( ( u , v ) ) paircounter [ pair ...
helper function for make_quadratic
23,760
def poly_energy ( sample_like , poly ) : msg = ( "poly_energy is deprecated and will be removed in dimod 0.9.0." "In the future, use BinaryPolynomial.energy" ) warnings . warn ( msg , DeprecationWarning ) return BinaryPolynomial ( poly , 'SPIN' ) . energy ( sample_like )
Calculates energy of a sample from a higher order polynomial .
23,761
def poly_energies ( samples_like , poly ) : msg = ( "poly_energies is deprecated and will be removed in dimod 0.9.0." "In the future, use BinaryPolynomial.energies" ) warnings . warn ( msg , DeprecationWarning ) return BinaryPolynomial ( poly , 'SPIN' ) . energies ( samples_like )
Calculates energy of samples from a higher order polynomial .
23,762
def frustrated_loop ( graph , num_cycles , R = float ( 'inf' ) , cycle_predicates = tuple ( ) , max_failed_cycles = 100 , seed = None ) : nodes , edges = graph if num_cycles <= 0 : raise ValueError ( "num_cycles should be a positive integer" ) if R <= 0 : raise ValueError ( "R should be a positive integer" ) if max_fai...
Generate a frustrated loop problem .
23,763
def _random_cycle ( adj , random_state ) : n = random_state . randint ( len ( adj ) ) for idx , v in enumerate ( adj ) : if idx == n : break start = v walk = [ start ] visited = { start : 0 } while True : if len ( walk ) > 1 : previous = walk [ - 2 ] neighbors = [ u for u in adj [ walk [ - 1 ] ] if u != previous ] else...
Find a cycle using a random graph walk .
23,764
def sample ( self , bqm , num_spin_reversal_transforms = 2 , spin_reversal_variables = None , ** kwargs ) : if spin_reversal_variables is not None : import warnings warnings . warn ( "'spin_reversal_variables' kwarg is deprecated and no longer functions." , DeprecationWarning ) responses = [ ] flipped_bqm = bqm . copy ...
Sample from the binary quadratic model .
23,765
def append_index ( self , num_rows ) : width = len ( str ( num_rows - 1 ) ) def f ( datum ) : return str ( datum . idx ) . ljust ( width ) header = ' ' * width self . append ( header , f )
Add an index column .
23,766
def append_sample ( self , v , vartype , _left = False ) : vstr = str ( v ) . rjust ( 2 ) length = len ( vstr ) if vartype is dimod . SPIN : def f ( datum ) : return _spinstr ( datum . sample [ v ] , rjust = length ) else : def f ( datum ) : return _binarystr ( datum . sample [ v ] , rjust = length ) self . append ( vs...
Add a sample column
23,767
def append_vector ( self , name , vector , _left = False ) : if np . issubdtype ( vector . dtype , np . integer ) : largest = str ( max ( vector . max ( ) , vector . min ( ) , key = abs ) ) length = max ( len ( largest ) , min ( 7 , len ( name ) ) ) if len ( name ) > length : header = name [ : length - 1 ] + '.' else :...
Add a data vectors column .
23,768
def format ( self , obj , ** kwargs ) : sio = StringIO ( ) self . fprint ( obj , stream = sio , ** kwargs ) return sio . getvalue ( )
Return the formatted representation of the object as a string .
23,769
def fprint ( self , obj , stream = None , ** kwargs ) : if stream is None : stream = sys . stdout options = self . options options . update ( kwargs ) if isinstance ( obj , dimod . SampleSet ) : self . _print_sampleset ( obj , stream , ** options ) return raise TypeError ( "cannot format type {}" . format ( type ( obj ...
Prints the formatted representation of the object on stream
23,770
def as_samples ( samples_like , dtype = None , copy = False , order = 'C' ) : if isinstance ( samples_like , SampleSet ) : return samples_like . record . sample , list ( samples_like . variables ) if isinstance ( samples_like , tuple ) and len ( samples_like ) == 2 : samples_like , labels = samples_like if not isinstan...
Convert a samples_like object to a NumPy array and list of labels .
23,771
def concatenate ( samplesets , defaults = None ) : itertup = iter ( samplesets ) try : first = next ( itertup ) except StopIteration : raise ValueError ( "samplesets must contain at least one SampleSet" ) vartype = first . vartype variables = first . variables records = [ first . record ] records . extend ( _iter_recor...
Combine SampleSets .
23,772
def from_samples_bqm ( cls , samples_like , bqm , ** kwargs ) : samples_like = as_samples ( samples_like ) energies = bqm . energies ( samples_like ) return cls . from_samples ( samples_like , energy = energies , vartype = bqm . vartype , ** kwargs )
Build a SampleSet from raw samples using a BinaryQuadraticModel to get energies and vartype .
23,773
def data_vectors ( self ) : return { field : self . record [ field ] for field in self . record . dtype . names if field != 'sample' }
The per - sample data in a vector .
23,774
def first ( self ) : try : return next ( self . data ( sorted_by = 'energy' , name = 'Sample' ) ) except StopIteration : raise ValueError ( '{} is empty' . format ( self . __class__ . __name__ ) )
Sample with the lowest - energy .
23,775
def done ( self ) : return ( not hasattr ( self , '_future' ) ) or ( not hasattr ( self . _future , 'done' ) ) or self . _future . done ( )
Return True if a pending computation is done .
23,776
def samples ( self , n = None , sorted_by = 'energy' ) : if n is not None : return self . samples ( sorted_by = sorted_by ) [ : n ] if sorted_by is None : samples = self . record . sample else : order = np . argsort ( self . record [ sorted_by ] ) samples = self . record . sample [ order ] return SamplesArray ( samples...
Return an iterable over the samples .
23,777
def copy ( self ) : return self . __class__ ( self . record . copy ( ) , self . variables , self . info . copy ( ) , self . vartype )
Create a shallow copy .
23,778
def aggregate ( self ) : _ , indices , inverse = np . unique ( self . record . sample , axis = 0 , return_index = True , return_inverse = True ) order = np . argsort ( indices ) indices = indices [ order ] record = self . record [ indices ] record . num_occurrences = 0 for old_idx , new_idx in enumerate ( inverse ) : n...
Create a new SampleSet with repeated samples aggregated .
23,779
def append_variables ( self , samples_like , sort_labels = True ) : samples , labels = as_samples ( samples_like ) num_samples = len ( self ) if samples . shape [ 0 ] == num_samples : pass elif samples . shape [ 0 ] == 1 and num_samples : samples = np . repeat ( samples , num_samples , axis = 0 ) else : msg = ( "mismat...
Create a new sampleset with the given variables with values added .
23,780
def lowest ( self , rtol = 1.e-5 , atol = 1.e-8 ) : if len ( self ) == 0 : return self . copy ( ) record = self . record close = np . isclose ( record . energy , np . min ( record . energy ) , rtol = rtol , atol = atol ) record = record [ close ] return type ( self ) ( record , self . variables , copy . deepcopy ( self...
Return a sample set containing the lowest - energy samples .
23,781
def slice ( self , * slice_args , ** kwargs ) : sorted_by = kwargs . pop ( 'sorted_by' , 'energy' ) if kwargs : raise TypeError ( 'slice got an unexpected ' 'keyword argument {!r}' . format ( kwargs . popitem ( ) [ 0 ] ) ) if slice_args : selector = slice ( * slice_args ) else : selector = slice ( None ) if sorted_by i...
Create a new SampleSet with rows sliced according to standard Python slicing syntax .
23,782
def to_pandas_dataframe ( self , sample_column = False ) : import pandas as pd if sample_column : df = pd . DataFrame ( self . data ( sorted_by = None , sample_dict_cast = True ) ) else : df = pd . DataFrame ( self . record . sample , columns = self . variables ) for field in sorted ( self . record . dtype . fields ) :...
Convert a SampleSet to a Pandas DataFrame
23,783
def penalty_satisfaction ( response , bqm ) : record = response . record label_dict = response . variables . index if len ( bqm . info [ 'reduction' ] ) == 0 : return np . array ( [ 1 ] * len ( record . sample ) ) penalty_vector = np . prod ( [ record . sample [ : , label_dict [ qi ] ] * record . sample [ : , label_dic...
Creates a penalty satisfaction list
23,784
def polymorph_response ( response , poly , bqm , penalty_strength = None , keep_penalty_variables = True , discard_unsatisfied = False ) : record = response . record penalty_vector = penalty_satisfaction ( response , bqm ) original_variables = bqm . variables if discard_unsatisfied : samples_to_keep = list ( map ( bool...
Transforms the sampleset for the higher order problem .
23,785
def sample_poly ( self , poly , penalty_strength = 1.0 , keep_penalty_variables = False , discard_unsatisfied = False , ** parameters ) : bqm = make_quadratic ( poly , penalty_strength , vartype = poly . vartype ) response = self . child . sample ( bqm , ** parameters ) return polymorph_response ( response , poly , bqm...
Sample from the given binary polynomial .
23,786
def sample_poly ( self , poly , scalar = None , bias_range = 1 , poly_range = None , ignored_terms = None , ** parameters ) : if ignored_terms is None : ignored_terms = set ( ) else : ignored_terms = { frozenset ( term ) for term in ignored_terms } original , poly = poly , poly . copy ( ) if scalar is not None : poly ....
Scale and sample from the given binary polynomial .
23,787
def sample_poly ( self , poly , ** kwargs ) : tkw = self . _truncate_kwargs if self . _aggregate : return self . child . sample_poly ( poly , ** kwargs ) . aggregate ( ) . truncate ( ** tkw ) else : return self . child . sample_poly ( poly , ** kwargs ) . truncate ( ** tkw )
Sample from the binary polynomial and truncate output .
23,788
def _samples_dicts_to_array ( samples_dicts , labels ) : itersamples = iter ( samples_dicts ) first_sample = next ( itersamples ) if labels is None : labels = list ( first_sample ) num_variables = len ( labels ) def _iter_samples ( ) : yield np . fromiter ( ( first_sample [ v ] for v in labels ) , count = num_variables...
Convert an iterable of samples where each sample is a dict to a numpy 2d array . Also determines the labels is they are None .
23,789
def data_struct_array ( sample , ** vectors ) : if not len ( sample ) : sample = np . zeros ( ( 0 , 0 ) , dtype = np . int8 ) else : sample = np . asarray ( sample , dtype = np . int8 ) if sample . ndim < 2 : sample = np . expand_dims ( sample , 0 ) num_samples , num_variables = sample . shape if 'num_occurrences' not ...
Combine samples and per - sample data into a numpy structured array .
23,790
def from_samples ( cls , samples_like , vectors , info , vartype , variable_labels = None ) : try : samples = np . asarray ( samples_like , dtype = np . int8 ) except TypeError : samples , variable_labels = _samples_dicts_to_array ( samples_like , variable_labels ) assert samples . dtype == np . int8 , 'sanity check' r...
Build a response from samples .
23,791
def breathe_identifier ( self ) : if self . kind == "function" : return "{name}({parameters})" . format ( name = self . name , parameters = ", " . join ( self . parameters ) ) return self . name
The unique identifier for breathe directives .
23,792
def full_signature ( self ) : if self . kind == "function" : return "{template}{return_type} {name}({parameters})" . format ( template = "template <{0}> " . format ( ", " . join ( self . template ) ) if self . template else "" , return_type = self . return_type , name = self . name , parameters = ", " . join ( self . p...
The full signature of a function node .
23,793
def findNestedNamespaces ( self , lst ) : if self . kind == "namespace" : lst . append ( self ) for c in self . children : c . findNestedNamespaces ( lst )
Recursive helper function for finding nested namespaces . If this node is a namespace node it is appended to lst . Each node also calls each of its child findNestedNamespaces with the same list .
23,794
def findNestedDirectories ( self , lst ) : if self . kind == "dir" : lst . append ( self ) for c in self . children : c . findNestedDirectories ( lst )
Recursive helper function for finding nested directories . If this node is a directory node it is appended to lst . Each node also calls each of its child findNestedDirectories with the same list .
23,795
def findNestedClassLike ( self , lst ) : if self . kind == "class" or self . kind == "struct" : lst . append ( self ) for c in self . children : c . findNestedClassLike ( lst )
Recursive helper function for finding nested classes and structs . If this node is a class or struct it is appended to lst . Each node also calls each of its child findNestedClassLike with the same list .
23,796
def generateDirectoryNodeDocuments ( self ) : all_dirs = [ ] for d in self . dirs : d . findNestedDirectories ( all_dirs ) for d in all_dirs : self . generateDirectoryNodeRST ( d )
Generates all of the directory reStructuredText documents .
23,797
def gerrymanderNodeFilenames ( self ) : for node in self . all_nodes : node . file_name = os . path . basename ( node . file_name ) if node . kind == "file" : node . program_file = os . path . basename ( node . program_file )
When creating nodes the filename needs to be relative to conf . py so it will include self . root_directory . However when generating the API the file we are writing to is in the same directory as the generated node files so we need to remove the directory path from a given ExhaleNode s file_name before we can include ...
23,798
def generateClassView ( self ) : class_view_stream = StringIO ( ) for n in self . namespaces : n . toHierarchy ( True , 0 , class_view_stream ) missing = [ ] for cl in sorted ( self . class_like ) : if not cl . in_class_hierarchy : missing . append ( cl ) for e in sorted ( self . enums ) : if not e . in_class_hierarchy...
Generates the class view hierarchy writing it to self . class_hierarchy_file .
23,799
def generateDirectoryView ( self ) : file_view_stream = StringIO ( ) for d in self . dirs : d . toHierarchy ( False , 0 , file_view_stream ) missing = [ ] for f in sorted ( self . files ) : if not f . in_file_hierarchy : missing . append ( f ) found_missing = len ( missing ) > 0 if found_missing : idx = 0 last_missing_...
Generates the file view hierarchy writing it to self . file_hierarchy_file .