idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
33,100
def cg ( a , b , M , reg , f , df , G0 = None , numItermax = 200 , stopThr = 1e-9 , verbose = False , log = False ) : loop = 1 if log : log = { 'loss' : [ ] } if G0 is None : G = np . outer ( a , b ) else : G = G0 def cost ( G ) : return np . sum ( M * G ) + reg * f ( G ) f_val = cost ( G ) if log : log [ 'loss' ] . ap...
Solve the general regularized OT problem with conditional gradient
33,101
def gcg ( a , b , M , reg1 , reg2 , f , df , G0 = None , numItermax = 10 , numInnerItermax = 200 , stopThr = 1e-9 , verbose = False , log = False ) : loop = 1 if log : log = { 'loss' : [ ] } if G0 is None : G = np . outer ( a , b ) else : G = G0 def cost ( G ) : return np . sum ( M * G ) + reg1 * np . sum ( G * np . lo...
Solve the general regularized OT problem with the generalized conditional gradient
33,102
def projection_simplex ( V , z = 1 , axis = None ) : if axis == 1 : n_features = V . shape [ 1 ] U = np . sort ( V , axis = 1 ) [ : , : : - 1 ] z = np . ones ( len ( V ) ) * z cssv = np . cumsum ( U , axis = 1 ) - z [ : , np . newaxis ] ind = np . arange ( n_features ) + 1 cond = U - cssv / ind > 0 rho = np . count_non...
Projection of x onto the simplex scaled by z
33,103
def dual_obj_grad ( alpha , beta , a , b , C , regul ) : obj = np . dot ( alpha , a ) + np . dot ( beta , b ) grad_alpha = a . copy ( ) grad_beta = b . copy ( ) X = alpha [ : , np . newaxis ] + beta - C val , G = regul . delta_Omega ( X ) obj -= np . sum ( val ) grad_alpha -= G . sum ( axis = 1 ) grad_beta -= G . sum (...
Compute objective value and gradients of dual objective .
33,104
def solve_dual ( a , b , C , regul , method = "L-BFGS-B" , tol = 1e-3 , max_iter = 500 , verbose = False ) : def _func ( params ) : alpha = params [ : len ( a ) ] beta = params [ len ( a ) : ] obj , grad_alpha , grad_beta = dual_obj_grad ( alpha , beta , a , b , C , regul ) grad = np . concatenate ( ( grad_alpha , grad...
Solve the smoothed dual objective .
33,105
def semi_dual_obj_grad ( alpha , a , b , C , regul ) : obj = np . dot ( alpha , a ) grad = a . copy ( ) X = alpha [ : , np . newaxis ] - C val , G = regul . max_Omega ( X , b ) obj -= np . dot ( b , val ) grad -= np . dot ( G , b ) return obj , grad
Compute objective value and gradient of semi - dual objective .
33,106
def solve_semi_dual ( a , b , C , regul , method = "L-BFGS-B" , tol = 1e-3 , max_iter = 500 , verbose = False ) : def _func ( alpha ) : obj , grad = semi_dual_obj_grad ( alpha , a , b , C , regul ) return - obj , - grad alpha_init = np . zeros ( len ( a ) ) res = minimize ( _func , alpha_init , method = method , jac = ...
Solve the smoothed semi - dual objective .
33,107
def get_plan_from_dual ( alpha , beta , C , regul ) : X = alpha [ : , np . newaxis ] + beta - C return regul . delta_Omega ( X ) [ 1 ]
Retrieve optimal transportation plan from optimal dual potentials .
33,108
def get_plan_from_semi_dual ( alpha , b , C , regul ) : X = alpha [ : , np . newaxis ] - C return regul . max_Omega ( X , b ) [ 1 ] * b
Retrieve optimal transportation plan from optimal semi - dual potentials .
33,109
def smooth_ot_dual ( a , b , M , reg , reg_type = 'l2' , method = "L-BFGS-B" , stopThr = 1e-9 , numItermax = 500 , verbose = False , log = False ) : r if reg_type . lower ( ) in [ 'l2' , 'squaredl2' ] : regul = SquaredL2 ( gamma = reg ) elif reg_type . lower ( ) in [ 'entropic' , 'negentropy' , 'kl' ] : regul = NegEntr...
r Solve the regularized OT problem in the dual and return the OT matrix
33,110
def smooth_ot_semi_dual ( a , b , M , reg , reg_type = 'l2' , method = "L-BFGS-B" , stopThr = 1e-9 , numItermax = 500 , verbose = False , log = False ) : r if reg_type . lower ( ) in [ 'l2' , 'squaredl2' ] : regul = SquaredL2 ( gamma = reg ) elif reg_type . lower ( ) in [ 'entropic' , 'negentropy' , 'kl' ] : regul = Ne...
r Solve the regularized OT problem in the semi - dual and return the OT matrix
33,111
def kernel ( x1 , x2 , method = 'gaussian' , sigma = 1 , ** kwargs ) : if method . lower ( ) in [ 'gaussian' , 'gauss' , 'rbf' ] : K = np . exp ( - dist ( x1 , x2 ) / ( 2 * sigma ** 2 ) ) return K
Compute kernel matrix
33,112
def clean_zeros ( a , b , M ) : M2 = M [ a > 0 , : ] [ : , b > 0 ] . copy ( ) a2 = a [ a > 0 ] b2 = b [ b > 0 ] return a2 , b2 , M2
Remove all components with zeros weights in a and b
33,113
def dist ( x1 , x2 = None , metric = 'sqeuclidean' ) : if x2 is None : x2 = x1 if metric == "sqeuclidean" : return euclidean_distances ( x1 , x2 , squared = True ) return cdist ( x1 , x2 , metric = metric )
Compute distance between samples in x1 and x2 using function scipy . spatial . distance . cdist
33,114
def cost_normalization ( C , norm = None ) : if norm == "median" : C /= float ( np . median ( C ) ) elif norm == "max" : C /= float ( np . max ( C ) ) elif norm == "log" : C = np . log ( 1 + C ) elif norm == "loglog" : C = np . log ( 1 + np . log ( 1 + C ) ) return C
Apply normalization to the loss matrix
33,115
def parmap ( f , X , nprocs = multiprocessing . cpu_count ( ) ) : q_in = multiprocessing . Queue ( 1 ) q_out = multiprocessing . Queue ( ) proc = [ multiprocessing . Process ( target = fun , args = ( f , q_in , q_out ) ) for _ in range ( nprocs ) ] for p in proc : p . daemon = True p . start ( ) sent = [ q_in . put ( (...
paralell map for multiprocessing
33,116
def _is_deprecated ( func ) : if sys . version_info < ( 3 , 5 ) : raise NotImplementedError ( "This is only available for python3.5 " "or above" ) closures = getattr ( func , '__closure__' , [ ] ) if closures is None : closures = [ ] is_deprecated = ( 'deprecated' in '' . join ( [ c . cell_contents for c in closures if...
Helper to check if func is wraped by our deprecated decorator
33,117
def _decorate_fun ( self , fun ) : msg = "Function %s is deprecated" % fun . __name__ if self . extra : msg += "; %s" % self . extra def wrapped ( * args , ** kwargs ) : warnings . warn ( msg , category = DeprecationWarning ) return fun ( * args , ** kwargs ) wrapped . __name__ = fun . __name__ wrapped . __dict__ = fun...
Decorate function fun
33,118
def split_classes ( X , y ) : lstsclass = np . unique ( y ) return [ X [ y == i , : ] . astype ( np . float32 ) for i in lstsclass ]
split samples in X by classes in y
33,119
def fda ( X , y , p = 2 , reg = 1e-16 ) : mx = np . mean ( X ) X -= mx . reshape ( ( 1 , - 1 ) ) d = X . shape [ 1 ] xc = split_classes ( X , y ) nc = len ( xc ) p = min ( nc - 1 , p ) Cw = 0 for x in xc : Cw += np . cov ( x , rowvar = False ) Cw /= nc mxc = np . zeros ( ( d , nc ) ) for i in range ( nc ) : mxc [ : , i...
Fisher Discriminant Analysis
33,120
def sag_entropic_transport ( a , b , M , reg , numItermax = 10000 , lr = None ) : if lr is None : lr = 1. / max ( a / reg ) n_source = np . shape ( M ) [ 0 ] n_target = np . shape ( M ) [ 1 ] cur_beta = np . zeros ( n_target ) stored_gradient = np . zeros ( ( n_source , n_target ) ) sum_stored_gradient = np . zeros ( n...
Compute the SAG algorithm to solve the regularized discrete measures optimal transport max problem
33,121
def averaged_sgd_entropic_transport ( a , b , M , reg , numItermax = 300000 , lr = None ) : if lr is None : lr = 1. / max ( a / reg ) n_source = np . shape ( M ) [ 0 ] n_target = np . shape ( M ) [ 1 ] cur_beta = np . zeros ( n_target ) ave_beta = np . zeros ( n_target ) for cur_iter in range ( numItermax ) : k = cur_i...
Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem
33,122
def c_transform_entropic ( b , M , reg , beta ) : n_source = np . shape ( M ) [ 0 ] alpha = np . zeros ( n_source ) for i in range ( n_source ) : r = M [ i , : ] - beta min_r = np . min ( r ) exp_beta = np . exp ( - ( r - min_r ) / reg ) * b alpha [ i ] = min_r - reg * np . log ( np . sum ( exp_beta ) ) return alpha
The goal is to recover u from the c - transform .
33,123
def solve_semi_dual_entropic ( a , b , M , reg , method , numItermax = 10000 , lr = None , log = False ) : if method . lower ( ) == "sag" : opt_beta = sag_entropic_transport ( a , b , M , reg , numItermax , lr ) elif method . lower ( ) == "asgd" : opt_beta = averaged_sgd_entropic_transport ( a , b , M , reg , numIterma...
Compute the transportation matrix to solve the regularized discrete measures optimal transport max problem
33,124
def batch_grad_dual ( a , b , M , reg , alpha , beta , batch_size , batch_alpha , batch_beta ) : G = - ( np . exp ( ( alpha [ batch_alpha , None ] + beta [ None , batch_beta ] - M [ batch_alpha , : ] [ : , batch_beta ] ) / reg ) * a [ batch_alpha , None ] * b [ None , batch_beta ] ) grad_beta = np . zeros ( np . shape ...
Computes the partial gradient of the dual optimal transport problem .
33,125
def sgd_entropic_regularization ( a , b , M , reg , batch_size , numItermax , lr ) : n_source = np . shape ( M ) [ 0 ] n_target = np . shape ( M ) [ 1 ] cur_alpha = np . zeros ( n_source ) cur_beta = np . zeros ( n_target ) for cur_iter in range ( numItermax ) : k = np . sqrt ( cur_iter + 1 ) batch_alpha = np . random ...
Compute the sgd algorithm to solve the regularized discrete measures optimal transport dual problem
33,126
def solve_dual_entropic ( a , b , M , reg , batch_size , numItermax = 10000 , lr = 1 , log = False ) : opt_alpha , opt_beta = sgd_entropic_regularization ( a , b , M , reg , batch_size , numItermax , lr ) pi = ( np . exp ( ( opt_alpha [ : , None ] + opt_beta [ None , : ] - M [ : , : ] ) / reg ) * a [ : , None ] * b [ N...
Compute the transportation matrix to solve the regularized discrete measures optimal transport dual problem
33,127
def flake ( self , message ) : self . _stdout . write ( str ( message ) ) self . _stdout . write ( '\n' )
pyflakes found something wrong with the code .
33,128
def counter ( items ) : results = { } for item in items : results [ item ] = results . get ( item , 0 ) + 1 return results
Simplest required implementation of collections . Counter . Required as 2 . 6 does not have Counter in collections .
33,129
def source_statement ( self ) : if self . _has_alias ( ) : return 'import %s as %s' % ( self . fullName , self . name ) else : return 'import %s' % self . fullName
Generate a source statement equivalent to the import .
33,130
def CLASSDEF ( self , node ) : for deco in node . decorator_list : self . handleNode ( deco , node ) for baseNode in node . bases : self . handleNode ( baseNode , node ) if not PY2 : for keywordNode in node . keywords : self . handleNode ( keywordNode , node ) self . pushScope ( ClassScope ) if ( self . withDoctest and...
Check names used in a class definition including its decorators base classes and the body of its definition . Additionally add its name to the current scope .
33,131
def isPythonFile ( filename ) : if filename . endswith ( '.py' ) : return True if filename . endswith ( "~" ) : return False max_bytes = 128 try : with open ( filename , 'rb' ) as f : text = f . read ( max_bytes ) if not text : return False except IOError : return False first_line = text . splitlines ( ) [ 0 ] return P...
Return True if filename points to a Python file .
33,132
def _exitOnSignal ( sigName , message ) : import signal try : sigNumber = getattr ( signal , sigName ) except AttributeError : return def handler ( sig , f ) : sys . exit ( message ) try : signal . signal ( sigNumber , handler ) except ValueError : pass
Handles a signal with sys . exit .
33,133
def _get_subclasses_recurse ( self , model , levels = None ) : related_objects = [ f for f in model . _meta . get_fields ( ) if isinstance ( f , OneToOneRel ) ] rels = [ rel for rel in related_objects if isinstance ( rel . field , OneToOneField ) and issubclass ( rel . field . model , model ) and model is not rel . fie...
Given a Model class find all related objects exploring children recursively returning a list of strings representing the relations for select_related
33,134
def _get_ancestors_path ( self , model , levels = None ) : if not issubclass ( model , self . model ) : raise ValueError ( "%r is not a subclass of %r" % ( model , self . model ) ) ancestry = [ ] parent_link = model . _meta . get_ancestor_link ( self . model ) if levels : levels -= 1 while parent_link is not None : rel...
Serves as an opposite to _get_subclasses_recurse instead walking from the Model class up the Model s ancestry and constructing the desired select_related string backwards .
33,135
def get_queryset ( self ) : kwargs = { 'model' : self . model , 'using' : self . _db } if hasattr ( self , '_hints' ) : kwargs [ 'hints' ] = self . _hints return self . _queryset_class ( ** kwargs ) . filter ( is_removed = False )
Return queryset limited to not removed entries .
33,136
def previous ( self , field ) : if self . instance . pk and field in self . deferred_fields and field not in self . saved_data : if field not in self . instance . __dict__ : self . get_field_value ( field ) else : current_value = self . get_field_value ( field ) self . instance . refresh_from_db ( fields = [ field ] ) ...
Returns currently saved value of given field
33,137
def get_field_map ( self , cls ) : field_map = dict ( ( field , field ) for field in self . fields ) all_fields = dict ( ( f . name , f . attname ) for f in cls . _meta . fields ) field_map . update ( ** dict ( ( k , v ) for ( k , v ) in all_fields . items ( ) if k in field_map ) ) return field_map
Returns dict mapping fields names to model attribute names
33,138
def add_status_query_managers ( sender , ** kwargs ) : if not issubclass ( sender , StatusModel ) : return if django . VERSION >= ( 1 , 10 ) : default_manager = sender . _meta . default_manager for value , display in getattr ( sender , 'STATUS' , ( ) ) : if _field_exists ( sender , value ) : raise ImproperlyConfigured ...
Add a Querymanager for each status item dynamically .
33,139
def add_timeframed_query_manager ( sender , ** kwargs ) : if not issubclass ( sender , TimeFramedModel ) : return if _field_exists ( sender , 'timeframed' ) : raise ImproperlyConfigured ( "Model '%s' has a field named 'timeframed' " "which conflicts with the TimeFramedModel manager." % sender . __name__ ) sender . add_...
Add a QueryManager for a specific timeframe .
33,140
def to_text ( path , language = 'fra' ) : import subprocess from distutils import spawn import tempfile import time if not spawn . find_executable ( 'tesseract' ) : raise EnvironmentError ( 'tesseract not installed.' ) if not spawn . find_executable ( 'convert' ) : raise EnvironmentError ( 'imagemagick not installed.' ...
Wraps Tesseract 4 OCR with custom language model .
33,141
def to_text ( path , bucket_name = 'cloud-vision-84893' , language = 'fr' ) : import os from google . cloud import vision from google . cloud import storage from google . protobuf import json_format mime_type = 'application/pdf' path_dir , filename = os . path . split ( path ) result_blob_basename = filename . replace ...
Sends PDF files to Google Cloud Vision for OCR .
33,142
def write_to_file ( data , path ) : if path . endswith ( '.csv' ) : filename = path else : filename = path + '.csv' if sys . version_info [ 0 ] < 3 : openfile = open ( filename , "wb" ) else : openfile = open ( filename , "w" , newline = '' ) with openfile as csv_file : writer = csv . writer ( csv_file , delimiter = ',...
Export extracted fields to csv
33,143
def to_text ( path ) : import subprocess from distutils import spawn if not spawn . find_executable ( 'tesseract' ) : raise EnvironmentError ( 'tesseract not installed.' ) if not spawn . find_executable ( 'convert' ) : raise EnvironmentError ( 'imagemagick not installed.' ) convert = [ 'convert' , '-density' , '350' , ...
Wraps Tesseract OCR .
33,144
def extract ( self , content , output ) : for table in self [ 'tables' ] : plugin_settings = DEFAULT_OPTIONS . copy ( ) plugin_settings . update ( table ) table = plugin_settings assert 'start' in table , 'Table start regex missing' assert 'end' in table , 'Table end regex missing' assert 'body' in table , 'Table body ...
Try to extract tables from an invoice
33,145
def to_text ( path ) : import subprocess from distutils import spawn if spawn . find_executable ( "pdftotext" ) : out , err = subprocess . Popen ( [ "pdftotext" , '-layout' , '-enc' , 'UTF-8' , path , '-' ] , stdout = subprocess . PIPE ) . communicate ( ) return out else : raise EnvironmentError ( 'pdftotext not instal...
Wrapper around Poppler pdftotext .
33,146
def prepare_input ( self , extracted_str ) : if self . options [ 'remove_whitespace' ] : optimized_str = re . sub ( ' +' , '' , extracted_str ) else : optimized_str = extracted_str if self . options [ 'remove_accents' ] : optimized_str = unidecode ( optimized_str ) if self . options [ 'lowercase' ] : optimized_str = op...
Input raw string and do transformations as set in template file .
33,147
def matches_input ( self , optimized_str ) : if all ( [ keyword in optimized_str for keyword in self [ 'keywords' ] ] ) : logger . debug ( 'Matched template %s' , self [ 'template_name' ] ) return True
See if string matches keywords set in template file
33,148
def parse_date ( self , value ) : res = dateparser . parse ( value , date_formats = self . options [ 'date_formats' ] , languages = self . options [ 'languages' ] ) logger . debug ( "result of date parsing=%s" , res ) return res
Parses date and returns date after parsing
33,149
def write_to_file ( data , path ) : if path . endswith ( '.json' ) : filename = path else : filename = path + '.json' with codecs . open ( filename , "w" , encoding = 'utf-8' ) as json_file : for line in data : line [ 'date' ] = line [ 'date' ] . strftime ( '%d/%m/%Y' ) print ( type ( json ) ) print ( json ) json . dum...
Export extracted fields to json
33,150
def create_parser ( ) : parser = argparse . ArgumentParser ( description = 'Extract structured data from PDF files and save to CSV or JSON.' ) parser . add_argument ( '--input-reader' , choices = input_mapping . keys ( ) , default = 'pdftotext' , help = 'Choose text extraction function. Default: pdftotext' , ) parser ....
Returns argument parser
33,151
def main ( args = None ) : if args is None : parser = create_parser ( ) args = parser . parse_args ( ) if args . debug : logging . basicConfig ( level = logging . DEBUG ) else : logging . basicConfig ( level = logging . INFO ) input_module = input_mapping [ args . input_reader ] output_module = output_mapping [ args . ...
Take folder or single file and analyze each .
33,152
def write_to_file ( data , path ) : if path . endswith ( '.xml' ) : filename = path else : filename = path + '.xml' tag_data = ET . Element ( 'data' ) xml_file = open ( filename , "w" ) i = 0 for line in data : i += 1 tag_item = ET . SubElement ( tag_data , 'item' ) tag_date = ET . SubElement ( tag_item , 'date' ) tag_...
Export extracted fields to xml
33,153
def read_templates ( folder = None ) : output = [ ] if folder is None : folder = pkg_resources . resource_filename ( __name__ , 'templates' ) for path , subdirs , files in os . walk ( folder ) : for name in sorted ( files ) : if name . endswith ( '.yml' ) : with open ( os . path . join ( path , name ) , 'rb' ) as f : e...
Load yaml templates from template folder . Return list of dicts .
33,154
def to_text ( path ) : try : from StringIO import StringIO import sys reload ( sys ) sys . setdefaultencoding ( 'utf8' ) except ImportError : from io import StringIO from pdfminer . pdfinterp import PDFResourceManager , PDFPageInterpreter from pdfminer . converter import TextConverter from pdfminer . layout import LAPa...
Wrapper around pdfminer .
33,155
def analyze ( problem , X , Y , second_order = False , print_to_console = False , seed = None ) : if seed : np . random . seed ( seed ) problem = extend_bounds ( problem ) num_vars = problem [ 'num_vars' ] X = generate_contrast ( problem ) main_effect = ( 1. / ( 2 * num_vars ) ) * np . dot ( Y , X ) Si = ResultDict ( (...
Perform a fractional factorial analysis
33,156
def to_df ( self ) : names = self [ 'names' ] main_effect = self [ 'ME' ] interactions = self . get ( 'IE' , None ) inter_effect = None if interactions : interaction_names = self . get ( 'interaction_names' ) names = [ name for name in names if not isinstance ( name , list ) ] inter_effect = pd . DataFrame ( { 'IE' : i...
Conversion method to Pandas DataFrame . To be attached to ResultDict .
33,157
def interactions ( problem , Y , print_to_console = False ) : names = problem [ 'names' ] num_vars = problem [ 'num_vars' ] X = generate_contrast ( problem ) ie_names = [ ] IE = [ ] for col in range ( X . shape [ 1 ] ) : for col_2 in range ( col ) : x = X [ : , col ] * X [ : , col_2 ] var_names = ( names [ col_2 ] , na...
Computes the second order effects
33,158
def avail_approaches ( pkg ) : methods = [ modname for importer , modname , ispkg in pkgutil . walk_packages ( path = pkg . __path__ ) if modname not in [ 'common_args' , 'directions' , 'sobol_sequence' ] ] return methods
Create list of available modules .
33,159
def scale_samples ( params , bounds ) : b = np . array ( bounds ) lower_bounds = b [ : , 0 ] upper_bounds = b [ : , 1 ] if np . any ( lower_bounds >= upper_bounds ) : raise ValueError ( "Bounds are not legal" ) np . add ( np . multiply ( params , ( upper_bounds - lower_bounds ) , out = params ) , lower_bounds , out = p...
Rescale samples in 0 - to - 1 range to arbitrary bounds
33,160
def nonuniform_scale_samples ( params , bounds , dists ) : b = np . array ( bounds ) conv_params = np . zeros_like ( params ) for i in range ( conv_params . shape [ 1 ] ) : b1 = b [ i ] [ 0 ] b2 = b [ i ] [ 1 ] if dists [ i ] == 'triang' : if b1 <= 0 or b2 <= 0 or b2 >= 1 : raise ValueError ( ) else : conv_params [ : ,...
Rescale samples in 0 - to - 1 range to other distributions
33,161
def read_param_file ( filename , delimiter = None ) : names = [ ] bounds = [ ] groups = [ ] dists = [ ] num_vars = 0 fieldnames = [ 'name' , 'lower_bound' , 'upper_bound' , 'group' , 'dist' ] with open ( filename , 'rU' ) as csvfile : dialect = csv . Sniffer ( ) . sniff ( csvfile . read ( 1024 ) , delimiters = delimite...
Unpacks a parameter file into a dictionary
33,162
def compute_groups_matrix ( groups ) : if not groups : return None num_vars = len ( groups ) unique_group_names = list ( OrderedDict . fromkeys ( groups ) ) number_of_groups = len ( unique_group_names ) indices = dict ( [ ( x , i ) for ( i , x ) in enumerate ( unique_group_names ) ] ) output = np . zeros ( ( num_vars ,...
Generate matrix which notes factor membership of groups
33,163
def requires_gurobipy ( _has_gurobi ) : def _outer_wrapper ( wrapped_function ) : def _wrapper ( * args , ** kwargs ) : if _has_gurobi : result = wrapped_function ( * args , ** kwargs ) else : warn ( "Gurobi not available" , ImportWarning ) result = None return result return _wrapper return _outer_wrapper
Decorator function which takes a boolean _has_gurobi as an argument . Use decorate any functions which require gurobi . Raises an import error at runtime if gurobi is not present . Note that all runtime errors should be avoided in the working code using brute force options as preference .
33,164
def compute_grouped_sigma ( ungrouped_sigma , group_matrix ) : group_matrix = np . array ( group_matrix , dtype = np . bool ) sigma_masked = np . ma . masked_array ( ungrouped_sigma * group_matrix . T , mask = ( group_matrix ^ 1 ) . T ) sigma_agg = np . ma . mean ( sigma_masked , axis = 1 ) sigma = np . zeros ( group_m...
Returns sigma for the groups of parameter values in the argument ungrouped_metric where the group consists of no more than one parameter
33,165
def compute_grouped_metric ( ungrouped_metric , group_matrix ) : group_matrix = np . array ( group_matrix , dtype = np . bool ) mu_star_masked = np . ma . masked_array ( ungrouped_metric * group_matrix . T , mask = ( group_matrix ^ 1 ) . T ) mean_of_mu_star = np . ma . mean ( mu_star_masked , axis = 1 ) return mean_of_...
Computes the mean value for the groups of parameter values in the argument ungrouped_metric
33,166
def compute_mu_star_confidence ( ee , num_trajectories , num_resamples , conf_level ) : ee_resampled = np . zeros ( [ num_trajectories ] ) mu_star_resampled = np . zeros ( [ num_resamples ] ) if not 0 < conf_level < 1 : raise ValueError ( "Confidence level must be between 0-1." ) resample_index = np . random . randint ...
Uses bootstrapping where the elementary effects are resampled with replacement to produce a histogram of resampled mu_star metrics . This resample is used to produce a confidence interval .
33,167
def timestamp ( num_params , p_levels , k_choices , N ) : string = "_v%s_l%s_gs%s_k%s_N%s_%s.txt" % ( num_params , p_levels , k_choices , N , dt . strftime ( dt . now ( ) , "%d%m%y%H%M%S" ) ) return string
Returns a uniform timestamp with parameter values for file identification
33,168
def brute_force_most_distant ( self , input_sample , num_samples , num_params , k_choices , num_groups = None ) : scores = self . find_most_distant ( input_sample , num_samples , num_params , k_choices , num_groups ) maximum_combo = self . find_maximum ( scores , num_samples , k_choices ) return maximum_combo
Use brute force method to find most distant trajectories
33,169
def find_most_distant ( self , input_sample , num_samples , num_params , k_choices , num_groups = None ) : if nchoosek ( num_samples , k_choices ) >= sys . maxsize : raise ValueError ( "Number of combinations is too large" ) number_of_combinations = int ( nchoosek ( num_samples , k_choices ) ) distance_matrix = self . ...
Finds the k_choices most distant choices from the num_samples trajectories contained in input_sample
33,170
def mappable ( combos , pairwise , distance_matrix ) : combos = np . array ( combos ) combo_list = combos [ : , pairwise [ : , ] ] addresses = tuple ( [ combo_list [ : , : , 1 ] , combo_list [ : , : , 0 ] ] ) all_distances = distance_matrix [ addresses ] new_scores = np . sqrt ( np . einsum ( 'ij,ij->i' , all_distances...
Obtains scores from the distance_matrix for each pairwise combination held in the combos array
33,171
def find_maximum ( self , scores , N , k_choices ) : if not isinstance ( scores , np . ndarray ) : raise TypeError ( "Scores input is not a numpy array" ) index_of_maximum = int ( scores . argmax ( ) ) maximum_combo = self . nth ( combinations ( list ( range ( N ) ) , k_choices ) , index_of_maximum , None ) return sort...
Finds the k_choices maximum scores from scores
33,172
def nth ( iterable , n , default = None ) : if type ( n ) != int : raise TypeError ( "n is not an integer" ) return next ( islice ( iterable , n , None ) , default )
Returns the nth item or a default value
33,173
def sample ( problem , N , num_levels = 4 , optimal_trajectories = None , local_optimization = True ) : if problem . get ( 'groups' ) : sample = _sample_groups ( problem , N , num_levels ) else : sample = _sample_oat ( problem , N , num_levels ) if optimal_trajectories : sample = _compute_optimised_trajectories ( probl...
Generate model inputs using the Method of Morris
33,174
def _sample_oat ( problem , N , num_levels = 4 ) : group_membership = np . asmatrix ( np . identity ( problem [ 'num_vars' ] , dtype = int ) ) num_params = group_membership . shape [ 0 ] sample = np . zeros ( ( N * ( num_params + 1 ) , num_params ) ) sample = np . array ( [ generate_trajectory ( group_membership , num_...
Generate trajectories without groups
33,175
def _sample_groups ( problem , N , num_levels = 4 ) : if len ( problem [ 'groups' ] ) != problem [ 'num_vars' ] : raise ValueError ( "Groups do not match to number of variables" ) group_membership , _ = compute_groups_matrix ( problem [ 'groups' ] ) if group_membership is None : raise ValueError ( "Please define the 'g...
Generate trajectories for groups
33,176
def generate_trajectory ( group_membership , num_levels = 4 ) : delta = compute_delta ( num_levels ) num_params = group_membership . shape [ 0 ] num_groups = group_membership . shape [ 1 ] B = np . tril ( np . ones ( [ num_groups + 1 , num_groups ] , dtype = int ) , - 1 ) P_star = generate_p_star ( num_groups ) J = np ...
Return a single trajectory
33,177
def generate_p_star ( num_groups ) : p_star = np . eye ( num_groups , num_groups ) rd . shuffle ( p_star ) return p_star
Describe the order in which groups move
33,178
def parse_subargs ( module , parser , method , opts ) : module . cli_args ( parser ) subargs = parser . parse_args ( opts ) return subargs
Attach argument parser for action specific options .
33,179
def find_local_maximum ( self , input_sample , N , num_params , k_choices , num_groups = None ) : distance_matrix = self . compute_distance_matrix ( input_sample , N , num_params , num_groups , local_optimization = True ) tot_indices_list = [ ] tot_max_array = np . zeros ( k_choices - 1 ) for i in range ( 1 , k_choices...
Find the most different trajectories in the input sample using a local approach
33,180
def sum_distances ( self , indices , distance_matrix ) : combs_tup = np . array ( tuple ( combinations ( indices , 2 ) ) ) combs = np . array ( [ [ i [ 0 ] for i in combs_tup ] , [ i [ 1 ] for i in combs_tup ] ] ) dist = np . sqrt ( np . sum ( np . square ( distance_matrix [ combs [ 0 ] , combs [ 1 ] ] ) , axis = 0 ) )...
Calculate combinatorial distance between a select group of trajectories indicated by indices
33,181
def get_max_sum_ind ( self , indices_list , distances , i , m ) : if len ( indices_list ) != len ( distances ) : msg = "Indices and distances are lists of different length." + "Length indices_list = {} and length distances = {}." + "In loop i = {} and m = {}" raise ValueError ( msg . format ( len ( indices_list ) , l...
Get the indices that belong to the maximum distance in distances
33,182
def add_indices ( self , indices , distance_matrix ) : list_new_indices = [ ] for i in range ( 0 , len ( distance_matrix ) ) : if i not in indices : list_new_indices . append ( indices + ( i , ) ) return list_new_indices
Adds extra indices for the combinatorial problem .
33,183
def to_df ( self ) : return pd . DataFrame ( { k : v for k , v in self . items ( ) if k is not 'names' } , index = self [ 'names' ] )
Convert dict structure into Pandas DataFrame .
33,184
def horizontal_bar_plot ( ax , Si , param_dict , sortby = 'mu_star' , unit = '' ) : assert sortby in [ 'mu_star' , 'mu_star_conf' , 'sigma' , 'mu' ] names_sorted = _sort_Si ( Si , 'names' , sortby ) mu_star_sorted = _sort_Si ( Si , 'mu_star' , sortby ) mu_star_conf_sorted = _sort_Si ( Si , 'mu_star_conf' , sortby ) y_p...
Updates a matplotlib axes instance with a horizontal bar plot
33,185
def sample_histograms ( fig , input_sample , problem , param_dict ) : num_vars = problem [ 'num_vars' ] names = problem [ 'names' ] framing = 101 + ( num_vars * 10 ) num_levels = len ( set ( input_sample [ : , 1 ] ) ) out = [ ] for variable in range ( num_vars ) : ax = fig . add_subplot ( framing + variable ) out . app...
Plots a set of subplots of histograms of the input sample
33,186
def extend_bounds ( problem ) : num_vars = problem [ 'num_vars' ] num_ff_vars = 2 ** find_smallest ( num_vars ) num_dummy_variables = num_ff_vars - num_vars bounds = list ( problem [ 'bounds' ] ) names = problem [ 'names' ] if num_dummy_variables > 0 : bounds . extend ( [ [ 0 , 1 ] for x in range ( num_dummy_variables ...
Extends the problem bounds to the nearest power of two
33,187
def generate_contrast ( problem ) : num_vars = problem [ 'num_vars' ] k = [ 2 ** n for n in range ( 16 ) ] k_chosen = 2 ** find_smallest ( num_vars ) contrast = np . vstack ( [ hadamard ( k_chosen ) , - hadamard ( k_chosen ) ] ) return contrast
Generates the raw sample from the problem file
33,188
def sample ( problem , seed = None ) : if seed : np . random . seed ( seed ) contrast = generate_contrast ( problem ) sample = np . array ( ( contrast + 1. ) / 2 , dtype = np . float ) problem = extend_bounds ( problem ) scale_samples ( sample , problem [ 'bounds' ] ) return sample
Generates model inputs using a fractional factorial sample
33,189
def cli_action ( args ) : problem = read_param_file ( args . paramfile ) param_values = sample ( problem , seed = args . seed ) np . savetxt ( args . output , param_values , delimiter = args . delimiter , fmt = '%.' + str ( args . precision ) + 'e' )
Run sampling method
33,190
def setup ( parser ) : parser . add_argument ( '-p' , '--paramfile' , type = str , required = True , help = 'Parameter Range File' ) parser . add_argument ( '-o' , '--output' , type = str , required = True , help = 'Output File' ) parser . add_argument ( '-s' , '--seed' , type = int , required = False , default = None ...
Add common sampling options to CLI parser .
33,191
def run_cli ( cli_parser , run_sample , known_args = None ) : parser = create ( cli_parser ) args = parser . parse_args ( known_args ) run_sample ( args )
Run sampling with CLI arguments .
33,192
def run_checks ( number_samples , k_choices ) : assert isinstance ( k_choices , int ) , "Number of optimal trajectories should be an integer" if k_choices < 2 : raise ValueError ( "The number of optimal trajectories must be set to 2 or more." ) if k_choices >= number_samples : msg = "The number of optimal trajectories ...
Runs checks on k_choices
33,193
def _make_index_list ( num_samples , num_params , num_groups = None ) : if num_groups is None : num_groups = num_params index_list = [ ] for j in range ( num_samples ) : index_list . append ( np . arange ( num_groups + 1 ) + j * ( num_groups + 1 ) ) return index_list
Identify indices of input sample associated with each trajectory
33,194
def compile_output ( self , input_sample , num_samples , num_params , maximum_combo , num_groups = None ) : if num_groups is None : num_groups = num_params self . check_input_sample ( input_sample , num_groups , num_samples ) index_list = self . _make_index_list ( num_samples , num_params , num_groups ) output = np . z...
Picks the trajectories from the input
33,195
def check_input_sample ( input_sample , num_params , num_samples ) : assert type ( input_sample ) == np . ndarray , "Input sample is not an numpy array" assert input_sample . shape [ 0 ] == ( num_params + 1 ) * num_samples , "Input sample does not match number of parameters or groups" assert np . any ( ( input_sample >...
Check the input_sample is valid
33,196
def compute_distance ( m , l ) : if np . shape ( m ) != np . shape ( l ) : raise ValueError ( "Input matrices are different sizes" ) if np . array_equal ( m , l ) : distance = 0 else : distance = np . array ( np . sum ( cdist ( m , l ) ) , dtype = np . float32 ) return distance
Compute distance between two trajectories
33,197
def compute_distance_matrix ( self , input_sample , num_samples , num_params , num_groups = None , local_optimization = False ) : if num_groups : self . check_input_sample ( input_sample , num_groups , num_samples ) else : self . check_input_sample ( input_sample , num_params , num_samples ) index_list = self . _make_i...
Computes the distance between each and every trajectory
33,198
def move_point_cat ( point , ipoint , to_clust , from_clust , cl_attr_freq , membship , centroids ) : membship [ to_clust , ipoint ] = 1 membship [ from_clust , ipoint ] = 0 for iattr , curattr in enumerate ( point ) : to_attr_counts = cl_attr_freq [ to_clust ] [ iattr ] from_attr_counts = cl_attr_freq [ from_clust ] [...
Move point between clusters categorical attributes .
33,199
def _labels_cost ( X , centroids , dissim , membship = None ) : X = check_array ( X ) n_points = X . shape [ 0 ] cost = 0. labels = np . empty ( n_points , dtype = np . uint16 ) for ipoint , curpoint in enumerate ( X ) : diss = dissim ( centroids , curpoint , X = X , membship = membship ) clust = np . argmin ( diss ) l...
Calculate labels and cost function given a matrix of points and a list of centroids for the k - modes algorithm .