idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
248,700 | def get_pg_info ( ) : from psycopg2 import connect , OperationalError log . debug ( "entered get_pg_info" ) try : conf = settings . DATABASES [ 'default' ] database = conf [ "NAME" ] user = conf [ "USER" ] host = conf [ "HOST" ] port = conf [ "PORT" ] password = conf [ "PASSWORD" ] except ( AttributeError , KeyError ) : log . error ( "No PostgreSQL connection info found in settings." ) return { "status" : NO_CONFIG } except TypeError : return { "status" : DOWN } log . debug ( "got past getting conf" ) try : start = datetime . now ( ) connection = connect ( database = database , user = user , host = host , port = port , password = password , connect_timeout = TIMEOUT_SECONDS , ) log . debug ( "at end of context manager" ) micro = ( datetime . now ( ) - start ) . microseconds connection . close ( ) except ( OperationalError , KeyError ) as ex : log . error ( "No PostgreSQL connection info found in settings. %s Error: %s" , conf , ex ) return { "status" : DOWN } log . debug ( "got to end of postgres check successfully" ) return { "status" : UP , "response_microseconds" : micro } | Check PostgreSQL connection . | 308 | 5 |
248,701 | def get_redis_info ( ) : from kombu . utils . url import _parse_url as parse_redis_url from redis import ( StrictRedis , ConnectionError as RedisConnectionError , ResponseError as RedisResponseError , ) for conf_name in ( 'REDIS_URL' , 'BROKER_URL' , 'CELERY_BROKER_URL' ) : if hasattr ( settings , conf_name ) : url = getattr ( settings , conf_name ) if url . startswith ( 'redis://' ) : break else : log . error ( "No redis connection info found in settings." ) return { "status" : NO_CONFIG } _ , host , port , _ , password , database , _ = parse_redis_url ( url ) start = datetime . now ( ) try : rdb = StrictRedis ( host = host , port = port , db = database , password = password , socket_timeout = TIMEOUT_SECONDS , ) info = rdb . info ( ) except ( RedisConnectionError , TypeError ) as ex : log . error ( "Error making Redis connection: %s" , ex . args ) return { "status" : DOWN } except RedisResponseError as ex : log . error ( "Bad Redis response: %s" , ex . args ) return { "status" : DOWN , "message" : "auth error" } micro = ( datetime . now ( ) - start ) . microseconds del rdb # the redis package does not support Redis's QUIT. ret = { "status" : UP , "response_microseconds" : micro , } fields = ( "uptime_in_seconds" , "used_memory" , "used_memory_peak" ) ret . update ( { x : info [ x ] for x in fields } ) return ret | Check Redis connection . | 413 | 5 |
248,702 | def get_elasticsearch_info ( ) : from elasticsearch import ( Elasticsearch , ConnectionError as ESConnectionError ) if hasattr ( settings , 'ELASTICSEARCH_URL' ) : url = settings . ELASTICSEARCH_URL else : return { "status" : NO_CONFIG } start = datetime . now ( ) try : search = Elasticsearch ( url , request_timeout = TIMEOUT_SECONDS ) search . info ( ) except ESConnectionError : return { "status" : DOWN } del search # The elasticsearch library has no "close" or "disconnect." micro = ( datetime . now ( ) - start ) . microseconds return { "status" : UP , "response_microseconds" : micro , } | Check Elasticsearch connection . | 163 | 5 |
248,703 | def get_celery_info ( ) : import celery if not getattr ( settings , 'USE_CELERY' , False ) : log . error ( "No celery config found. Set USE_CELERY in settings to enable." ) return { "status" : NO_CONFIG } start = datetime . now ( ) try : # pylint: disable=no-member app = celery . Celery ( 'tasks' ) app . config_from_object ( 'django.conf:settings' , namespace = 'CELERY' ) # Make sure celery is connected with max_retries=1 # and not the default of max_retries=None if the connection # is made lazily app . connection ( ) . ensure_connection ( max_retries = 1 ) celery_stats = celery . task . control . inspect ( ) . stats ( ) if not celery_stats : log . error ( "No running Celery workers were found." ) return { "status" : DOWN , "message" : "No running Celery workers" } except Exception as exp : # pylint: disable=broad-except log . error ( "Error connecting to the backend: %s" , exp ) return { "status" : DOWN , "message" : "Error connecting to the backend" } return { "status" : UP , "response_microseconds" : ( datetime . now ( ) - start ) . microseconds } | Check celery availability | 315 | 4 |
248,704 | def get_certificate_info ( ) : if hasattr ( settings , 'MIT_WS_CERTIFICATE' ) and settings . MIT_WS_CERTIFICATE : mit_ws_certificate = settings . MIT_WS_CERTIFICATE else : return { "status" : NO_CONFIG } app_cert = OpenSSL . crypto . load_certificate ( OpenSSL . crypto . FILETYPE_PEM , ( mit_ws_certificate if not isinstance ( mit_ws_certificate , str ) else mit_ws_certificate . encode ( ) . decode ( 'unicode_escape' ) . encode ( ) ) ) app_cert_expiration = datetime . strptime ( app_cert . get_notAfter ( ) . decode ( 'ascii' ) , '%Y%m%d%H%M%SZ' ) date_delta = app_cert_expiration - datetime . now ( ) # if more then 30 days left in expiry of certificate then app is safe return { 'app_cert_expires' : app_cert_expiration . strftime ( '%Y-%m-%dT%H:%M:%S' ) , 'status' : UP if date_delta . days > 30 else DOWN } | checks app certificate expiry status | 285 | 6 |
248,705 | def _start ( self ) : if self . whoami is None : me = self . get_me ( ) if me . get ( 'ok' , False ) : self . whoami = me [ 'result' ] else : raise ValueError ( 'Bot Cannot request information, check ' 'api_key' ) | Requests bot information based on current api_key and sets self . whoami to dictionary with username first_name and id of the configured bot . | 67 | 30 |
248,706 | def poll ( self , offset = None , poll_timeout = 600 , cooldown = 60 , debug = False ) : if self . config [ 'api_key' ] is None : raise ValueError ( 'config api_key is undefined' ) if offset or self . config . get ( 'offset' , None ) : self . offset = offset or self . config . get ( 'offset' , None ) self . _start ( ) while True : try : response = self . get_updates ( poll_timeout , self . offset ) if response . get ( 'ok' , False ) is False : raise ValueError ( response [ 'error' ] ) else : self . process_updates ( response ) except Exception as e : print ( 'Error: Unknown Exception' ) print ( e ) if debug : raise e else : time . sleep ( cooldown ) | These should also be in the config section but some here for overrides | 180 | 14 |
248,707 | def get_attr ( obj , attr , default = None ) : if '.' not in attr : return getattr ( obj , attr , default ) else : L = attr . split ( '.' ) return get_attr ( getattr ( obj , L [ 0 ] , default ) , '.' . join ( L [ 1 : ] ) , default ) | Recursive get object s attribute . May use dot notation . | 78 | 12 |
248,708 | def asset ( path ) : commit = bitcaster . get_full_version ( ) return mark_safe ( '{0}?{1}' . format ( _static ( path ) , commit ) ) | Join the given path with the STATIC_URL setting . | 44 | 12 |
248,709 | def get_client_ip ( request ) : try : return request . META [ 'HTTP_X_FORWARDED_FOR' ] . split ( ',' ) [ 0 ] . strip ( ) except ( KeyError , IndexError ) : return request . META . get ( 'REMOTE_ADDR' ) | Naively yank the first IP address in an X - Forwarded - For header and assume this is correct . | 68 | 23 |
248,710 | def _pack_image ( filename , max_size , form_field = 'image' , f = None ) : # image must be less than 700kb in size if f is None : try : if os . path . getsize ( filename ) > ( max_size * 1024 ) : raise TweepError ( 'File is too big, must be less than %skb.' % max_size ) except os . error as e : raise TweepError ( 'Unable to access file: %s' % e . strerror ) # build the mulitpart-formdata body fp = open ( filename , 'rb' ) else : f . seek ( 0 , 2 ) # Seek to end of file if f . tell ( ) > ( max_size * 1024 ) : raise TweepError ( 'File is too big, must be less than %skb.' % max_size ) f . seek ( 0 ) # Reset to beginning of file fp = f # image must be gif, jpeg, or png file_type = mimetypes . guess_type ( filename ) if file_type is None : raise TweepError ( 'Could not determine file type' ) file_type = file_type [ 0 ] if file_type not in [ 'image/gif' , 'image/jpeg' , 'image/png' ] : raise TweepError ( 'Invalid file type for image: %s' % file_type ) if isinstance ( filename , six . text_type ) : filename = filename . encode ( 'utf-8' ) BOUNDARY = b'Tw3ePy' body = [ ] body . append ( b'--' + BOUNDARY ) body . append ( 'Content-Disposition: form-data; name="{0}";' ' filename="{1}"' . format ( form_field , filename ) . encode ( 'utf-8' ) ) body . append ( 'Content-Type: {0}' . format ( file_type ) . encode ( 'utf-8' ) ) body . append ( b'' ) body . append ( fp . read ( ) ) body . append ( b'--' + BOUNDARY + b'--' ) body . append ( b'' ) fp . close ( ) body = b'\r\n' . join ( body ) # build headers headers = { 'Content-Type' : 'multipart/form-data; boundary=Tw3ePy' , 'Content-Length' : str ( len ( body ) ) } return headers , body | Pack image from file into multipart - formdata post body | 549 | 12 |
248,711 | def channel_submit_row ( context ) : change = context [ 'change' ] is_popup = context [ 'is_popup' ] save_as = context [ 'save_as' ] show_save = context . get ( 'show_save' , True ) show_save_and_continue = context . get ( 'show_save_and_continue' , True ) can_delete = context [ 'has_delete_permission' ] can_add = context [ 'has_add_permission' ] can_change = context [ 'has_change_permission' ] ctx = Context ( context ) ctx . update ( { 'show_delete_link' : ( not is_popup and can_delete and change and context . get ( 'show_delete' , True ) ) , 'show_save_as_new' : not is_popup and change and save_as , 'show_save_and_add_another' : ( can_add and not is_popup and ( not save_as or context [ 'add' ] ) ) , 'show_save_and_continue' : ( not is_popup and can_change and show_save_and_continue ) , 'show_save' : show_save , } ) return ctx | Display the row of buttons for delete and save . | 282 | 10 |
248,712 | def get_setting ( self , name ) : notfound = object ( ) value = getattr ( config , name , notfound ) if name . endswith ( '_WHITELISTED_DOMAINS' ) : if value : return value . split ( ',' ) else : return [ ] if value is notfound : value = getattr ( settings , name ) # Force text on URL named settings that are instance of Promise if name . endswith ( '_URL' ) : if isinstance ( value , Promise ) : value = force_text ( value ) value = resolve_url ( value ) return value | get configuration from constance . config first | 132 | 8 |
248,713 | def debug ( self , request , message , extra_tags = '' , fail_silently = False ) : add ( self . target_name , request , constants . DEBUG , message , extra_tags = extra_tags , fail_silently = fail_silently ) | Add a message with the DEBUG level . | 57 | 8 |
248,714 | def info ( self , request , message , extra_tags = '' , fail_silently = False ) : add ( self . target_name , request , constants . INFO , message , extra_tags = extra_tags , fail_silently = fail_silently ) | Add a message with the INFO level . | 57 | 8 |
248,715 | def success ( self , request , message , extra_tags = '' , fail_silently = False ) : add ( self . target_name , request , constants . SUCCESS , message , extra_tags = extra_tags , fail_silently = fail_silently ) | Add a message with the SUCCESS level . | 59 | 10 |
248,716 | def warning ( self , request , message , extra_tags = '' , fail_silently = False ) : add ( self . target_name , request , constants . WARNING , message , extra_tags = extra_tags , fail_silently = fail_silently ) | Add a message with the WARNING level . | 57 | 8 |
248,717 | def error ( self , request , message , extra_tags = '' , fail_silently = False ) : add ( self . target_name , request , constants . ERROR , message , extra_tags = extra_tags , fail_silently = fail_silently ) | Add a message with the ERROR level . | 57 | 8 |
248,718 | def signup ( request , signup_form = SignupForm , template_name = 'userena/signup_form.html' , success_url = None , extra_context = None ) : # If signup is disabled, return 403 if userena_settings . USERENA_DISABLE_SIGNUP : raise PermissionDenied # If no usernames are wanted and the default form is used, fallback to the # default form that doesn't display to enter the username. if userena_settings . USERENA_WITHOUT_USERNAMES and ( signup_form == SignupForm ) : signup_form = SignupFormOnlyEmail form = signup_form ( ) if request . method == 'POST' : form = signup_form ( request . POST , request . FILES ) if form . is_valid ( ) : user = form . save ( ) # Send the signup complete signal userena_signals . signup_complete . send ( sender = None , user = user ) if success_url : redirect_to = success_url else : redirect_to = reverse ( 'userena_signup_complete' , kwargs = { 'username' : user . username } ) # A new signed user should logout the old one. if request . user . is_authenticated ( ) : logout ( request ) if ( userena_settings . USERENA_SIGNIN_AFTER_SIGNUP and not userena_settings . USERENA_ACTIVATION_REQUIRED ) : user = authenticate ( identification = user . email , check_password = False ) login ( request , user ) return redirect ( redirect_to ) if not extra_context : extra_context = dict ( ) extra_context [ 'form' ] = form return ExtraContextTemplateView . as_view ( template_name = template_name , extra_context = extra_context ) ( request ) | Signup of an account . | 422 | 6 |
248,719 | def extend ( self , other ) : overlap = [ key for key in other . defaults if key in self . defaults ] if overlap : raise ValueError ( "Duplicate hyperparameter(s): %s" % " " . join ( overlap ) ) new = dict ( self . defaults ) new . update ( other . defaults ) return HyperparameterDefaults ( * * new ) | Return a new HyperparameterDefaults instance containing the hyperparameters from the current instance combined with those from other . | 81 | 24 |
248,720 | def with_defaults ( self , obj ) : self . check_valid_keys ( obj ) obj = dict ( obj ) for ( key , value ) in self . defaults . items ( ) : if key not in obj : obj [ key ] = value return obj | Given a dict of hyperparameter settings return a dict containing those settings augmented by the defaults for any keys missing from the dict . | 56 | 26 |
248,721 | def subselect ( self , obj ) : return dict ( ( key , value ) for ( key , value ) in obj . items ( ) if key in self . defaults ) | Filter a dict of hyperparameter settings to only those keys defined in this HyperparameterDefaults . | 36 | 21 |
248,722 | def check_valid_keys ( self , obj ) : invalid_keys = [ x for x in obj if x not in self . defaults ] if invalid_keys : raise ValueError ( "No such model parameters: %s. Valid parameters are: %s" % ( " " . join ( invalid_keys ) , " " . join ( self . defaults ) ) ) | Given a dict of hyperparameter settings throw an exception if any keys are not defined in this HyperparameterDefaults instance . | 78 | 26 |
248,723 | def models_grid ( self , * * kwargs ) : # Check parameters self . check_valid_keys ( kwargs ) for ( key , value ) in kwargs . items ( ) : if not isinstance ( value , list ) : raise ValueError ( "All parameters must be lists, but %s is %s" % ( key , str ( type ( value ) ) ) ) # Make models, using defaults. parameters = dict ( ( key , [ value ] ) for ( key , value ) in self . defaults . items ( ) ) parameters . update ( kwargs ) parameter_names = list ( parameters ) parameter_values = [ parameters [ name ] for name in parameter_names ] models = [ dict ( zip ( parameter_names , model_values ) ) for model_values in itertools . product ( * parameter_values ) ] return models | Make a grid of models by taking the cartesian product of all specified model parameter lists . | 185 | 18 |
248,724 | def fixed_length_vector_encoded_sequences ( self , vector_encoding_name ) : cache_key = ( "fixed_length_vector_encoding" , vector_encoding_name ) if cache_key not in self . encoding_cache : index_encoded_matrix = amino_acid . index_encoding ( self . fixed_length_sequences . values , amino_acid . AMINO_ACID_INDEX ) vector_encoded = amino_acid . fixed_vectors_encoding ( index_encoded_matrix , amino_acid . ENCODING_DATA_FRAMES [ vector_encoding_name ] ) result = vector_encoded [ self . indices ] self . encoding_cache [ cache_key ] = result return self . encoding_cache [ cache_key ] | Encode alleles . | 180 | 5 |
248,725 | def index_encoding ( sequences , letter_to_index_dict ) : df = pandas . DataFrame ( iter ( s ) for s in sequences ) result = df . replace ( letter_to_index_dict ) return result . values | Encode a sequence of same - length strings to a matrix of integers of the same shape . The map from characters to integers is given by letter_to_index_dict . | 52 | 36 |
248,726 | def apply_hyperparameter_renames ( cls , hyperparameters ) : for ( from_name , to_name ) in cls . hyperparameter_renames . items ( ) : if from_name in hyperparameters : value = hyperparameters . pop ( from_name ) if to_name : hyperparameters [ to_name ] = value return hyperparameters | Handle hyperparameter renames . | 83 | 7 |
248,727 | def borrow_cached_network ( klass , network_json , network_weights ) : assert network_weights is not None key = klass . keras_network_cache_key ( network_json ) if key not in klass . KERAS_MODELS_CACHE : # Cache miss. import keras . models network = keras . models . model_from_json ( network_json ) existing_weights = None else : # Cache hit. ( network , existing_weights ) = klass . KERAS_MODELS_CACHE [ key ] if existing_weights is not network_weights : network . set_weights ( network_weights ) klass . KERAS_MODELS_CACHE [ key ] = ( network , network_weights ) # As an added safety check we overwrite the fit method on the returned # model to throw an error if it is called. def throw ( * args , * * kwargs ) : raise NotImplementedError ( "Do not call fit on cached model." ) network . fit = throw return network | Return a keras Model with the specified architecture and weights . As an optimization when possible this will reuse architectures from a process - wide cache . | 230 | 28 |
248,728 | def network ( self , borrow = False ) : if self . _network is None and self . network_json is not None : self . load_weights ( ) if borrow : return self . borrow_cached_network ( self . network_json , self . network_weights ) else : import keras . models self . _network = keras . models . model_from_json ( self . network_json ) if self . network_weights is not None : self . _network . set_weights ( self . network_weights ) self . network_json = None self . network_weights = None return self . _network | Return the keras model associated with this predictor . | 132 | 10 |
248,729 | def load_weights ( self ) : if self . network_weights_loader : self . network_weights = self . network_weights_loader ( ) self . network_weights_loader = None | Load weights by evaluating self . network_weights_loader if needed . | 41 | 14 |
248,730 | def predict ( self , peptides , allele_encoding = None , batch_size = 4096 ) : assert self . prediction_cache is not None use_cache = ( allele_encoding is None and isinstance ( peptides , EncodableSequences ) ) if use_cache and peptides in self . prediction_cache : return self . prediction_cache [ peptides ] . copy ( ) x_dict = { 'peptide' : self . peptides_to_network_input ( peptides ) } if allele_encoding is not None : allele_input = self . allele_encoding_to_network_input ( allele_encoding ) x_dict [ 'allele' ] = allele_input network = self . network ( borrow = True ) raw_predictions = network . predict ( x_dict , batch_size = batch_size ) predictions = numpy . array ( raw_predictions , dtype = "float64" ) [ : , 0 ] result = to_ic50 ( predictions ) if use_cache : self . prediction_cache [ peptides ] = result return result | Predict affinities . | 237 | 6 |
248,731 | def make_scores ( ic50_y , ic50_y_pred , sample_weight = None , threshold_nm = 500 , max_ic50 = 50000 ) : y_pred = from_ic50 ( ic50_y_pred , max_ic50 ) try : auc = sklearn . metrics . roc_auc_score ( ic50_y <= threshold_nm , y_pred , sample_weight = sample_weight ) except ValueError as e : logging . warning ( e ) auc = numpy . nan try : f1 = sklearn . metrics . f1_score ( ic50_y <= threshold_nm , ic50_y_pred <= threshold_nm , sample_weight = sample_weight ) except ValueError as e : logging . warning ( e ) f1 = numpy . nan try : tau = scipy . stats . kendalltau ( ic50_y_pred , ic50_y ) [ 0 ] except ValueError as e : logging . warning ( e ) tau = numpy . nan return dict ( auc = auc , f1 = f1 , tau = tau ) | Calculate AUC F1 and Kendall Tau scores . | 251 | 12 |
248,732 | def variable_length_to_fixed_length_vector_encoding ( self , vector_encoding_name , left_edge = 4 , right_edge = 4 , max_length = 15 ) : cache_key = ( "fixed_length_vector_encoding" , vector_encoding_name , left_edge , right_edge , max_length ) if cache_key not in self . encoding_cache : fixed_length_sequences = ( self . sequences_to_fixed_length_index_encoded_array ( self . sequences , left_edge = left_edge , right_edge = right_edge , max_length = max_length ) ) result = amino_acid . fixed_vectors_encoding ( fixed_length_sequences , amino_acid . ENCODING_DATA_FRAMES [ vector_encoding_name ] ) assert result . shape [ 0 ] == len ( self . sequences ) self . encoding_cache [ cache_key ] = result return self . encoding_cache [ cache_key ] | Encode variable - length sequences using a fixed - length encoding designed for preserving the anchor positions of class I peptides . | 225 | 24 |
248,733 | def sequences_to_fixed_length_index_encoded_array ( klass , sequences , left_edge = 4 , right_edge = 4 , max_length = 15 ) : # Result array is int32, filled with X (null amino acid) value. result = numpy . full ( fill_value = amino_acid . AMINO_ACID_INDEX [ 'X' ] , shape = ( len ( sequences ) , max_length ) , dtype = "int32" ) df = pandas . DataFrame ( { "peptide" : sequences } ) df [ "length" ] = df . peptide . str . len ( ) middle_length = max_length - left_edge - right_edge # For efficiency we handle each supported peptide length using bulk # array operations. for ( length , sub_df ) in df . groupby ( "length" ) : if length < left_edge + right_edge : raise ValueError ( "Sequence '%s' (length %d) unsupported: length must be at " "least %d. There are %d total peptides with this length." % ( sub_df . iloc [ 0 ] . peptide , length , left_edge + right_edge , len ( sub_df ) ) ) if length > max_length : raise ValueError ( "Sequence '%s' (length %d) unsupported: length must be at " "most %d. There are %d total peptides with this length." % ( sub_df . iloc [ 0 ] . peptide , length , max_length , len ( sub_df ) ) ) # Array of shape (num peptides, length) giving fixed-length amino # acid encoding each peptide of the current length. fixed_length_sequences = numpy . stack ( sub_df . peptide . map ( lambda s : numpy . array ( [ amino_acid . AMINO_ACID_INDEX [ char ] for char in s ] ) ) . values ) num_null = max_length - length num_null_left = int ( math . ceil ( num_null / 2 ) ) num_middle_filled = middle_length - num_null middle_start = left_edge + num_null_left # Set left edge result [ sub_df . index , : left_edge ] = fixed_length_sequences [ : , : left_edge ] # Set middle. result [ sub_df . index , middle_start : middle_start + num_middle_filled ] = fixed_length_sequences [ : , left_edge : left_edge + num_middle_filled ] # Set right edge. result [ sub_df . index , - right_edge : ] = fixed_length_sequences [ : , - right_edge : ] return result | Transform a sequence of strings where each string is of length at least left_edge + right_edge and at most max_length into strings of length max_length using a scheme designed to preserve the anchor positions of class I peptides . | 607 | 48 |
248,734 | def robust_mean ( log_values ) : if log_values . shape [ 1 ] <= 3 : # Too few values to use robust mean. return numpy . nanmean ( log_values , axis = 1 ) without_nans = numpy . nan_to_num ( log_values ) # replace nan with 0 mask = ( ( ~ numpy . isnan ( log_values ) ) & ( without_nans <= numpy . nanpercentile ( log_values , 75 , axis = 1 ) . reshape ( ( - 1 , 1 ) ) ) & ( without_nans >= numpy . nanpercentile ( log_values , 25 , axis = 1 ) . reshape ( ( - 1 , 1 ) ) ) ) return ( without_nans * mask . astype ( float ) ) . sum ( 1 ) / mask . sum ( 1 ) | Mean of values falling within the 25 - 75 percentiles . | 185 | 13 |
248,735 | def neural_networks ( self ) : result = [ ] for models in self . allele_to_allele_specific_models . values ( ) : result . extend ( models ) result . extend ( self . class1_pan_allele_models ) return result | List of the neural networks in the ensemble . | 57 | 9 |
248,736 | def merge ( cls , predictors ) : assert len ( predictors ) > 0 if len ( predictors ) == 1 : return predictors [ 0 ] allele_to_allele_specific_models = collections . defaultdict ( list ) class1_pan_allele_models = [ ] allele_to_fixed_length_sequence = predictors [ 0 ] . allele_to_fixed_length_sequence for predictor in predictors : for ( allele , networks ) in ( predictor . allele_to_allele_specific_models . items ( ) ) : allele_to_allele_specific_models [ allele ] . extend ( networks ) class1_pan_allele_models . extend ( predictor . class1_pan_allele_models ) return Class1AffinityPredictor ( allele_to_allele_specific_models = allele_to_allele_specific_models , class1_pan_allele_models = class1_pan_allele_models , allele_to_fixed_length_sequence = allele_to_fixed_length_sequence ) | Merge the ensembles of two or more Class1AffinityPredictor instances . | 233 | 19 |
248,737 | def merge_in_place ( self , others ) : new_model_names = [ ] for predictor in others : for model in predictor . class1_pan_allele_models : model_name = self . model_name ( "pan-class1" , len ( self . class1_pan_allele_models ) ) self . class1_pan_allele_models . append ( model ) row = pandas . Series ( collections . OrderedDict ( [ ( "model_name" , model_name ) , ( "allele" , "pan-class1" ) , ( "config_json" , json . dumps ( model . get_config ( ) ) ) , ( "model" , model ) , ] ) ) . to_frame ( ) . T self . _manifest_df = pandas . concat ( [ self . manifest_df , row ] , ignore_index = True ) new_model_names . append ( model_name ) for allele in predictor . allele_to_allele_specific_models : if allele not in self . allele_to_allele_specific_models : self . allele_to_allele_specific_models [ allele ] = [ ] current_models = self . allele_to_allele_specific_models [ allele ] for model in predictor . allele_to_allele_specific_models [ allele ] : model_name = self . model_name ( allele , len ( current_models ) ) row = pandas . Series ( collections . OrderedDict ( [ ( "model_name" , model_name ) , ( "allele" , allele ) , ( "config_json" , json . dumps ( model . get_config ( ) ) ) , ( "model" , model ) , ] ) ) . to_frame ( ) . T self . _manifest_df = pandas . concat ( [ self . manifest_df , row ] , ignore_index = True ) current_models . append ( model ) new_model_names . append ( model_name ) self . clear_cache ( ) return new_model_names | Add the models present other predictors into the current predictor . | 458 | 12 |
248,738 | def percentile_ranks ( self , affinities , allele = None , alleles = None , throw = True ) : if allele is not None : try : transform = self . allele_to_percent_rank_transform [ allele ] return transform . transform ( affinities ) except KeyError : msg = "Allele %s has no percentile rank information" % allele if throw : raise ValueError ( msg ) else : warnings . warn ( msg ) # Return NaNs return numpy . ones ( len ( affinities ) ) * numpy . nan if alleles is None : raise ValueError ( "Specify allele or alleles" ) df = pandas . DataFrame ( { "affinity" : affinities } ) df [ "allele" ] = alleles df [ "result" ] = numpy . nan for ( allele , sub_df ) in df . groupby ( "allele" ) : df . loc [ sub_df . index , "result" ] = self . percentile_ranks ( sub_df . affinity , allele = allele , throw = throw ) return df . result . values | Return percentile ranks for the given ic50 affinities and alleles . | 239 | 15 |
248,739 | def calibrate_percentile_ranks ( self , peptides = None , num_peptides_per_length = int ( 1e5 ) , alleles = None , bins = None ) : if bins is None : bins = to_ic50 ( numpy . linspace ( 1 , 0 , 1000 ) ) if alleles is None : alleles = self . supported_alleles if peptides is None : peptides = [ ] lengths = range ( self . supported_peptide_lengths [ 0 ] , self . supported_peptide_lengths [ 1 ] + 1 ) for length in lengths : peptides . extend ( random_peptides ( num_peptides_per_length , length ) ) encoded_peptides = EncodableSequences . create ( peptides ) for ( i , allele ) in enumerate ( alleles ) : predictions = self . predict ( encoded_peptides , allele = allele ) transform = PercentRankTransform ( ) transform . fit ( predictions , bins = bins ) self . allele_to_percent_rank_transform [ allele ] = transform return encoded_peptides | Compute the cumulative distribution of ic50 values for a set of alleles over a large universe of random peptides to enable computing quantiles in this distribution later . | 245 | 33 |
248,740 | def filter_networks ( self , predicate ) : allele_to_allele_specific_models = { } for ( allele , models ) in self . allele_to_allele_specific_models . items ( ) : allele_to_allele_specific_models [ allele ] = [ m for m in models if predicate ( m ) ] class1_pan_allele_models = [ m for m in self . class1_pan_allele_models if predicate ( m ) ] return Class1AffinityPredictor ( allele_to_allele_specific_models = allele_to_allele_specific_models , class1_pan_allele_models = class1_pan_allele_models , allele_to_fixed_length_sequence = self . allele_to_fixed_length_sequence , ) | Return a new Class1AffinityPredictor containing a subset of this predictor s neural networks . | 180 | 20 |
248,741 | def model_select ( self , score_function , alleles = None , min_models = 1 , max_models = 10000 ) : if alleles is None : alleles = self . supported_alleles dfs = [ ] allele_to_allele_specific_models = { } for allele in alleles : df = pandas . DataFrame ( { 'model' : self . allele_to_allele_specific_models [ allele ] } ) df [ "model_num" ] = df . index df [ "allele" ] = allele df [ "selected" ] = False round_num = 1 while not df . selected . all ( ) and sum ( df . selected ) < max_models : score_col = "score_%2d" % round_num prev_score_col = "score_%2d" % ( round_num - 1 ) existing_selected = list ( df [ df . selected ] . model ) df [ score_col ] = [ numpy . nan if row . selected else score_function ( Class1AffinityPredictor ( allele_to_allele_specific_models = { allele : [ row . model ] + existing_selected } ) ) for ( _ , row ) in df . iterrows ( ) ] if round_num > min_models and ( df [ score_col ] . max ( ) < df [ prev_score_col ] . max ( ) ) : break # In case of a tie, pick a model at random. ( best_model_index , ) = df . loc [ ( df [ score_col ] == df [ score_col ] . max ( ) ) ] . sample ( 1 ) . index df . loc [ best_model_index , "selected" ] = True round_num += 1 dfs . append ( df ) allele_to_allele_specific_models [ allele ] = list ( df . loc [ df . selected ] . model ) df = pandas . concat ( dfs , ignore_index = True ) new_predictor = Class1AffinityPredictor ( allele_to_allele_specific_models , metadata_dataframes = { "model_selection" : df , } ) return new_predictor | Perform model selection using a user - specified scoring function . | 481 | 12 |
248,742 | def to_series ( self ) : return pandas . Series ( self . cdf , index = [ numpy . nan ] + list ( self . bin_edges ) + [ numpy . nan ] ) | Serialize the fit to a pandas . Series . | 45 | 11 |
248,743 | def get_default_class1_models_dir ( test_exists = True ) : if _MHCFLURRY_DEFAULT_CLASS1_MODELS_DIR : result = join ( get_downloads_dir ( ) , _MHCFLURRY_DEFAULT_CLASS1_MODELS_DIR ) if test_exists and not exists ( result ) : raise IOError ( "No such directory: %s" % result ) return result else : return get_path ( "models_class1" , "models" , test_exists = test_exists ) | Return the absolute path to the default class1 models dir . | 127 | 12 |
248,744 | def get_current_release_downloads ( ) : downloads = ( get_downloads_metadata ( ) [ 'releases' ] [ get_current_release ( ) ] [ 'downloads' ] ) return OrderedDict ( ( download [ "name" ] , { 'downloaded' : exists ( join ( get_downloads_dir ( ) , download [ "name" ] ) ) , 'metadata' : download , } ) for download in downloads ) | Return a dict of all available downloads in the current release . | 100 | 12 |
248,745 | def get_path ( download_name , filename = '' , test_exists = True ) : assert '/' not in download_name , "Invalid download: %s" % download_name path = join ( get_downloads_dir ( ) , download_name , filename ) if test_exists and not exists ( path ) : raise RuntimeError ( "Missing MHCflurry downloadable file: %s. " "To download this data, run:\n\tmhcflurry-downloads fetch %s\n" "in a shell." % ( quote ( path ) , download_name ) ) return path | Get the local path to a file in a MHCflurry download | 132 | 14 |
248,746 | def configure ( ) : global _DOWNLOADS_DIR global _CURRENT_RELEASE _CURRENT_RELEASE = None _DOWNLOADS_DIR = environ . get ( "MHCFLURRY_DOWNLOADS_DIR" ) if not _DOWNLOADS_DIR : metadata = get_downloads_metadata ( ) _CURRENT_RELEASE = environ . get ( "MHCFLURRY_DOWNLOADS_CURRENT_RELEASE" ) if not _CURRENT_RELEASE : _CURRENT_RELEASE = metadata [ 'current-release' ] current_release_compatability = ( metadata [ "releases" ] [ _CURRENT_RELEASE ] [ "compatibility-version" ] ) current_compatability = metadata [ "current-compatibility-version" ] if current_release_compatability != current_compatability : logging . warn ( "The specified downloads are not compatible with this version " "of the MHCflurry codebase. Downloads: release %s, " "compatability version: %d. Code compatability version: %d" % ( _CURRENT_RELEASE , current_release_compatability , current_compatability ) ) data_dir = environ . get ( "MHCFLURRY_DATA_DIR" ) if not data_dir : # increase the version every time we make a breaking change in # how the data is organized. For changes to e.g. just model # serialization, the downloads release numbers should be used. data_dir = user_data_dir ( "mhcflurry" , version = "4" ) _DOWNLOADS_DIR = join ( data_dir , _CURRENT_RELEASE ) logging . debug ( "Configured MHCFLURRY_DOWNLOADS_DIR: %s" % _DOWNLOADS_DIR ) | Setup various global variables based on environment variables . | 405 | 9 |
248,747 | def make_worker_pool ( processes = None , initializer = None , initializer_kwargs_per_process = None , max_tasks_per_worker = None ) : if not processes : processes = cpu_count ( ) pool_kwargs = { 'processes' : processes , } if max_tasks_per_worker : pool_kwargs [ "maxtasksperchild" ] = max_tasks_per_worker if initializer : if initializer_kwargs_per_process : assert len ( initializer_kwargs_per_process ) == processes kwargs_queue = Queue ( ) kwargs_queue_backup = Queue ( ) for kwargs in initializer_kwargs_per_process : kwargs_queue . put ( kwargs ) kwargs_queue_backup . put ( kwargs ) pool_kwargs [ "initializer" ] = worker_init_entry_point pool_kwargs [ "initargs" ] = ( initializer , kwargs_queue , kwargs_queue_backup ) else : pool_kwargs [ "initializer" ] = initializer worker_pool = Pool ( * * pool_kwargs ) print ( "Started pool: %s" % str ( worker_pool ) ) pprint ( pool_kwargs ) return worker_pool | Convenience wrapper to create a multiprocessing . Pool . | 298 | 14 |
248,748 | def calibrate_percentile_ranks ( allele , predictor , peptides = None ) : global GLOBAL_DATA if peptides is None : peptides = GLOBAL_DATA [ "calibration_peptides" ] predictor . calibrate_percentile_ranks ( peptides = peptides , alleles = [ allele ] ) return { allele : predictor . allele_to_percent_rank_transform [ allele ] , } | Private helper function . | 95 | 4 |
248,749 | def set_keras_backend ( backend = None , gpu_device_nums = None , num_threads = None ) : os . environ [ "KERAS_BACKEND" ] = "tensorflow" original_backend = backend if not backend : backend = "tensorflow-default" if gpu_device_nums is not None : os . environ [ "CUDA_VISIBLE_DEVICES" ] = "," . join ( [ str ( i ) for i in gpu_device_nums ] ) if backend == "tensorflow-cpu" or gpu_device_nums == [ ] : print ( "Forcing tensorflow/CPU backend." ) os . environ [ "CUDA_VISIBLE_DEVICES" ] = "" device_count = { 'CPU' : 1 , 'GPU' : 0 } elif backend == "tensorflow-gpu" : print ( "Forcing tensorflow/GPU backend." ) device_count = { 'CPU' : 0 , 'GPU' : 1 } elif backend == "tensorflow-default" : print ( "Forcing tensorflow backend." ) device_count = None else : raise ValueError ( "Unsupported backend: %s" % backend ) import tensorflow from keras import backend as K if K . backend ( ) == 'tensorflow' : config = tensorflow . ConfigProto ( device_count = device_count ) config . gpu_options . allow_growth = True if num_threads : config . inter_op_parallelism_threads = num_threads config . intra_op_parallelism_threads = num_threads session = tensorflow . Session ( config = config ) K . set_session ( session ) else : if original_backend or gpu_device_nums or num_threads : warnings . warn ( "Only tensorflow backend can be customized. Ignoring " " customization. Backend: %s" % K . backend ( ) ) | Configure Keras backend to use GPU or CPU . Only tensorflow is supported . | 445 | 18 |
248,750 | def uproot ( tree ) : uprooted = tree . copy ( ) uprooted . parent = None for child in tree . all_children ( ) : uprooted . add_general_child ( child ) return uprooted | Take a subranch of a tree and deep - copy the children of this subbranch into a new LabeledTree | 46 | 24 |
248,751 | def copy ( self ) : return LabeledTree ( udepth = self . udepth , depth = self . depth , text = self . text , label = self . label , children = self . children . copy ( ) if self . children != None else [ ] , parent = self . parent ) | Deep Copy of a LabeledTree | 62 | 7 |
248,752 | def add_child ( self , child ) : self . children . append ( child ) child . parent = self self . udepth = max ( [ child . udepth for child in self . children ] ) + 1 | Adds a branch to the current tree . | 45 | 8 |
248,753 | def lowercase ( self ) : if len ( self . children ) > 0 : for child in self . children : child . lowercase ( ) else : self . text = self . text . lower ( ) | Lowercase all strings in this tree . Works recursively and in - place . | 43 | 17 |
248,754 | def inject_visualization_javascript ( tree_width = 1200 , tree_height = 400 , tree_node_radius = 10 ) : from . javascript import insert_sentiment_markup insert_sentiment_markup ( tree_width = tree_width , tree_height = tree_height , tree_node_radius = tree_node_radius ) | In an Ipython notebook show SST trees using the same Javascript code as used by Jason Chuang s visualisations . | 76 | 24 |
248,755 | def create_tree_from_string ( line ) : depth = 0 current_word = "" root = None current_node = root for char in line : if char == '(' : if current_node is not None and len ( current_word ) > 0 : attribute_text_label ( current_node , current_word ) current_word = "" depth += 1 if depth > 1 : # replace current head node by this node: child = LabeledTree ( depth = depth ) current_node . add_child ( child ) current_node = child root . add_general_child ( child ) else : root = LabeledTree ( depth = depth ) root . add_general_child ( root ) current_node = root elif char == ')' : # assign current word: if len ( current_word ) > 0 : attribute_text_label ( current_node , current_word ) current_word = "" # go up a level: depth -= 1 if current_node . parent != None : current_node . parent . udepth = max ( current_node . udepth + 1 , current_node . parent . udepth ) current_node = current_node . parent else : # add to current read word current_word += char if depth != 0 : raise ParseError ( "Not an equal amount of closing and opening parentheses" ) return root | Parse and convert a string representation of an example into a LabeledTree datastructure . | 288 | 19 |
248,756 | def import_tree_corpus ( path ) : tree_list = LabeledTreeCorpus ( ) with codecs . open ( path , "r" , "UTF-8" ) as f : for line in f : tree_list . append ( create_tree_from_string ( line ) ) return tree_list | Import a text file of treebank trees . | 70 | 9 |
248,757 | def load_sst ( path = None , url = 'http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip' ) : if path is None : # find a good temporary path path = os . path . expanduser ( "~/stanford_sentiment_treebank/" ) makedirs ( path , exist_ok = True ) fnames = download_sst ( path , url ) return { key : import_tree_corpus ( value ) for key , value in fnames . items ( ) } | Download and read in the Stanford Sentiment Treebank dataset into a dictionary with a train dev and test keys . The dictionary keys point to lists of LabeledTrees . | 122 | 34 |
248,758 | def labels ( self ) : labelings = OrderedDict ( ) for tree in self : for label , line in tree . to_labeled_lines ( ) : labelings [ line ] = label return labelings | Construct a dictionary of string - > labels | 46 | 8 |
248,759 | def to_file ( self , path , mode = "w" ) : with open ( path , mode = mode ) as f : for tree in self : for label , line in tree . to_labeled_lines ( ) : f . write ( line + "\n" ) | Save the corpus to a text file in the original format . | 59 | 12 |
248,760 | def import_tree_corpus ( labels_path , parents_path , texts_path ) : with codecs . open ( labels_path , "r" , "UTF-8" ) as f : label_lines = f . readlines ( ) with codecs . open ( parents_path , "r" , "UTF-8" ) as f : parent_lines = f . readlines ( ) with codecs . open ( texts_path , "r" , "UTF-8" ) as f : word_lines = f . readlines ( ) assert len ( label_lines ) == len ( parent_lines ) assert len ( label_lines ) == len ( word_lines ) trees = [ ] for labels , parents , words in zip ( label_lines , parent_lines , word_lines ) : labels = [ int ( l ) + 2 for l in labels . strip ( ) . split ( " " ) ] parents = [ int ( l ) for l in parents . strip ( ) . split ( " " ) ] words = words . strip ( ) . split ( " " ) assert len ( labels ) == len ( parents ) trees . append ( read_tree ( parents , labels , words ) ) return trees | Import dataset from the TreeLSTM data generation scrips . | 261 | 14 |
248,761 | def assign_texts ( node , words , next_idx = 0 ) : if len ( node . children ) == 0 : node . text = words [ next_idx ] return next_idx + 1 else : for child in node . children : next_idx = assign_texts ( child , words , next_idx ) return next_idx | Recursively assign the words to nodes by finding and assigning strings to the leaves of a tree in left to right order . | 79 | 25 |
248,762 | def read_tree ( parents , labels , words ) : trees = { } root = None for i in range ( 1 , len ( parents ) + 1 ) : if not i in trees and parents [ i - 1 ] != - 1 : idx = i prev = None while True : parent = parents [ idx - 1 ] if parent == - 1 : break tree = LabeledTree ( ) if prev is not None : tree . add_child ( prev ) trees [ idx ] = tree tree . label = labels [ idx - 1 ] if trees . get ( parent ) is not None : trees [ parent ] . add_child ( tree ) break elif parent == 0 : root = tree break else : prev = tree idx = parent assert assign_texts ( root , words ) == len ( words ) return root | Take as input a list of integers for parents and labels along with a list of words and reconstruct a LabeledTree . | 174 | 24 |
248,763 | def set_initial_status ( self , configuration = None ) : super ( CognitiveOpDynModel , self ) . set_initial_status ( configuration ) # set node status for node in self . status : self . status [ node ] = np . random . random_sample ( ) self . initial_status = self . status . copy ( ) # set new node parameters self . params [ 'nodes' ] [ 'cognitive' ] = { } # first correct the input model parameters and retreive T_range, B_range and R_distribution T_range = ( self . params [ 'model' ] [ 'T_range_min' ] , self . params [ 'model' ] [ 'T_range_max' ] ) if self . params [ 'model' ] [ 'T_range_min' ] > self . params [ 'model' ] [ 'T_range_max' ] : T_range = ( self . params [ 'model' ] [ 'T_range_max' ] , self . params [ 'model' ] [ 'T_range_min' ] ) B_range = ( self . params [ 'model' ] [ 'B_range_min' ] , self . params [ 'model' ] [ 'B_range_max' ] ) if self . params [ 'model' ] [ 'B_range_min' ] > self . params [ 'model' ] [ 'B_range_max' ] : B_range = ( self . params [ 'model' ] [ 'B_range_max' ] , self . params [ 'model' ] [ 'B_range_min' ] ) s = float ( self . params [ 'model' ] [ 'R_fraction_negative' ] + self . params [ 'model' ] [ 'R_fraction_neutral' ] + self . params [ 'model' ] [ 'R_fraction_positive' ] ) R_distribution = ( self . params [ 'model' ] [ 'R_fraction_negative' ] / s , self . params [ 'model' ] [ 'R_fraction_neutral' ] / s , self . params [ 'model' ] [ 'R_fraction_positive' ] / s ) # then sample parameters from the ranges and distribution for node in self . graph . nodes ( ) : R_prob = np . random . random_sample ( ) if R_prob < R_distribution [ 0 ] : R = - 1 elif R_prob < ( R_distribution [ 0 ] + R_distribution [ 1 ] ) : R = 0 else : R = 1 # R, B and T parameters in a tuple self . params [ 'nodes' ] [ 'cognitive' ] [ node ] = ( R , B_range [ 0 ] + ( B_range [ 1 ] - B_range [ 0 ] ) * np . random . random_sample ( ) , T_range [ 0 ] + ( T_range [ 1 ] - T_range [ 0 ] ) * np . random . random_sample ( ) ) | Override behaviour of methods in class DiffusionModel . Overwrites initial status using random real values . Generates random node profiles . | 670 | 26 |
248,764 | def add_node_configuration ( self , param_name , node_id , param_value ) : if param_name not in self . config [ 'nodes' ] : self . config [ 'nodes' ] [ param_name ] = { node_id : param_value } else : self . config [ 'nodes' ] [ param_name ] [ node_id ] = param_value | Set a parameter for a given node | 88 | 7 |
248,765 | def add_node_set_configuration ( self , param_name , node_to_value ) : for nid , val in future . utils . iteritems ( node_to_value ) : self . add_node_configuration ( param_name , nid , val ) | Set Nodes parameter | 62 | 4 |
248,766 | def add_edge_configuration ( self , param_name , edge , param_value ) : if param_name not in self . config [ 'edges' ] : self . config [ 'edges' ] [ param_name ] = { edge : param_value } else : self . config [ 'edges' ] [ param_name ] [ edge ] = param_value | Set a parameter for a given edge | 82 | 7 |
248,767 | def add_edge_set_configuration ( self , param_name , edge_to_value ) : for edge , val in future . utils . iteritems ( edge_to_value ) : self . add_edge_configuration ( param_name , edge , val ) | Set Edges parameter | 60 | 4 |
248,768 | def multi_runs ( model , execution_number = 1 , iteration_number = 50 , infection_sets = None , nprocesses = multiprocessing . cpu_count ( ) ) : if nprocesses > multiprocessing . cpu_count ( ) : nprocesses = multiprocessing . cpu_count ( ) executions = [ ] if infection_sets is not None : if len ( infection_sets ) != execution_number : raise InitializationException ( { "message" : "Number of infection sets provided does not match the number of executions required" } ) for x in past . builtins . xrange ( 0 , execution_number , nprocesses ) : with closing ( multiprocessing . Pool ( processes = nprocesses , maxtasksperchild = 10 ) ) as pool : tasks = [ copy . copy ( model ) . reset ( infection_sets [ i ] ) for i in past . builtins . xrange ( x , min ( x + nprocesses , execution_number ) ) ] results = [ pool . apply_async ( __execute , ( t , iteration_number ) ) for t in tasks ] for result in results : executions . append ( result . get ( ) ) else : for x in past . builtins . xrange ( 0 , execution_number , nprocesses ) : with closing ( multiprocessing . Pool ( processes = nprocesses , maxtasksperchild = 10 ) ) as pool : tasks = [ copy . deepcopy ( model ) . reset ( ) for _ in past . builtins . xrange ( x , min ( x + nprocesses , execution_number ) ) ] results = [ pool . apply_async ( __execute , ( t , iteration_number ) ) for t in tasks ] for result in results : executions . append ( result . get ( ) ) return executions | Multiple executions of a given model varying the initial set of infected nodes | 395 | 13 |
248,769 | def __execute ( model , iteration_number ) : iterations = model . iteration_bunch ( iteration_number , False ) trends = model . build_trends ( iterations ) [ 0 ] del iterations del model return trends | Execute a simulation model | 47 | 5 |
248,770 | def set_initial_status ( self , configuration = None ) : super ( AlgorithmicBiasModel , self ) . set_initial_status ( configuration ) # set node status for node in self . status : self . status [ node ] = np . random . random_sample ( ) self . initial_status = self . status . copy ( ) | Override behaviour of methods in class DiffusionModel . Overwrites initial status using random real values . | 74 | 20 |
248,771 | def names ( self ) : if self . name == self . UNKNOWN_HUMAN_PLAYER : return "" , "" if not self . is_ai and " " in self . name : return "" , self . name return self . name , "" | Returns the player s name and real name . Returns two empty strings if the player is unknown . AI real name is always an empty string . | 54 | 28 |
248,772 | def _getgroup ( string , depth ) : out , comma = [ ] , False while string : items , string = _getitem ( string , depth ) if not string : break out += items if string [ 0 ] == '}' : if comma : return out , string [ 1 : ] return [ '{' + a + '}' for a in out ] , string [ 1 : ] if string [ 0 ] == ',' : comma , string = True , string [ 1 : ] return None | Get a group from the string where group is a list of all the comma separated substrings up to the next } char or the brace enclosed substring if there is no comma | 106 | 35 |
248,773 | def filter_noexpand_columns ( columns ) : prefix_len = len ( NOEXPAND_PREFIX ) noexpand = [ c [ prefix_len : ] for c in columns if c . startswith ( NOEXPAND_PREFIX ) ] other = [ c for c in columns if not c . startswith ( NOEXPAND_PREFIX ) ] return other , noexpand | Return columns not containing and containing the noexpand prefix . | 90 | 12 |
248,774 | def to_root ( df , path , key = 'my_ttree' , mode = 'w' , store_index = True , * args , * * kwargs ) : if mode == 'a' : mode = 'update' elif mode == 'w' : mode = 'recreate' else : raise ValueError ( 'Unknown mode: {}. Must be "a" or "w".' . format ( mode ) ) from root_numpy import array2tree # We don't want to modify the user's DataFrame here, so we make a shallow copy df_ = df . copy ( deep = False ) if store_index : name = df_ . index . name if name is None : # Handle the case where the index has no name name = '' df_ [ '__index__' + name ] = df_ . index # Convert categorical columns into something root_numpy can serialise for col in df_ . select_dtypes ( [ 'category' ] ) . columns : name_components = [ '__rpCaT' , col , str ( df_ [ col ] . cat . ordered ) ] name_components . extend ( df_ [ col ] . cat . categories ) if [ '*' not in c for c in name_components ] : sep = '*' else : raise ValueError ( 'Unable to find suitable separator for columns' ) df_ [ col ] = df_ [ col ] . cat . codes df_ . rename ( index = str , columns = { col : sep . join ( name_components ) } , inplace = True ) arr = df_ . to_records ( index = False ) root_file = ROOT . TFile . Open ( path , mode ) if not root_file : raise IOError ( "cannot open file {0}" . format ( path ) ) if not root_file . IsWritable ( ) : raise IOError ( "file {0} is not writable" . format ( path ) ) # Navigate to the requested directory open_dirs = [ root_file ] for dir_name in key . split ( '/' ) [ : - 1 ] : current_dir = open_dirs [ - 1 ] . Get ( dir_name ) if not current_dir : current_dir = open_dirs [ - 1 ] . mkdir ( dir_name ) current_dir . cd ( ) open_dirs . append ( current_dir ) # The key is now just the top component key = key . split ( '/' ) [ - 1 ] # If a tree with that name exists, we want to update it tree = open_dirs [ - 1 ] . Get ( key ) if not tree : tree = None tree = array2tree ( arr , name = key , tree = tree ) tree . Write ( key , ROOT . TFile . kOverwrite ) root_file . Close ( ) | Write DataFrame to a ROOT file . | 627 | 9 |
248,775 | def run ( self , symbol : str ) -> SecurityDetailsViewModel : from pydatum import Datum svc = self . _svc sec_agg = svc . securities . get_aggregate_for_symbol ( symbol ) model = SecurityDetailsViewModel ( ) model . symbol = sec_agg . security . namespace + ":" + sec_agg . security . mnemonic model . security = sec_agg . security # Quantity model . quantity = sec_agg . get_quantity ( ) model . value = sec_agg . get_value ( ) currency = sec_agg . get_currency ( ) if currency : assert isinstance ( currency , str ) model . currency = currency model . price = sec_agg . get_last_available_price ( ) model . average_price = sec_agg . get_avg_price ( ) # Here we take only the amount paid for the remaining stock. model . total_paid = sec_agg . get_total_paid_for_remaining_stock ( ) # Profit/loss model . profit_loss = model . value - model . total_paid if model . total_paid : model . profit_loss_perc = abs ( model . profit_loss ) * 100 / model . total_paid else : model . profit_loss_perc = 0 if abs ( model . value ) < abs ( model . total_paid ) : model . profit_loss_perc *= - 1 # Income model . income = sec_agg . get_income_total ( ) if model . total_paid : model . income_perc = model . income * 100 / model . total_paid else : model . income_perc = 0 # income in the last 12 months start = Datum ( ) start . subtract_months ( 12 ) end = Datum ( ) model . income_last_12m = sec_agg . get_income_in_period ( start , end ) if model . total_paid == 0 : model . income_perc_last_12m = 0 else : model . income_perc_last_12m = model . income_last_12m * 100 / model . total_paid # Return of Capital roc = sec_agg . get_return_of_capital ( ) model . return_of_capital = roc # total return model . total_return = model . profit_loss + model . income if model . total_paid : model . total_return_perc = model . total_return * 100 / model . total_paid else : model . total_return_perc = 0 # load all holding accounts model . accounts = sec_agg . accounts # Income accounts model . income_accounts = sec_agg . get_income_accounts ( ) # Load asset classes to which this security belongs. # todo load asset allocation, find the parents for this symbol # svc.asset_allocation.load_config_only(svc.currencies.default_currency) # stocks = svc.asset_allocation.get_stock(model.symbol) # # for stock in stocks: # model.asset_classes.append(stock.asset_class) from asset_allocation import AppAggregate aa = AppAggregate ( ) aa . open_session ( ) aa . get_asset_classes_for_security ( None , model . symbol ) return model | Loads the model for security details | 734 | 7 |
248,776 | def handle_friday ( next_date : Datum , period : str , mult : int , start_date : Datum ) : assert isinstance ( next_date , Datum ) assert isinstance ( start_date , Datum ) # Starting from line 220. tmp_sat = next_date . clone ( ) tmp_sat . add_days ( 1 ) tmp_sun = next_date . clone ( ) tmp_sun . add_days ( 2 ) if period == RecurrencePeriod . END_OF_MONTH . value : if ( next_date . is_end_of_month ( ) or tmp_sat . is_end_of_month ( ) or tmp_sun . is_end_of_month ( ) ) : next_date . add_months ( 1 ) else : next_date . add_months ( mult - 1 ) else : if tmp_sat . get_day_name ( ) == start_date . get_day_name ( ) : next_date . add_days ( 1 ) next_date . add_months ( mult ) elif tmp_sun . get_day_name ( ) == start_date . get_day_name ( ) : next_date . add_days ( 2 ) next_date . add_months ( mult ) elif next_date . get_day ( ) >= start_date . get_day ( ) : next_date . add_months ( mult ) elif next_date . is_end_of_month ( ) : next_date . add_months ( mult ) elif tmp_sat . is_end_of_month ( ) : next_date . add_days ( 1 ) next_date . add_months ( mult ) elif tmp_sun . is_end_of_month ( ) : next_date . add_days ( 2 ) next_date . add_months ( mult ) else : # /* one fewer month fwd because of the occurrence in this month */ next_date . subtract_months ( 1 ) return next_date | Extracted the calculation for when the next_day is Friday | 439 | 12 |
248,777 | def get_next_occurrence ( self ) -> date : result = get_next_occurrence ( self . transaction ) assert isinstance ( result , date ) return result | Returns the next occurrence date for transaction | 36 | 7 |
248,778 | def get_enabled ( self ) -> List [ ScheduledTransaction ] : query = ( self . query . filter ( ScheduledTransaction . enabled == True ) ) return query . all ( ) | Returns only enabled scheduled transactions | 39 | 5 |
248,779 | def get_by_id ( self , tx_id : str ) -> ScheduledTransaction : return self . query . filter ( ScheduledTransaction . guid == tx_id ) . first ( ) | Fetches a tx by id | 41 | 7 |
248,780 | def get_aggregate_by_id ( self , tx_id : str ) -> ScheduledTxAggregate : tran = self . get_by_id ( tx_id ) return self . get_aggregate_for ( tran ) | Creates an aggregate for single entity | 53 | 7 |
248,781 | def get_avg_price_stat ( self ) -> Decimal : avg_price = Decimal ( 0 ) price_total = Decimal ( 0 ) price_count = 0 for account in self . security . accounts : # Ignore trading accounts. if account . type == AccountType . TRADING . name : continue for split in account . splits : # Don't count the non-transactions. if split . quantity == 0 : continue price = split . value / split . quantity price_count += 1 price_total += price if price_count : avg_price = price_total / price_count return avg_price | Calculates the statistical average price for the security by averaging only the prices paid . Very simple first implementation . | 132 | 22 |
248,782 | def get_avg_price_fifo ( self ) -> Decimal : balance = self . get_quantity ( ) if not balance : return Decimal ( 0 ) paid = Decimal ( 0 ) accounts = self . get_holding_accounts ( ) # get unused splits (quantity and total paid) per account. for account in accounts : splits = self . get_available_splits_for_account ( account ) for split in splits : paid += split . value avg_price = paid / balance return avg_price | Calculates the average price paid for the security . security = Commodity Returns Decimal value . | 113 | 21 |
248,783 | def get_available_splits_for_account ( self , account : Account ) -> List [ Split ] : available_splits = [ ] # get all purchase splits in the account query = ( self . get_splits_query ( ) . filter ( Split . account == account ) ) buy_splits = ( query . filter ( Split . quantity > 0 ) . join ( Transaction ) . order_by ( desc ( Transaction . post_date ) ) ) . all ( ) buy_q = sum ( split . quantity for split in buy_splits ) sell_splits = query . filter ( Split . quantity < 0 ) . all ( ) sell_q = sum ( split . quantity for split in sell_splits ) balance = buy_q + sell_q if balance == 0 : return available_splits for real_split in buy_splits : split = splitmapper . map_split ( real_split , SplitModel ( ) ) if split . quantity < balance : # take this split and reduce the balance. balance -= split . quantity else : # This is the last split. price = split . value / split . quantity # Take only the remaining quantity. split . quantity -= balance # Also adjust the value for easier calculation elsewhere. split . value = balance * price # The remaining balance is now distributed into splits. balance = 0 # add to the collection. available_splits . append ( split ) if balance == 0 : break return available_splits | Returns all unused splits in the account . Used for the calculation of avg . price . The split that has been partially used will have its quantity reduced to available quantity only . | 310 | 34 |
248,784 | def get_num_shares ( self ) -> Decimal : from pydatum import Datum today = Datum ( ) . today ( ) return self . get_num_shares_on ( today ) | Returns the number of shares at this time | 45 | 8 |
248,785 | def get_last_available_price ( self ) -> PriceModel : price_db = PriceDbApplication ( ) symbol = SecuritySymbol ( self . security . namespace , self . security . mnemonic ) result = price_db . get_latest_price ( symbol ) return result | Finds the last available price for security . Uses PriceDb . | 60 | 13 |
248,786 | def __get_holding_accounts_query ( self ) : query = ( self . book . session . query ( Account ) . filter ( Account . commodity == self . security ) . filter ( Account . type != AccountType . trading . value ) ) # generic.print_sql(query) return query | Returns all holding accounts except Trading accounts . | 64 | 8 |
248,787 | def get_income_accounts ( self ) -> List [ Account ] : # trading = self.book.trading_account(self.security) # log(DEBUG, "trading account = %s, %s", trading.fullname, trading.guid) # Example on how to self-link, i.e. parent account, using alias. # parent_alias = aliased(Account) # .join(parent_alias, Account.parent) # parent_alias.parent_guid != trading.guid query = ( self . book . session . query ( Account ) . join ( Commodity ) . filter ( Account . name == self . security . mnemonic ) . filter ( Commodity . namespace == "CURRENCY" ) # .filter(Account.type != "TRADING") . filter ( Account . type == AccountType . income . value ) ) # generic.print_sql(query) return query . all ( ) | Returns all income accounts for this security . Income accounts are accounts not under Trading expressed in currency and having the same name as the mnemonic . They should be under Assets but this requires a recursive SQL query . | 206 | 42 |
248,788 | def get_income_total ( self ) -> Decimal : accounts = self . get_income_accounts ( ) # log(DEBUG, "income accounts: %s", accounts) income = Decimal ( 0 ) for acct in accounts : income += acct . get_balance ( ) return income | Sum of all income = sum of balances of all income accounts . | 64 | 13 |
248,789 | def get_income_in_period ( self , start : datetime , end : datetime ) -> Decimal : accounts = self . get_income_accounts ( ) income = Decimal ( 0 ) for acct in accounts : acc_agg = AccountAggregate ( self . book , acct ) acc_bal = acc_agg . get_balance_in_period ( start , end ) income += acc_bal return income | Returns all income in the given period | 92 | 7 |
248,790 | def get_prices ( self ) -> List [ PriceModel ] : # return self.security.prices.order_by(Price.date) from pricedb . dal import Price pricedb = PriceDbApplication ( ) repo = pricedb . get_price_repository ( ) query = ( repo . query ( Price ) . filter ( Price . namespace == self . security . namespace ) . filter ( Price . symbol == self . security . mnemonic ) . orderby_desc ( Price . date ) ) return query . all ( ) | Returns all available prices for security | 116 | 6 |
248,791 | def get_quantity ( self ) -> Decimal : from pydatum import Datum # Use today's date but reset hour and lower. today = Datum ( ) today . today ( ) today . end_of_day ( ) return self . get_num_shares_on ( today . value ) | Returns the number of shares for the given security . It gets the number from all the accounts in the book . | 66 | 22 |
248,792 | def get_splits_query ( self ) : query = ( self . book . session . query ( Split ) . join ( Account ) . filter ( Account . type != AccountType . trading . value ) . filter ( Account . commodity_guid == self . security . guid ) ) return query | Returns the query for all splits for this security | 62 | 9 |
248,793 | def get_total_paid ( self ) -> Decimal : query = ( self . get_splits_query ( ) ) splits = query . all ( ) total = Decimal ( 0 ) for split in splits : total += split . value return total | Returns the total amount paid in currency for the stocks owned | 53 | 11 |
248,794 | def get_total_paid_for_remaining_stock ( self ) -> Decimal : paid = Decimal ( 0 ) accounts = self . get_holding_accounts ( ) for acc in accounts : splits = self . get_available_splits_for_account ( acc ) paid += sum ( split . value for split in splits ) return paid | Returns the amount paid only for the remaining stock | 75 | 9 |
248,795 | def get_value ( self ) -> Decimal : quantity = self . get_quantity ( ) price = self . get_last_available_price ( ) if not price : # raise ValueError("no price found for", self.full_symbol) return Decimal ( 0 ) value = quantity * price . value return value | Returns the current value of stocks | 70 | 6 |
248,796 | def get_value_in_base_currency ( self ) -> Decimal : # check if the currency is the base currency. amt_orig = self . get_value ( ) # Security currency sec_cur = self . get_currency ( ) #base_cur = self.book.default_currency cur_svc = CurrenciesAggregate ( self . book ) base_cur = cur_svc . get_default_currency ( ) if sec_cur == base_cur : return amt_orig # otherwise recalculate single_svc = cur_svc . get_currency_aggregate ( sec_cur ) rate = single_svc . get_latest_rate ( base_cur ) result = amt_orig * rate . value return result | Calculates the value of security holdings in base currency | 164 | 11 |
248,797 | def accounts ( self ) -> List [ Account ] : # use only Assets sub-accounts result = ( [ acct for acct in self . security . accounts if acct . fullname . startswith ( 'Assets' ) ] ) return result | Returns the asset accounts in which the security is held | 54 | 10 |
248,798 | def find ( self , search_term : str ) -> List [ Commodity ] : query = ( self . query . filter ( Commodity . mnemonic . like ( '%' + search_term + '%' ) | Commodity . fullname . like ( '%' + search_term + '%' ) ) ) return query . all ( ) | Searches for security by part of the name | 80 | 10 |
248,799 | def get_all ( self ) -> List [ Commodity ] : query = ( self . query . order_by ( Commodity . namespace , Commodity . mnemonic ) ) return query . all ( ) | Loads all non - currency commodities assuming they are stocks . | 47 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.