idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
34,100 | def score ( self , file : str = '' , code : str = '' , out : 'SASdata' = None ) -> 'SASdata' : if out is not None : outTable = out . table outLibref = out . libref else : outTable = self . table outLibref = self . libref codestr = code code = "data %s.%s%s;" % ( outLibref , outTable , self . _dsopts ( ) ) code += "set ... | This method is meant to update a SAS Data object with a model score file . |
34,101 | def to_df ( self , method : str = 'MEMORY' , ** kwargs ) -> 'pd.DataFrame' : ll = self . _is_valid ( ) if ll : print ( ll [ 'LOG' ] ) return None else : return self . sas . sasdata2dataframe ( self . table , self . libref , self . dsopts , method , ** kwargs ) | Export this SAS Data Set to a Pandas Data Frame |
34,102 | def to_df_CSV ( self , tempfile : str = None , tempkeep : bool = False , ** kwargs ) -> 'pd.DataFrame' : return self . to_df ( method = 'CSV' , tempfile = tempfile , tempkeep = tempkeep , ** kwargs ) | Export this SAS Data Set to a Pandas Data Frame via CSV file |
34,103 | def series ( self , x : str , y : list , title : str = '' ) -> object : code = "proc sgplot data=" + self . libref + '.' + self . table + self . _dsopts ( ) + ";\n" if len ( title ) > 0 : code += '\ttitle "' + title + '";\n' if isinstance ( y , list ) : num = len ( y ) else : num = 1 y = [ y ] for i in range ( num ) : ... | This method plots a series of x y coordinates . You can provide a list of y columns for multiple line plots . |
34,104 | def _charlist ( self , data ) -> list : char_string = nosub = self . sas . nosub self . sas . nosub = False ll = self . sas . submit ( char_string . format ( data . libref , data . table + data . _dsopts ( ) ) ) self . sas . nosub = nosub l2 = ll [ 'LOG' ] . partition ( "VARLIST=\n" ) l2 = l2 [ 2 ] . rpartition ( "VARL... | Private method to return the variables in a SAS Data set that are of type char |
34,105 | def disconnect ( self ) : if not self . sascfg . reconnect : return "Disconnecting and then reconnecting to this workspaceserver has been disabled. Did not disconnect" pgm = b'\n' + b'tom says EOL=DISCONNECT \n' self . stdin [ 0 ] . send ( pgm ) while True : try : log = self . stderr [ 0 ] . recv (... | This method disconnects an IOM session to allow for reconnecting when switching networks |
34,106 | def proc_decorator ( req_set ) : def decorator ( func ) : @ wraps ( func ) def inner ( self , * args , ** kwargs ) : proc = func . __name__ . lower ( ) inner . proc_decorator = kwargs self . logger . debug ( "processing proc:{}" . format ( func . __name__ ) ) self . logger . debug ( req_set ) self . logger . debug ( "k... | Decorator that provides the wrapped function with an attribute actual_kwargs containing just those keyword arguments actually passed in to the function . |
34,107 | def ALL ( self ) : if not self . sas . batch : for i in self . _names : if i . upper ( ) != 'LOG' : x = self . __getattr__ ( i ) if isinstance ( x , pd . DataFrame ) : if self . sas . sascfg . display . lower ( ) == 'zeppelin' : print ( "%text " + i + "\n" + str ( x ) + "\n" ) else : self . sas . DISPLAY ( x ) else : r... | This method shows all the results attributes for a given object |
34,108 | def execute_table ( self , _output_type , ** kwargs : dict ) -> 'SASresults' : left = kwargs . pop ( 'left' , None ) top = kwargs . pop ( 'top' , None ) sets = dict ( classes = set ( ) , vars = set ( ) ) left . _gather ( sets ) if top : top . _gather ( sets ) table = top and '%s, %s' % ( str ( left ) , str ( top ) ) or... | executes a PROC TABULATE statement |
34,109 | def dumps_content ( self , ** kwargs ) : r return dumps_list ( self , escape = self . escape , token = self . content_separator , ** kwargs ) | r Represent the container as a string in LaTeX syntax . |
34,110 | def _propagate_packages ( self ) : for item in self . data : if isinstance ( item , LatexObject ) : if isinstance ( item , Container ) : item . _propagate_packages ( ) for p in item . packages : self . packages . add ( p ) | Make sure packages get propagated . |
34,111 | def create ( self , child ) : prev_data = self . data self . data = child . data yield child self . data = prev_data self . append ( child ) | Add a LaTeX object to current container context - manager style . |
34,112 | def dumps ( self ) : content = self . dumps_content ( ) if not content . strip ( ) and self . omit_if_empty : return '' string = '' if self . arguments is None : extra_arguments = Arguments ( ) else : extra_arguments = self . arguments begin = Command ( 'begin' , self . start_arguments , self . options , extra_argument... | Represent the environment as a string in LaTeX syntax . |
34,113 | def dumps ( self ) : r content = self . dumps_content ( ) if not content . strip ( ) and self . omit_if_empty : return '' string = '' start = Command ( self . latex_name , arguments = self . arguments , options = self . options ) string += start . dumps ( ) + '{ \n' if content != '' : string += content + '\n}' else : s... | r Convert the container to a string in latex syntax . |
34,114 | def dumps ( self ) : if not self . numbering : num = '*' else : num = '' string = Command ( self . latex_name + num , self . title ) . dumps ( ) if self . label is not None : string += '%\n' + self . label . dumps ( ) string += '%\n' + self . dumps_content ( ) return string | Represent the section as a string in LaTeX syntax . |
34,115 | def _get_table_width ( table_spec ) : cleaner_spec = re . sub ( r'{[^}]*}' , '' , table_spec ) cleaner_spec = re . sub ( r'X\[(.*?(.))\]' , r'\2' , cleaner_spec ) spec_counter = Counter ( cleaner_spec ) return sum ( spec_counter [ l ] for l in COLUMN_LETTERS ) | Calculate the width of a table based on its spec . |
34,116 | def dumps ( self ) : r string = "" if self . row_height is not None : row_height = Command ( 'renewcommand' , arguments = [ NoEscape ( r'\arraystretch' ) , self . row_height ] ) string += row_height . dumps ( ) + '%\n' if self . col_space is not None : col_space = Command ( 'setlength' , arguments = [ NoEscape ( r'\tab... | r Turn the Latex Object into a string in Latex format . |
34,117 | def dumps_content ( self , ** kwargs ) : r content = '' if self . booktabs : content += '\\toprule%\n' content += super ( ) . dumps_content ( ** kwargs ) if self . booktabs : content += '\\bottomrule%\n' return NoEscape ( content ) | r Represent the content of the tabular in LaTeX syntax . |
34,118 | def add_hline ( self , start = None , end = None , * , color = None , cmidruleoption = None ) : r if self . booktabs : hline = 'midrule' cline = 'cmidrule' if cmidruleoption is not None : cline += '(' + cmidruleoption + ')' else : hline = 'hline' cline = 'cline' if color is not None : if not self . color : self . packa... | r Add a horizontal line to the table . |
34,119 | def add_row ( self , * cells , color = None , escape = None , mapper = None , strict = True ) : if len ( cells ) == 1 and _is_iterable ( cells ) : cells = cells [ 0 ] if escape is None : escape = self . escape for c in cells : if isinstance ( c , LatexObject ) : for p in c . packages : self . packages . add ( p ) cell_... | Add a row of cells to the table . |
34,120 | def dumps ( self ) : args = [ self . size , self . align , self . dumps_content ( ) ] string = Command ( self . latex_name , args ) . dumps ( ) return string | Represent the multicolumn as a string in LaTeX syntax . |
34,121 | def dumps ( self ) : _s = super ( ) . dumps ( ) if self . _preamble : if _s . startswith ( r"\begin{longtabu}" ) : _s = _s [ : 16 ] + self . _preamble + _s [ 16 : ] elif _s . startswith ( r"\begin{tabu}" ) : _s = _s [ : 12 ] + self . _preamble + _s [ 12 : ] else : raise TableError ( "Can't apply preamble to Tabu table ... | Turn the tabu object into a string in Latex format . |
34,122 | def end_table_header ( self ) : r if self . header : msg = "Table already has a header" raise TableError ( msg ) self . header = True self . append ( Command ( r'endhead' ) ) | r End the table header which will appear on every page . |
34,123 | def end_table_footer ( self ) : r if self . foot : msg = "Table already has a foot" raise TableError ( msg ) self . foot = True self . append ( Command ( 'endfoot' ) ) | r End the table foot which will appear on every page . |
34,124 | def end_table_last_footer ( self ) : r if self . lastFoot : msg = "Table already has a last foot" raise TableError ( msg ) self . lastFoot = True self . append ( Command ( 'endlastfoot' ) ) | r End the table foot which will appear on the last page . |
34,125 | def escape_latex ( s ) : r if isinstance ( s , NoEscape ) : return s return NoEscape ( '' . join ( _latex_special_chars . get ( c , c ) for c in str ( s ) ) ) | r Escape characters that are special in latex . |
34,126 | def fix_filename ( path ) : r path_parts = path . split ( '/' if os . name == 'posix' else '\\' ) dir_parts = path_parts [ : - 1 ] filename = path_parts [ - 1 ] file_parts = filename . split ( '.' ) if len ( file_parts ) > 2 : filename = '{' + '.' . join ( file_parts [ 0 : - 1 ] ) + '}.' + file_parts [ - 1 ] dir_parts ... | r Fix filenames for use in LaTeX . |
34,127 | def dumps_list ( l , * , escape = True , token = '%\n' , mapper = None , as_content = True ) : r strings = ( _latex_item_to_string ( i , escape = escape , as_content = as_content ) for i in l ) if mapper is not None : if not isinstance ( mapper , list ) : mapper = [ mapper ] for m in mapper : strings = [ m ( s ) for s ... | r Try to generate a LaTeX string of a list that can contain anything . |
34,128 | def _latex_item_to_string ( item , * , escape = False , as_content = False ) : if isinstance ( item , pylatex . base_classes . LatexObject ) : if as_content : return item . dumps_as_content ( ) else : return item . dumps ( ) elif not isinstance ( item , str ) : item = str ( item ) if escape : item = escape_latex ( item... | Use the render method when possible otherwise uses str . |
34,129 | def bold ( s , * , escape = True ) : r if escape : s = escape_latex ( s ) return NoEscape ( r'\textbf{' + s + '}' ) | r Make a string appear bold in LaTeX formatting . |
34,130 | def italic ( s , * , escape = True ) : r if escape : s = escape_latex ( s ) return NoEscape ( r'\textit{' + s + '}' ) | r Make a string appear italicized in LaTeX formatting . |
34,131 | def auto_change_docstring ( app , what , name , obj , options , lines ) : r if what == 'module' and name . startswith ( 'pylatex' ) : lines . insert ( 0 , len ( name ) * '=' ) lines . insert ( 0 , name ) hits = 0 for i , line in enumerate ( lines . copy ( ) ) : if line . endswith ( '\\' ) : lines [ i - hits ] += lines ... | r Make some automatic changes to docstrings . |
34,132 | def _remove_invalid_char ( s ) : s = '' . join ( [ i if ord ( i ) >= 32 and ord ( i ) < 127 else '' for i in s ] ) s = s . translate ( dict . fromkeys ( map ( ord , "_%~#\\{}\":" ) ) ) return s | Remove invalid and dangerous characters from a string . |
34,133 | def add_image ( self , filename , * , width = NoEscape ( r'0.8\textwidth' ) , placement = NoEscape ( r'\centering' ) ) : if width is not None : if self . escape : width = escape_latex ( width ) width = 'width=' + str ( width ) if placement is not None : self . append ( placement ) self . append ( StandAloneGraphic ( im... | Add an image to the figure . |
34,134 | def _save_plot ( self , * args , extension = 'pdf' , ** kwargs ) : import matplotlib . pyplot as plt tmp_path = make_temp_dir ( ) filename = '{}.{}' . format ( str ( uuid . uuid4 ( ) ) , extension . strip ( '.' ) ) filepath = posixpath . join ( tmp_path , filename ) plt . savefig ( filepath , * args , ** kwargs ) retur... | Save the plot . |
34,135 | def add_plot ( self , * args , extension = 'pdf' , ** kwargs ) : add_image_kwargs = { } for key in ( 'width' , 'placement' ) : if key in kwargs : add_image_kwargs [ key ] = kwargs . pop ( key ) filename = self . _save_plot ( * args , extension = extension , ** kwargs ) self . add_image ( filename , ** add_image_kwargs ... | Add the current Matplotlib plot to the figure . |
34,136 | def add_image ( self , filename , * , width = NoEscape ( r'\linewidth' ) , placement = None ) : super ( ) . add_image ( filename , width = width , placement = placement ) | Add an image to the subfigure . |
34,137 | def escape ( self ) : if self . _escape is not None : return self . _escape if self . _default_escape is not None : return self . _default_escape return True | Determine whether or not to escape content of this class . |
34,138 | def _repr_values ( self ) : def getattr_better ( obj , field ) : try : return getattr ( obj , field ) except AttributeError as e : try : return getattr ( obj , '_' + field ) except AttributeError : raise e return ( getattr_better ( self , attr ) for attr in self . _repr_attributes ) | Return values that are to be shown in repr string . |
34,139 | def _repr_attributes ( self ) : if self . _repr_attributes_override is None : attrs = getfullargspec ( self . __init__ ) . args [ 1 : ] mapping = self . _repr_attributes_mapping if mapping : attrs = [ mapping [ a ] if a in mapping else a for a in attrs ] return attrs return self . _repr_attributes_override | Return attributes that should be part of the repr string . |
34,140 | def latex_name ( self ) : star = ( '*' if self . _star_latex_name else '' ) if self . _latex_name is not None : return self . _latex_name + star return self . __class__ . __name__ . lower ( ) + star | Return the name of the class used in LaTeX . |
34,141 | def generate_tex ( self , filepath ) : with open ( filepath + '.tex' , 'w' , encoding = 'utf-8' ) as newf : self . dump ( newf ) | Generate a . tex file . |
34,142 | def dumps_as_content ( self ) : string = self . dumps ( ) if self . separate_paragraph or self . begin_paragraph : string = '\n\n' + string . lstrip ( '\n' ) if self . separate_paragraph or self . end_paragraph : string = string . rstrip ( '\n' ) + '\n\n' return string | Create a string representation of the object as content . |
34,143 | def _propagate_packages ( self ) : r super ( ) . _propagate_packages ( ) for item in ( self . preamble ) : if isinstance ( item , LatexObject ) : if isinstance ( item , Container ) : item . _propagate_packages ( ) for p in item . packages : self . packages . add ( p ) | r Propogate packages . |
34,144 | def dumps ( self ) : head = self . documentclass . dumps ( ) + '%\n' head += self . dumps_packages ( ) + '%\n' head += dumps_list ( self . variables ) + '%\n' head += dumps_list ( self . preamble ) + '%\n' return head + '%\n' + super ( ) . dumps ( ) | Represent the document as a string in LaTeX syntax . |
34,145 | def generate_pdf ( self , filepath = None , * , clean = True , clean_tex = True , compiler = None , compiler_args = None , silent = True ) : if compiler_args is None : compiler_args = [ ] filepath = self . _select_filepath ( filepath ) filepath = os . path . join ( '.' , filepath ) cur_dir = os . getcwd ( ) dest_dir = ... | Generate a pdf file from the document . |
34,146 | def _select_filepath ( self , filepath ) : if filepath is None : return self . default_filepath else : if os . path . basename ( filepath ) == '' : filepath = os . path . join ( filepath , os . path . basename ( self . default_filepath ) ) return filepath | Make a choice between filepath and self . default_filepath . |
34,147 | def add_color ( self , name , model , description ) : r if self . color is False : self . packages . append ( Package ( "color" ) ) self . color = True self . preamble . append ( Command ( "definecolor" , arguments = [ name , model , description ] ) ) | r Add a color that can be used throughout the document . |
34,148 | def change_length ( self , parameter , value ) : r self . preamble . append ( UnsafeCommand ( 'setlength' , arguments = [ parameter , value ] ) ) | r Change the length of a certain parameter to a certain value . |
34,149 | def set_variable ( self , name , value ) : r name_arg = "\\" + name variable_exists = False for variable in self . variables : if name_arg == variable . arguments . _positional_args [ 0 ] : variable_exists = True break if variable_exists : renew = Command ( command = "renewcommand" , arguments = [ NoEscape ( name_arg )... | r Add a variable which can be used inside the document . |
34,150 | def change ( self , ** kwargs ) : old_attrs = { } for k , v in kwargs . items ( ) : old_attrs [ k ] = getattr ( self , k , v ) setattr ( self , k , v ) yield self for k , v in old_attrs . items ( ) : setattr ( self , k , v ) | Override some attributes of the config in a specific context . |
34,151 | def __key ( self ) : return ( self . latex_name , self . arguments , self . options , self . extra_arguments ) | Return a hashable key representing the command . |
34,152 | def dumps ( self ) : options = self . options . dumps ( ) arguments = self . arguments . dumps ( ) if self . extra_arguments is None : return r'\{command}{options}{arguments}' . format ( command = self . latex_name , options = options , arguments = arguments ) extra_arguments = self . extra_arguments . dumps ( ) return... | Represent the command as a string in LaTeX syntax . |
34,153 | def _format_contents ( self , prefix , separator , suffix ) : params = self . _list_args_kwargs ( ) if len ( params ) <= 0 : return '' string = prefix + dumps_list ( params , escape = self . escape , token = separator ) + suffix return string | Format the parameters . |
34,154 | def _list_args_kwargs ( self ) : params = [ ] params . extend ( self . _positional_args ) params . extend ( [ '{k}={v}' . format ( k = k , v = v ) for k , v in self . _key_value_args . items ( ) ] ) return params | Make a list of strings representing al parameters . |
34,155 | def dumps_content ( self ) : import numpy as np string = '' shape = self . matrix . shape for ( y , x ) , value in np . ndenumerate ( self . matrix ) : if x : string += '&' string += str ( value ) if x == shape [ 1 ] - 1 and y != shape [ 0 ] - 1 : string += r'\\' + '%\n' super ( ) . dumps_content ( ) return string | Return a string representing the matrix in LaTeX syntax . |
34,156 | def change_thickness ( self , element , thickness ) : r if element == "header" : self . data . append ( Command ( "renewcommand" , arguments = [ NoEscape ( r"\headrulewidth" ) , str ( thickness ) + 'pt' ] ) ) elif element == "footer" : self . data . append ( Command ( "renewcommand" , arguments = [ NoEscape ( r"\footru... | r Change line thickness . |
34,157 | def from_str ( cls , coordinate ) : m = cls . _coordinate_str_regex . match ( coordinate ) if m is None : raise ValueError ( 'invalid coordinate string' ) if m . group ( 1 ) == '++' : relative = True else : relative = False return TikZCoordinate ( float ( m . group ( 2 ) ) , float ( m . group ( 4 ) ) , relative = relat... | Build a TikZCoordinate object from a string . |
34,158 | def distance_to ( self , other ) : other_coord = self . _arith_check ( other ) return math . sqrt ( math . pow ( self . _x - other_coord . _x , 2 ) + math . pow ( self . _y - other_coord . _y , 2 ) ) | Euclidean distance between two coordinates . |
34,159 | def dumps ( self ) : ret_str = [ ] ret_str . append ( Command ( 'node' , options = self . options ) . dumps ( ) ) if self . handle is not None : ret_str . append ( '({})' . format ( self . handle ) ) if self . _node_position is not None : ret_str . append ( 'at {}' . format ( str ( self . _position ) ) ) if self . _nod... | Return string representation of the node . |
34,160 | def get_anchor_point ( self , anchor_name ) : if anchor_name in self . _possible_anchors : return TikZNodeAnchor ( self . handle , anchor_name ) else : try : anchor = int ( anchor_name . split ( '_' ) [ 1 ] ) except : anchor = None if anchor is not None : return TikZNodeAnchor ( self . handle , str ( anchor ) ) raise V... | Return an anchor point of the node if it exists . |
34,161 | def dumps ( self ) : ret_str = self . path_type if self . options is not None : ret_str += self . options . dumps ( ) return ret_str | Return path command representation . |
34,162 | def dumps ( self ) : ret_str = [ ] for item in self . _arg_list : if isinstance ( item , TikZUserPath ) : ret_str . append ( item . dumps ( ) ) elif isinstance ( item , TikZCoordinate ) : ret_str . append ( item . dumps ( ) ) elif isinstance ( item , str ) : ret_str . append ( item ) return ' ' . join ( ret_str ) | Return representation of the path command . |
34,163 | def dumps ( self ) : ret_str = [ Command ( 'path' , options = self . options ) . dumps ( ) ] ret_str . append ( self . path . dumps ( ) ) return ' ' . join ( ret_str ) + ';' | Return a representation for the command . |
34,164 | def dumps ( self ) : string = Command ( 'addplot' , options = self . options ) . dumps ( ) if self . coordinates is not None : string += ' coordinates {%\n' if self . error_bar is None : for x , y in self . coordinates : string += '(' + str ( x ) + ',' + str ( y ) + ')%\n' else : for ( x , y ) , ( e_x , e_y ) in zip ( ... | Represent the plot as a string in LaTeX syntax . |
34,165 | def _cost_gp ( self , x ) : m , _ , _ , _ = self . cost_model . predict_withGradients ( x ) return np . exp ( m ) | Predicts the time cost of evaluating the function at x . |
34,166 | def _cost_gp_withGradients ( self , x ) : m , _ , dmdx , _ = self . cost_model . predict_withGradients ( x ) return np . exp ( m ) , np . exp ( m ) * dmdx | Predicts the time cost and its gradient of evaluating the function at x . |
34,167 | def update_cost_model ( self , x , cost_x ) : if self . cost_type == 'evaluation_time' : cost_evals = np . log ( np . atleast_2d ( np . asarray ( cost_x ) ) . T ) if self . num_updates == 0 : X_all = x costs_all = cost_evals else : X_all = np . vstack ( ( self . cost_model . model . X , x ) ) costs_all = np . vstack ( ... | Updates the GP used to handle the cost . |
34,168 | def update_batches ( self , X_batch , L , Min ) : self . X_batch = X_batch if X_batch is not None : self . r_x0 , self . s_x0 = self . _hammer_function_precompute ( X_batch , L , Min , self . model ) | Updates the batches internally and pre - computes the |
34,169 | def _hammer_function_precompute ( self , x0 , L , Min , model ) : if x0 is None : return None , None if len ( x0 . shape ) == 1 : x0 = x0 [ None , : ] m = model . predict ( x0 ) [ 0 ] pred = model . predict ( x0 ) [ 1 ] . copy ( ) pred [ pred < 1e-16 ] = 1e-16 s = np . sqrt ( pred ) r_x0 = ( m - Min ) / L s_x0 = s / L ... | Pre - computes the parameters of a penalizer centered at x0 . |
34,170 | def _hammer_function ( self , x , x0 , r_x0 , s_x0 ) : return norm . logcdf ( ( np . sqrt ( ( np . square ( np . atleast_2d ( x ) [ : , None , : ] - np . atleast_2d ( x0 ) [ None , : , : ] ) ) . sum ( - 1 ) ) - r_x0 ) / s_x0 ) | Creates the function to define the exclusion zones |
34,171 | def _penalized_acquisition ( self , x , model , X_batch , r_x0 , s_x0 ) : fval = - self . acq . acquisition_function ( x ) [ : , 0 ] if self . transform == 'softplus' : fval_org = fval . copy ( ) fval [ fval_org >= 40. ] = np . log ( fval_org [ fval_org >= 40. ] ) fval [ fval_org < 40. ] = np . log ( np . log1p ( np . ... | Creates a penalized acquisition function using hammer functions around the points collected in the batch |
34,172 | def acquisition_function ( self , x ) : return self . _penalized_acquisition ( x , self . model , self . X_batch , self . r_x0 , self . s_x0 ) | Returns the value of the acquisition function at x . |
34,173 | def d_acquisition_function ( self , x ) : x = np . atleast_2d ( x ) if self . transform == 'softplus' : fval = - self . acq . acquisition_function ( x ) [ : , 0 ] scale = 1. / ( np . log1p ( np . exp ( fval ) ) * ( 1. + np . exp ( - fval ) ) ) elif self . transform == 'none' : fval = - self . acq . acquisition_function... | Returns the gradient of the acquisition function at x . |
34,174 | def acquisition_function_withGradients ( self , x ) : aqu_x = self . acquisition_function ( x ) aqu_x_grad = self . d_acquisition_function ( x ) return aqu_x , aqu_x_grad | Returns the acquisition function and its its gradient at x . |
34,175 | def acquisition_function ( self , x ) : f_acqu = self . _compute_acq ( x ) cost_x , _ = self . cost_withGradients ( x ) return - ( f_acqu * self . space . indicator_constraints ( x ) ) / cost_x | Takes an acquisition and weights it so the domain and cost are taken into account . |
34,176 | def acquisition_function_withGradients ( self , x ) : f_acqu , df_acqu = self . _compute_acq_withGradients ( x ) cost_x , cost_grad_x = self . cost_withGradients ( x ) f_acq_cost = f_acqu / cost_x df_acq_cost = ( df_acqu * cost_x - f_acqu * cost_grad_x ) / ( cost_x ** 2 ) return - f_acq_cost * self . space . indicator_... | Takes an acquisition and it gradient and weights it so the domain and cost are taken into account . |
34,177 | def reshape ( x , input_dim ) : x = np . array ( x ) if x . size == input_dim : x = x . reshape ( ( 1 , input_dim ) ) return x | Reshapes x into a matrix with input_dim columns |
34,178 | def spawn ( f ) : def fun ( pipe , x ) : pipe . send ( f ( x ) ) pipe . close ( ) return fun | Function for parallel evaluation of the acquisition function |
34,179 | def values_to_array ( input_values ) : if type ( input_values ) == tuple : values = np . array ( input_values ) . reshape ( - 1 , 1 ) elif type ( input_values ) == np . ndarray : values = np . atleast_2d ( input_values ) elif type ( input_values ) == int or type ( input_values ) == float or type ( np . int64 ) : values... | Transforms a values of int float and tuples to a column vector numpy array |
34,180 | def merge_values ( values1 , values2 ) : array1 = values_to_array ( values1 ) array2 = values_to_array ( values2 ) if array1 . size == 0 : return array2 if array2 . size == 0 : return array1 merged_array = [ ] for row_array1 in array1 : for row_array2 in array2 : merged_row = np . hstack ( ( row_array1 , row_array2 ) )... | Merges two numpy arrays by calculating all possible combinations of rows |
34,181 | def normalize ( Y , normalization_type = 'stats' ) : Y = np . asarray ( Y , dtype = float ) if np . max ( Y . shape ) != Y . size : raise NotImplementedError ( 'Only 1-dimensional arrays are supported.' ) if normalization_type == 'stats' : Y_norm = Y - Y . mean ( ) std = Y . std ( ) if std > 0 : Y_norm /= std elif norm... | Normalize the vector Y using statistics or its range . |
34,182 | def get_samples ( self , init_points_count ) : init_points_count = self . _adjust_init_points_count ( init_points_count ) samples = np . empty ( ( init_points_count , self . space . dimensionality ) ) random_design = RandomDesign ( self . space ) random_design . fill_noncontinous_variables ( samples ) if self . space .... | This method may return less points than requested . The total number of generated points is the smallest closest integer of n^d to the selected amount of points . |
34,183 | def get_samples_with_constraints ( self , init_points_count ) : samples = np . empty ( ( 0 , self . space . dimensionality ) ) while samples . shape [ 0 ] < init_points_count : domain_samples = self . get_samples_without_constraints ( init_points_count ) valid_indices = ( self . space . indicator_constraints ( domain_s... | Draw random samples and only save those that satisfy constraints Finish when required number of samples is generated |
34,184 | def fill_noncontinous_variables ( self , samples ) : init_points_count = samples . shape [ 0 ] for ( idx , var ) in enumerate ( self . space . space_expanded ) : if isinstance ( var , DiscreteVariable ) or isinstance ( var , CategoricalVariable ) : sample_var = np . atleast_2d ( np . random . choice ( var . domain , in... | Fill sample values to non - continuous variables in place |
34,185 | def _get_obj ( self , space ) : obj_func = self . obj_func from . . core . task import SingleObjective return SingleObjective ( obj_func , self . config [ 'resources' ] [ 'cores' ] , space = space , unfold_args = True ) | Imports the acquisition function . |
34,186 | def _get_space ( self ) : assert 'space' in self . config , 'The search space is NOT configured!' space_config = self . config [ 'space' ] constraint_config = self . config [ 'constraints' ] from . . core . task . space import Design_space return Design_space . fromConfig ( space_config , constraint_config ) | Imports the domain . |
34,187 | def _get_model ( self ) : from copy import deepcopy model_args = deepcopy ( self . config [ 'model' ] ) del model_args [ 'type' ] from . . models import select_model return select_model ( self . config [ 'model' ] [ 'type' ] ) . fromConfig ( model_args ) | Imports the model . |
34,188 | def _get_acquisition ( self , model , space ) : from copy import deepcopy acqOpt_config = deepcopy ( self . config [ 'acquisition' ] [ 'optimizer' ] ) acqOpt_name = acqOpt_config [ 'name' ] del acqOpt_config [ 'name' ] from . . optimization import AcquisitionOptimizer acqOpt = AcquisitionOptimizer ( space , acqOpt_name... | Imports the acquisition |
34,189 | def _get_acq_evaluator ( self , acq ) : from . . core . evaluators import select_evaluator from copy import deepcopy eval_args = deepcopy ( self . config [ 'acquisition' ] [ 'evaluator' ] ) del eval_args [ 'type' ] return select_evaluator ( self . config [ 'acquisition' ] [ 'evaluator' ] [ 'type' ] ) ( acq , ** eval_ar... | Imports the evaluator |
34,190 | def _check_stop ( self , iters , elapsed_time , converged ) : r_c = self . config [ 'resources' ] stop = False if converged == 0 : stop = True if r_c [ 'maximum-iterations' ] != 'NA' and iters >= r_c [ 'maximum-iterations' ] : stop = True if r_c [ 'max-run-time' ] != 'NA' and elapsed_time / 60. >= r_c [ 'max-run-time' ... | Defines the stopping criterion . |
34,191 | def run ( self ) : space = self . _get_space ( ) obj_func = self . _get_obj ( space ) model = self . _get_model ( ) acq = self . _get_acquisition ( model , space ) acq_eval = self . _get_acq_evaluator ( acq ) from . . experiment_design import initial_design X_init = initial_design ( self . config [ 'initialization' ] [... | Runs the optimization using the previously loaded elements . |
34,192 | def choose_optimizer ( optimizer_name , bounds ) : if optimizer_name == 'lbfgs' : optimizer = OptLbfgs ( bounds ) elif optimizer_name == 'DIRECT' : optimizer = OptDirect ( bounds ) elif optimizer_name == 'CMA' : optimizer = OptCma ( bounds ) else : raise InvalidVariableNameError ( 'Invalid optimizer selected.' ) return... | Selects the type of local optimizer |
34,193 | def evaluator_creator ( self , evaluator_type , acquisition , batch_size , model_type , model , space , acquisition_optimizer ) : acquisition_transformation = self . kwargs . get ( 'acquisition_transformation' , 'none' ) if batch_size == 1 or evaluator_type == 'sequential' : return Sequential ( acquisition ) elif batch... | Acquisition chooser from the available options . Guide the optimization through sequential or parallel evalutions of the objective . |
34,194 | def _compute_acq ( self , x ) : m , s = self . model . predict ( x ) f_acqu = - m + self . exploration_weight * s return f_acqu | Computes the GP - Lower Confidence Bound |
34,195 | def _compute_acq_withGradients ( self , x ) : m , s , dmdx , dsdx = self . model . predict_withGradients ( x ) f_acqu = - m + self . exploration_weight * s df_acqu = - dmdx + self . exploration_weight * dsdx return f_acqu , df_acqu | Computes the GP - Lower Confidence Bound and its derivative |
34,196 | def create_variable ( descriptor ) : if descriptor [ 'type' ] == 'continuous' : return ContinuousVariable ( descriptor [ 'name' ] , descriptor [ 'domain' ] , descriptor . get ( 'dimensionality' , 1 ) ) elif descriptor [ 'type' ] == 'bandit' : return BanditVariable ( descriptor [ 'name' ] , descriptor [ 'domain' ] , des... | Creates a variable from a dictionary descriptor |
34,197 | def expand ( self ) : expanded_variables = [ ] for i in range ( self . dimensionality ) : one_d_variable = deepcopy ( self ) one_d_variable . dimensionality = 1 if self . dimensionality > 1 : one_d_variable . name = '{}_{}' . format ( self . name , i + 1 ) else : one_d_variable . name = self . name one_d_variable . dim... | Builds a list of single dimensional variables representing current variable . |
34,198 | def round ( self , value_array ) : min_value = self . domain [ 0 ] max_value = self . domain [ 1 ] rounded_value = value_array [ 0 ] if rounded_value < min_value : rounded_value = min_value elif rounded_value > max_value : rounded_value = max_value return [ rounded_value ] | If value falls within bounds just return it otherwise return min or max whichever is closer to the value Assumes an 1d array with a single element as an input . |
34,199 | def round ( self , value_array ) : distances = np . linalg . norm ( np . array ( self . domain ) - value_array , axis = 1 ) idx = np . argmin ( distances ) return [ self . domain [ idx ] ] | Rounds a bandit variable by selecting the closest point in the domain Closest here is defined by euclidian distance Assumes an 1d array of the same length as the single variable value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.