idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
234,900 | def _filterize ( name , value ) : if name . endswith ( '_min' ) : name = name [ : - 4 ] comp = '>=' elif name . endswith ( '_max' ) : name = name [ : - 4 ] comp = '<' else : comp = '==' result = '{} {} {!r}' . format ( name , comp , value ) logger . debug ( 'converted name={} and value={} to filter {}' . format ( name , value , result ) ) return result | Turn a name and value into a string expression compatible the DataFrame . query method . | 120 | 17 |
234,901 | def str_model_expression ( expr , add_constant = True ) : if not isinstance ( expr , str ) : if isinstance ( expr , collections . Mapping ) : left_side = expr . get ( 'left_side' ) right_side = str_model_expression ( expr [ 'right_side' ] , add_constant ) else : # some kind of iterable like a list left_side = None right_side = ' + ' . join ( expr ) if left_side : model_expression = ' ~ ' . join ( ( left_side , right_side ) ) else : model_expression = right_side else : model_expression = expr if not has_constant_expr ( model_expression ) : if add_constant : model_expression += ' + 1' else : model_expression += ' - 1' logger . debug ( 'converted expression: {!r} to model: {!r}' . format ( expr , model_expression ) ) return model_expression | We support specifying model expressions as strings lists or dicts ; but for use with patsy and statsmodels we need a string . This function will take any of those as input and return a string . | 219 | 41 |
234,902 | def sorted_groupby ( df , groupby ) : start = 0 prev = df [ groupby ] . iloc [ start ] for i , x in enumerate ( df [ groupby ] ) : if x != prev : yield prev , df . iloc [ start : i ] prev = x start = i # need to send back the last group yield prev , df . iloc [ start : ] | Perform a groupby on a DataFrame using a specific column and assuming that that column is sorted . | 85 | 21 |
234,903 | def columns_in_filters ( filters ) : if not filters : return [ ] if not isinstance ( filters , str ) : filters = ' ' . join ( filters ) columns = [ ] reserved = { 'and' , 'or' , 'in' , 'not' } for toknum , tokval , _ , _ , _ in generate_tokens ( StringIO ( filters ) . readline ) : if toknum == NAME and tokval not in reserved : columns . append ( tokval ) return list ( tz . unique ( columns ) ) | Returns a list of the columns used in a set of query filters . | 124 | 14 |
234,904 | def _tokens_from_patsy ( node ) : for n in node . args : for t in _tokens_from_patsy ( n ) : yield t if node . token : yield node . token | Yields all the individual tokens from within a patsy formula as parsed by patsy . parse_formula . parse_formula . | 50 | 31 |
234,905 | def columns_in_formula ( formula ) : if formula is None : return [ ] formula = str_model_expression ( formula , add_constant = False ) columns = [ ] tokens = map ( lambda x : x . extra , tz . remove ( lambda x : x . extra is None , _tokens_from_patsy ( patsy . parse_formula . parse_formula ( formula ) ) ) ) for tok in tokens : # if there are parentheses in the expression we # want to drop them and everything outside # and start again from the top if '(' in tok : start = tok . find ( '(' ) + 1 fin = tok . rfind ( ')' ) columns . extend ( columns_in_formula ( tok [ start : fin ] ) ) else : for toknum , tokval , _ , _ , _ in generate_tokens ( StringIO ( tok ) . readline ) : if toknum == NAME : columns . append ( tokval ) return list ( tz . unique ( columns ) ) | Returns the names of all the columns used in a patsy formula . | 235 | 15 |
234,906 | def fit_model ( df , filters , model_expression ) : df = util . apply_filter_query ( df , filters ) model = smf . ols ( formula = model_expression , data = df ) if len ( model . exog ) != len ( df ) : raise ModelEvaluationError ( 'Estimated data does not have the same length as input. ' 'This suggests there are null values in one or more of ' 'the input columns.' ) with log_start_finish ( 'statsmodels OLS fit' , logger ) : return model . fit ( ) | Use statsmodels OLS to construct a model relation . | 125 | 11 |
234,907 | def predict ( df , filters , model_fit , ytransform = None ) : df = util . apply_filter_query ( df , filters ) with log_start_finish ( 'statsmodels predict' , logger ) : sim_data = model_fit . predict ( df ) if len ( sim_data ) != len ( df ) : raise ModelEvaluationError ( 'Predicted data does not have the same length as input. ' 'This suggests there are null values in one or more of ' 'the input columns.' ) if ytransform : sim_data = ytransform ( sim_data ) return pd . Series ( sim_data , index = df . index ) | Apply model to new data to predict new dependent values . | 144 | 11 |
234,908 | def _model_fit_to_table ( fit ) : fit_parameters = pd . DataFrame ( { 'Coefficient' : fit . params , 'Std. Error' : fit . bse , 'T-Score' : fit . tvalues } ) fit_parameters . rsquared = fit . rsquared fit_parameters . rsquared_adj = fit . rsquared_adj return fit_parameters | Produce a pandas DataFrame of model fit results from a statsmodels fit result object . | 96 | 19 |
234,909 | def predict ( self , data ) : with log_start_finish ( '_FakeRegressionResults prediction' , logger ) : model_design = dmatrix ( self . _rhs , data = data , return_type = 'dataframe' ) return model_design . dot ( self . params ) . values | Predict new values by running data through the fit model . | 68 | 12 |
234,910 | def from_yaml ( cls , yaml_str = None , str_or_buffer = None ) : cfg = yamlio . yaml_to_dict ( yaml_str , str_or_buffer ) model = cls ( cfg [ 'fit_filters' ] , cfg [ 'predict_filters' ] , cfg [ 'model_expression' ] , YTRANSFORM_MAPPING [ cfg [ 'ytransform' ] ] , cfg [ 'name' ] ) if 'fitted' in cfg and cfg [ 'fitted' ] : fit_parameters = pd . DataFrame ( cfg [ 'fit_parameters' ] ) fit_parameters . rsquared = cfg [ 'fit_rsquared' ] fit_parameters . rsquared_adj = cfg [ 'fit_rsquared_adj' ] model . model_fit = _FakeRegressionResults ( model . str_model_expression , fit_parameters , cfg [ 'fit_rsquared' ] , cfg [ 'fit_rsquared_adj' ] ) model . fit_parameters = fit_parameters logger . debug ( 'loaded regression model {} from YAML' . format ( model . name ) ) return model | Create a RegressionModel instance from a saved YAML configuration . Arguments are mutually exclusive . | 283 | 20 |
234,911 | def predict ( self , data ) : self . assert_fitted ( ) with log_start_finish ( 'predicting model {}' . format ( self . name ) , logger ) : return predict ( data , self . predict_filters , self . model_fit , self . ytransform ) | Predict a new data set based on an estimated model . | 64 | 12 |
234,912 | def to_dict ( self ) : d = { 'model_type' : 'regression' , 'name' : self . name , 'fit_filters' : self . fit_filters , 'predict_filters' : self . predict_filters , 'model_expression' : self . model_expression , 'ytransform' : YTRANSFORM_MAPPING [ self . ytransform ] , 'fitted' : self . fitted , 'fit_parameters' : None , 'fit_rsquared' : None , 'fit_rsquared_adj' : None } if self . fitted : d [ 'fit_parameters' ] = yamlio . frame_to_yaml_safe ( self . fit_parameters ) d [ 'fit_rsquared' ] = float ( self . model_fit . rsquared ) d [ 'fit_rsquared_adj' ] = float ( self . model_fit . rsquared_adj ) return d | Returns a dictionary representation of a RegressionModel instance . | 217 | 11 |
234,913 | def columns_used ( self ) : return list ( tz . unique ( tz . concatv ( util . columns_in_filters ( self . fit_filters ) , util . columns_in_filters ( self . predict_filters ) , util . columns_in_formula ( self . model_expression ) ) ) ) | Returns all the columns used in this model for filtering and in the model expression . | 75 | 16 |
234,914 | def add_model ( self , model ) : logger . debug ( 'adding model {} to group {}' . format ( model . name , self . name ) ) self . models [ model . name ] = model | Add a RegressionModel instance . | 44 | 7 |
234,915 | def add_model_from_params ( self , name , fit_filters , predict_filters , model_expression , ytransform = None ) : logger . debug ( 'adding model {} to group {}' . format ( name , self . name ) ) model = RegressionModel ( fit_filters , predict_filters , model_expression , ytransform , name ) self . models [ name ] = model | Add a model by passing arguments through to RegressionModel . | 88 | 12 |
234,916 | def fit ( self , data , debug = False ) : with log_start_finish ( 'fitting models in group {}' . format ( self . name ) , logger ) : return { name : self . models [ name ] . fit ( df , debug = debug ) for name , df in self . _iter_groups ( data ) } | Fit each of the models in the group . | 72 | 9 |
234,917 | def from_yaml ( cls , yaml_str = None , str_or_buffer = None ) : cfg = yamlio . yaml_to_dict ( yaml_str , str_or_buffer ) default_model_expr = cfg [ 'default_config' ] [ 'model_expression' ] default_ytransform = cfg [ 'default_config' ] [ 'ytransform' ] seg = cls ( cfg [ 'segmentation_col' ] , cfg [ 'fit_filters' ] , cfg [ 'predict_filters' ] , default_model_expr , YTRANSFORM_MAPPING [ default_ytransform ] , cfg [ 'min_segment_size' ] , cfg [ 'name' ] ) if "models" not in cfg : cfg [ "models" ] = { } for name , m in cfg [ 'models' ] . items ( ) : m [ 'model_expression' ] = m . get ( 'model_expression' , default_model_expr ) m [ 'ytransform' ] = m . get ( 'ytransform' , default_ytransform ) m [ 'fit_filters' ] = None m [ 'predict_filters' ] = None reg = RegressionModel . from_yaml ( yamlio . convert_to_yaml ( m , None ) ) seg . _group . add_model ( reg ) logger . debug ( 'loaded segmented regression model {} from yaml' . format ( seg . name ) ) return seg | Create a SegmentedRegressionModel instance from a saved YAML configuration . Arguments are mutally exclusive . | 347 | 24 |
234,918 | def add_segment ( self , name , model_expression = None , ytransform = 'default' ) : if not model_expression : if self . default_model_expr is None : raise ValueError ( 'No default model available, ' 'you must supply a model experssion.' ) model_expression = self . default_model_expr if ytransform == 'default' : ytransform = self . default_ytransform # no fit or predict filters, we'll take care of that this side. self . _group . add_model_from_params ( name , None , None , model_expression , ytransform ) logger . debug ( 'added segment {} to model {}' . format ( name , self . name ) ) | Add a new segment with its own model expression and ytransform . | 156 | 13 |
234,919 | def fit ( self , data , debug = False ) : data = util . apply_filter_query ( data , self . fit_filters ) unique = data [ self . segmentation_col ] . unique ( ) value_counts = data [ self . segmentation_col ] . value_counts ( ) # Remove any existing segments that may no longer have counterparts # in the data. This can happen when loading a saved model and then # calling this method with data that no longer has segments that # were there the last time this was called. gone = set ( self . _group . models ) - set ( unique ) for g in gone : del self . _group . models [ g ] for x in unique : if x not in self . _group . models and value_counts [ x ] > self . min_segment_size : self . add_segment ( x ) with log_start_finish ( 'fitting models in segmented model {}' . format ( self . name ) , logger ) : return self . _group . fit ( data , debug = debug ) | Fit each segment . Segments that have not already been explicitly added will be automatically added with default model and ytransform . | 230 | 24 |
234,920 | def columns_used ( self ) : return list ( tz . unique ( tz . concatv ( util . columns_in_filters ( self . fit_filters ) , util . columns_in_filters ( self . predict_filters ) , util . columns_in_formula ( self . default_model_expr ) , self . _group . columns_used ( ) , [ self . segmentation_col ] ) ) ) | Returns all the columns used across all models in the group for filtering and in the model expression . | 97 | 19 |
234,921 | def find_movers ( choosers , rates , rate_column ) : logger . debug ( 'start: find movers for relocation' ) relocation_rates = pd . Series ( np . zeros ( len ( choosers ) ) , index = choosers . index ) for _ , row in rates . iterrows ( ) : indexes = util . filter_table ( choosers , row , ignore = { rate_column } ) . index relocation_rates . loc [ indexes ] = row [ rate_column ] movers = relocation_rates . index [ relocation_rates > np . random . random ( len ( choosers ) ) ] logger . debug ( 'picked {} movers for relocation' . format ( len ( movers ) ) ) logger . debug ( 'finish: find movers for relocation' ) return movers | Returns an array of the indexes of the choosers that are slated to move . | 179 | 17 |
234,922 | def _calculate_adjustment ( lcm , choosers , alternatives , alt_segmenter , clip_change_low , clip_change_high , multiplier_func = None ) : logger . debug ( 'start: calculate supply and demand price adjustment ratio' ) # probabilities of agents choosing * number of agents = demand demand = lcm . summed_probabilities ( choosers , alternatives ) # group by submarket demand = demand . groupby ( alt_segmenter . loc [ demand . index ] . values ) . sum ( ) # number of alternatives supply = alt_segmenter . value_counts ( ) if multiplier_func is not None : multiplier , finished = multiplier_func ( demand , supply ) else : multiplier , finished = ( demand / supply ) , False multiplier = multiplier . clip ( clip_change_low , clip_change_high ) # broadcast multiplier back to alternatives index alts_muliplier = multiplier . loc [ alt_segmenter ] alts_muliplier . index = alt_segmenter . index logger . debug ( ( 'finish: calculate supply and demand price adjustment multiplier ' 'with mean multiplier {}' ) . format ( multiplier . mean ( ) ) ) return alts_muliplier , multiplier , finished | Calculate adjustments to prices to compensate for supply and demand effects . | 275 | 14 |
234,923 | def supply_and_demand ( lcm , choosers , alternatives , alt_segmenter , price_col , base_multiplier = None , clip_change_low = 0.75 , clip_change_high = 1.25 , iterations = 5 , multiplier_func = None ) : logger . debug ( 'start: calculating supply and demand price adjustment' ) # copy alternatives so we don't modify the user's original alternatives = alternatives . copy ( ) # if alt_segmenter is a string, get the actual column for segmenting demand if isinstance ( alt_segmenter , str ) : alt_segmenter = alternatives [ alt_segmenter ] elif isinstance ( alt_segmenter , np . array ) : alt_segmenter = pd . Series ( alt_segmenter , index = alternatives . index ) choosers , alternatives = lcm . apply_predict_filters ( choosers , alternatives ) alt_segmenter = alt_segmenter . loc [ alternatives . index ] # check base ratio and apply it to prices if given if base_multiplier is not None : bm = base_multiplier . loc [ alt_segmenter ] bm . index = alt_segmenter . index alternatives [ price_col ] = alternatives [ price_col ] * bm base_multiplier = base_multiplier . copy ( ) for _ in range ( iterations ) : alts_muliplier , submarkets_multiplier , finished = _calculate_adjustment ( lcm , choosers , alternatives , alt_segmenter , clip_change_low , clip_change_high , multiplier_func = multiplier_func ) alternatives [ price_col ] = alternatives [ price_col ] * alts_muliplier # might need to initialize this for holding cumulative multiplier if base_multiplier is None : base_multiplier = pd . Series ( np . ones ( len ( submarkets_multiplier ) ) , index = submarkets_multiplier . index ) base_multiplier *= submarkets_multiplier if finished : break logger . debug ( 'finish: calculating supply and demand price adjustment' ) return alternatives [ price_col ] , base_multiplier | Adjust real estate prices to compensate for supply and demand effects . | 484 | 12 |
234,924 | def _max_form ( f , colname ) : df = f . stack ( level = 0 ) [ [ colname ] ] . stack ( ) . unstack ( level = 1 ) . reset_index ( level = 1 , drop = True ) return df . idxmax ( axis = 1 ) | Assumes dataframe with hierarchical columns with first index equal to the use and second index equal to the attribute . | 64 | 22 |
234,925 | def keep_form_with_max_profit ( self , forms = None ) : f = self . feasibility if forms is not None : f = f [ forms ] if len ( f ) > 0 : mu = self . _max_form ( f , "max_profit" ) indexes = [ tuple ( x ) for x in mu . reset_index ( ) . values ] else : indexes = [ ] df = f . stack ( level = 0 ) . loc [ indexes ] df . index . names = [ "parcel_id" , "form" ] df = df . reset_index ( level = 1 ) return df | This converts the dataframe which shows all profitable forms to the form with the greatest profit so that more profitable forms outcompete less profitable forms . | 133 | 29 |
234,926 | def compute_units_to_build ( num_agents , num_units , target_vacancy ) : print ( "Number of agents: {:,}" . format ( num_agents ) ) print ( "Number of agent spaces: {:,}" . format ( int ( num_units ) ) ) assert target_vacancy < 1.0 target_units = int ( max ( num_agents / ( 1 - target_vacancy ) - num_units , 0 ) ) print ( "Current vacancy = {:.2f}" . format ( 1 - num_agents / float ( num_units ) ) ) print ( "Target vacancy = {:.2f}, target of new units = {:,}" . format ( target_vacancy , target_units ) ) return target_units | Compute number of units to build to match target vacancy . | 168 | 12 |
234,927 | def pick ( self , form , target_units , parcel_size , ave_unit_size , current_units , max_parcel_size = 200000 , min_unit_size = 400 , drop_after_build = True , residential = True , bldg_sqft_per_job = 400.0 , profit_to_prob_func = None ) : if len ( self . feasibility ) == 0 : # no feasible buildings, might as well bail return if form is None : df = self . feasibility elif isinstance ( form , list ) : df = self . keep_form_with_max_profit ( form ) else : df = self . feasibility [ form ] # feasible buildings only for this building type df = df [ df . max_profit_far > 0 ] ave_unit_size [ ave_unit_size < min_unit_size ] = min_unit_size df [ "ave_unit_size" ] = ave_unit_size df [ "parcel_size" ] = parcel_size df [ 'current_units' ] = current_units df = df [ df . parcel_size < max_parcel_size ] df [ 'residential_units' ] = ( df . residential_sqft / df . ave_unit_size ) . round ( ) df [ 'job_spaces' ] = ( df . non_residential_sqft / bldg_sqft_per_job ) . round ( ) if residential : df [ 'net_units' ] = df . residential_units - df . current_units else : df [ 'net_units' ] = df . job_spaces - df . current_units df = df [ df . net_units > 0 ] if len ( df ) == 0 : print ( "WARNING THERE ARE NO FEASIBLE BUILDING TO CHOOSE FROM" ) return # print "Describe of net units\n", df.net_units.describe() print ( "Sum of net units that are profitable: {:,}" . format ( int ( df . net_units . sum ( ) ) ) ) if profit_to_prob_func : p = profit_to_prob_func ( df ) else : df [ 'max_profit_per_size' ] = df . max_profit / df . parcel_size p = df . max_profit_per_size . values / df . max_profit_per_size . sum ( ) if df . net_units . sum ( ) < target_units : print ( "WARNING THERE WERE NOT ENOUGH PROFITABLE UNITS TO" , "MATCH DEMAND" ) build_idx = df . index . values elif target_units <= 0 : build_idx = [ ] else : # we don't know how many developments we will need, as they differ in net_units. # If all developments have net_units of 1 than we need target_units of them. # So we choose the smaller of available developments and target_units. choices = np . random . choice ( df . index . values , size = min ( len ( df . index ) , target_units ) , replace = False , p = p ) tot_units = df . net_units . loc [ choices ] . values . cumsum ( ) ind = int ( np . searchsorted ( tot_units , target_units , side = "left" ) ) + 1 build_idx = choices [ : ind ] if drop_after_build : self . feasibility = self . feasibility . drop ( build_idx ) new_df = df . loc [ build_idx ] new_df . index . name = "parcel_id" return new_df . reset_index ( ) | Choose the buildings from the list that are feasible to build in order to match the specified demand . | 813 | 19 |
234,928 | def _analyze_root_causes ( self ) : causes = { } for a in self . anomalies : try : causes [ a ] = self . correlations [ a ] [ 0 ] except IndexError : raise exceptions . InvalidDataFormat ( 'luminol.luminol: dict correlations contains empty list.' ) self . causes = causes | Conduct root cause analysis . The first metric of the list is taken as the root cause right now . | 72 | 21 |
234,929 | def _sanity_check ( self ) : if len ( self . time_series_a ) < 2 or len ( self . time_series_b ) < 2 : raise exceptions . NotEnoughDataPoints ( 'luminol.Correlator: Too few data points!' ) | Check if the time series have more than two data points . | 60 | 12 |
234,930 | def _correlate ( self ) : a = self . algorithm ( * * self . algorithm_params ) self . correlation_result = a . run ( ) | Run correlation algorithm . | 34 | 4 |
234,931 | def _analyze ( self ) : output = defaultdict ( list ) output_by_name = defaultdict ( list ) scores = self . anomaly_detector . get_all_scores ( ) if self . anomalies : for anomaly in self . anomalies : metrix_scores = scores start_t , end_t = anomaly . get_time_window ( ) t = anomaly . exact_timestamp # Compute extended start timestamp and extended end timestamp. room = ( end_t - start_t ) / 2 if not room : room = 30 extended_start_t = start_t - room extended_end_t = end_t + room metrix_scores_cropped = metrix_scores . crop ( extended_start_t , extended_end_t ) # Adjust the two timestamps if not enough data points are included. while len ( metrix_scores_cropped ) < 2 : extended_start_t = extended_start_t - room extended_end_t = extended_end_t + room metrix_scores_cropped = metrix_scores . crop ( extended_start_t , extended_end_t ) # Correlate with other metrics for entry in self . related_metrices : try : entry_correlation_result = Correlator ( self . metrix , entry , time_period = ( extended_start_t , extended_end_t ) , use_anomaly_score = True ) . get_correlation_result ( ) record = extended_start_t , extended_end_t , entry_correlation_result . __dict__ , entry record_by_name = extended_start_t , extended_end_t , entry_correlation_result . __dict__ output [ t ] . append ( record ) output_by_name [ entry ] . append ( record_by_name ) except exceptions . NotEnoughDataPoints : pass self . output = output self . output_by_name = output_by_name | Analyzes if a matrix has anomalies . If any anomaly is found determine if the matrix correlates with any other matrixes . To be implemented . | 434 | 28 |
234,932 | def _set_scores ( self ) : anom_scores_ema = self . exp_avg_detector . run ( ) anom_scores_deri = self . derivative_detector . run ( ) anom_scores = { } for timestamp in anom_scores_ema . timestamps : # Compute a weighted anomaly score. anom_scores [ timestamp ] = max ( anom_scores_ema [ timestamp ] , anom_scores_ema [ timestamp ] * DEFAULT_DETECTOR_EMA_WEIGHT + anom_scores_deri [ timestamp ] * ( 1 - DEFAULT_DETECTOR_EMA_WEIGHT ) ) # If ema score is significant enough, take the bigger one of the weighted score and deri score. if anom_scores_ema [ timestamp ] > DEFAULT_DETECTOR_EMA_SIGNIFICANT : anom_scores [ timestamp ] = max ( anom_scores [ timestamp ] , anom_scores_deri [ timestamp ] ) self . anom_scores = TimeSeries ( self . _denoise_scores ( anom_scores ) ) | Set anomaly scores using a weighted sum . | 263 | 8 |
234,933 | def _compute_derivatives ( self ) : derivatives = [ ] for i , ( timestamp , value ) in enumerate ( self . time_series_items ) : if i > 0 : pre_item = self . time_series_items [ i - 1 ] pre_timestamp = pre_item [ 0 ] pre_value = pre_item [ 1 ] td = timestamp - pre_timestamp derivative = ( value - pre_value ) / td if td != 0 else value - pre_value derivative = abs ( derivative ) derivatives . append ( derivative ) # First timestamp is assigned the same derivative as the second timestamp. if derivatives : derivatives . insert ( 0 , derivatives [ 0 ] ) self . derivatives = derivatives | Compute derivatives of the time series . | 152 | 8 |
234,934 | def _sanity_check ( self ) : windows = self . lag_window_size + self . future_window_size if ( not self . lag_window_size or not self . future_window_size or self . time_series_length < windows or windows < DEFAULT_BITMAP_MINIMAL_POINTS_IN_WINDOWS ) : raise exceptions . NotEnoughDataPoints # If window size is too big, too many data points will be assigned a score of 0 in the first lag window # and the last future window. if self . lag_window_size > DEFAULT_BITMAP_MAXIMAL_POINTS_IN_WINDOWS : self . lag_window_size = DEFAULT_BITMAP_MAXIMAL_POINTS_IN_WINDOWS if self . future_window_size > DEFAULT_BITMAP_MAXIMAL_POINTS_IN_WINDOWS : self . future_window_size = DEFAULT_BITMAP_MAXIMAL_POINTS_IN_WINDOWS | Check if there are enough data points . | 220 | 8 |
234,935 | def _generate_SAX ( self ) : sections = { } self . value_min = self . time_series . min ( ) self . value_max = self . time_series . max ( ) # Break the whole value range into different sections. section_height = ( self . value_max - self . value_min ) / self . precision for section_number in range ( self . precision ) : sections [ section_number ] = self . value_min + section_number * section_height # Generate SAX representation. self . sax = '' . join ( self . _generate_SAX_single ( sections , value ) for value in self . time_series . values ) | Generate SAX representation for all values of the time series . | 149 | 13 |
234,936 | def _set_scores ( self ) : anom_scores = { } self . _generate_SAX ( ) self . _construct_all_SAX_chunk_dict ( ) length = self . time_series_length lws = self . lag_window_size fws = self . future_window_size for i , timestamp in enumerate ( self . time_series . timestamps ) : if i < lws or i > length - fws : anom_scores [ timestamp ] = 0 else : anom_scores [ timestamp ] = self . _compute_anom_score_between_two_windows ( i ) self . anom_scores = TimeSeries ( self . _denoise_scores ( anom_scores ) ) | Compute anomaly scores for the time series by sliding both lagging window and future window . | 172 | 18 |
234,937 | def _detect_correlation ( self ) : correlations = [ ] shifted_correlations = [ ] self . time_series_a . normalize ( ) self . time_series_b . normalize ( ) a , b = self . time_series_a . align ( self . time_series_b ) a_values , b_values = a . values , b . values a_avg , b_avg = a . average ( ) , b . average ( ) a_stdev , b_stdev = a . stdev ( ) , b . stdev ( ) n = len ( a ) denom = a_stdev * b_stdev * n # Find the maximal shift steps according to the maximal shift seconds. allowed_shift_step = self . _find_allowed_shift ( a . timestamps ) if allowed_shift_step : shift_upper_bound = allowed_shift_step shift_lower_bound = - allowed_shift_step else : shift_upper_bound = 1 shift_lower_bound = 0 for delay in range ( shift_lower_bound , shift_upper_bound ) : delay_in_seconds = a . timestamps [ abs ( delay ) ] - a . timestamps [ 0 ] if delay < 0 : delay_in_seconds = - delay_in_seconds s = 0 for i in range ( n ) : j = i + delay if j < 0 or j >= n : continue else : s += ( ( a_values [ i ] - a_avg ) * ( b_values [ j ] - b_avg ) ) r = s / denom if denom != 0 else s correlations . append ( [ delay_in_seconds , r ] ) # Take shift into account to create a "shifted correlation coefficient". if self . max_shift_milliseconds : shifted_correlations . append ( r * ( 1 + float ( delay_in_seconds ) / self . max_shift_milliseconds * self . shift_impact ) ) else : shifted_correlations . append ( r ) max_correlation = list ( max ( correlations , key = lambda k : k [ 1 ] ) ) max_shifted_correlation = max ( shifted_correlations ) max_correlation . append ( max_shifted_correlation ) self . correlation_result = CorrelationResult ( * max_correlation ) | Detect correlation by computing correlation coefficients for all allowed shift steps then take the maximum . | 516 | 16 |
234,938 | def _compute_anom_data_using_window ( self ) : anom_scores = { } values = self . time_series . values stdev = numpy . std ( values ) for i , ( timestamp , value ) in enumerate ( self . time_series_items ) : if i < self . lag_window_size : anom_score = self . _compute_anom_score ( values [ : i + 1 ] , value ) else : anom_score = self . _compute_anom_score ( values [ i - self . lag_window_size : i + 1 ] , value ) if stdev : anom_scores [ timestamp ] = anom_score / stdev else : anom_scores [ timestamp ] = anom_score self . anom_scores = TimeSeries ( self . _denoise_scores ( anom_scores ) ) | Compute anomaly scores using a lagging window . | 201 | 10 |
234,939 | def _compute_anom_data_decay_all ( self ) : anom_scores = { } values = self . time_series . values ema = utils . compute_ema ( self . smoothing_factor , values ) stdev = numpy . std ( values ) for i , ( timestamp , value ) in enumerate ( self . time_series_items ) : anom_score = abs ( ( value - ema [ i ] ) / stdev ) if stdev else value - ema [ i ] anom_scores [ timestamp ] = anom_score self . anom_scores = TimeSeries ( self . _denoise_scores ( anom_scores ) ) | Compute anomaly scores using a lagging window covering all the data points before . | 156 | 16 |
234,940 | def _generic_binary_op ( self , other , op ) : output = { } if isinstance ( other , TimeSeries ) : for key , value in self . items ( ) : if key in other : try : result = op ( value , other [ key ] ) if result is NotImplemented : other_type = type ( other [ key ] ) other_op = vars ( other_type ) . get ( op . __name__ ) if other_op : output [ key ] = other_op ( other_type ( value ) , other [ key ] ) else : output [ key ] = result except ZeroDivisionError : continue else : for key , value in self . items ( ) : try : result = op ( value , other ) if result is NotImplemented : other_type = type ( other ) other_op = vars ( other_type ) . get ( op . __name__ ) if other_op : output [ key ] = other_op ( other_type ( value ) , other ) else : output [ key ] = result except ZeroDivisionError : continue if output : return TimeSeries ( output ) else : raise ValueError ( 'TimeSeries data was empty or invalid.' ) | Perform the method operation specified in the op parameter on the values within the instance s time series values and either another time series or a constant number value . | 260 | 31 |
234,941 | def _get_value_type ( self , other ) : if self . values : return type ( self . values [ 0 ] ) elif isinstance ( other , TimeSeries ) and other . values : return type ( other . values [ 0 ] ) else : raise ValueError ( 'Cannot perform arithmetic on empty time series.' ) | Get the object type of the value within the values portion of the time series . | 70 | 16 |
234,942 | def smooth ( self , smoothing_factor ) : forward_smooth = { } backward_smooth = { } output = { } if self : pre = self . values [ 0 ] next = self . values [ - 1 ] for key , value in self . items ( ) : forward_smooth [ key ] = smoothing_factor * pre + ( 1 - smoothing_factor ) * value pre = forward_smooth [ key ] for key , value in reversed ( self . items ( ) ) : backward_smooth [ key ] = smoothing_factor * next + ( 1 - smoothing_factor ) * value next = backward_smooth [ key ] for key in forward_smooth . keys ( ) : output [ key ] = ( forward_smooth [ key ] + backward_smooth [ key ] ) / 2 return TimeSeries ( output ) | return a new time series which is a exponential smoothed version of the original data series . soomth forward once backward once and then take the average . | 184 | 31 |
234,943 | def add_offset ( self , offset ) : self . timestamps = [ ts + offset for ts in self . timestamps ] | Return a new time series with all timestamps incremented by some offset . | 29 | 16 |
234,944 | def normalize ( self ) : maximum = self . max ( ) if maximum : self . values = [ value / maximum for value in self . values ] | Return a new time series with all values normalized to 0 to 1 . | 32 | 14 |
234,945 | def crop ( self , start_timestamp , end_timestamp ) : output = { } for key , value in self . items ( ) : if key >= start_timestamp and key <= end_timestamp : output [ key ] = value if output : return TimeSeries ( output ) else : raise ValueError ( 'TimeSeries data was empty or invalid.' ) | Return a new TimeSeries object contains all the timstamps and values within the specified range . | 77 | 19 |
234,946 | def average ( self , default = None ) : return numpy . asscalar ( numpy . average ( self . values ) ) if self . values else default | Calculate the average value over the time series . | 34 | 11 |
234,947 | def median ( self , default = None ) : return numpy . asscalar ( numpy . median ( self . values ) ) if self . values else default | Calculate the median value over the time series . | 34 | 11 |
234,948 | def max ( self , default = None ) : return numpy . asscalar ( numpy . max ( self . values ) ) if self . values else default | Calculate the maximum value over the time series . | 34 | 11 |
234,949 | def min ( self , default = None ) : return numpy . asscalar ( numpy . min ( self . values ) ) if self . values else default | Calculate the minimum value over the time series . | 34 | 11 |
234,950 | def percentile ( self , n , default = None ) : return numpy . asscalar ( numpy . percentile ( self . values , n ) ) if self . values else default | Calculate the Nth Percentile value over the time series . | 38 | 14 |
234,951 | def stdev ( self , default = None ) : return numpy . asscalar ( numpy . std ( self . values ) ) if self . values else default | Calculate the standard deviation of the time series . | 35 | 11 |
234,952 | def sum ( self , default = None ) : return numpy . asscalar ( numpy . sum ( self . values ) ) if self . values else default | Calculate the sum of all the values in the times series . | 34 | 14 |
234,953 | def _detect_anomalies ( self ) : anom_scores = self . anom_scores max_anom_score = anom_scores . max ( ) anomalies = [ ] if max_anom_score : threshold = self . threshold or max_anom_score * self . score_percent_threshold # Find all the anomaly intervals. intervals = [ ] start , end = None , None for timestamp , value in anom_scores . iteritems ( ) : if value > threshold : end = timestamp if not start : start = timestamp elif start and end is not None : intervals . append ( [ start , end ] ) start = None end = None if start is not None : intervals . append ( [ start , end ] ) # Locate the exact anomaly point within each anomaly interval. for interval_start , interval_end in intervals : interval_series = anom_scores . crop ( interval_start , interval_end ) self . refine_algorithm_params [ 'time_series' ] = interval_series refine_algorithm = self . refine_algorithm ( * * self . refine_algorithm_params ) scores = refine_algorithm . run ( ) max_refine_score = scores . max ( ) # Get the timestamp of the maximal score. max_refine_timestamp = scores . timestamps [ scores . values . index ( max_refine_score ) ] anomaly = Anomaly ( interval_start , interval_end , interval_series . max ( ) , max_refine_timestamp ) anomalies . append ( anomaly ) self . anomalies = anomalies | Detect anomalies using a threshold on anomaly scores . | 348 | 9 |
234,954 | def handle_response ( response ) : # ignore valid responses if response . status_code < 400 : return cls = _status_to_exception_type . get ( response . status_code , HttpError ) kwargs = { 'code' : response . status_code , 'method' : response . request . method , 'url' : response . request . url , 'details' : response . text , } if response . headers and 'retry-after' in response . headers : kwargs [ 'retry_after' ] = response . headers . get ( 'retry-after' ) raise cls ( * * kwargs ) | Given a requests . Response object throw the appropriate exception if applicable . | 142 | 13 |
234,955 | def create ( self , data , * * kwargs ) : self . client . post ( self . url , data = data ) | Create classifitions for specific entity | 28 | 7 |
234,956 | def create ( self , * * kwargs ) : raise exceptions . MethodNotImplemented ( method = self . create , url = self . url , details = 'GUID cannot be duplicated, to create a new GUID use the relationship resource' ) | Raise error since guid cannot be duplicated | 55 | 9 |
234,957 | def normalize_underscore_case ( name ) : normalized = name . lower ( ) normalized = re . sub ( r'_(\w)' , lambda match : ' ' + match . group ( 1 ) . upper ( ) , normalized ) return normalized [ 0 ] . upper ( ) + normalized [ 1 : ] | Normalize an underscore - separated descriptor to something more readable . | 66 | 12 |
234,958 | def normalize_camel_case ( name ) : normalized = re . sub ( '([a-z])([A-Z])' , lambda match : ' ' . join ( [ match . group ( 1 ) , match . group ( 2 ) ] ) , name ) return normalized [ 0 ] . upper ( ) + normalized [ 1 : ] | Normalize a camelCase descriptor to something more readable . | 74 | 11 |
234,959 | def version_tuple ( version ) : if isinstance ( version , str ) : return tuple ( int ( x ) for x in version . split ( '.' ) ) elif isinstance ( version , tuple ) : return version else : raise ValueError ( "Invalid version: %s" % version ) | Convert a version string or tuple to a tuple . | 64 | 11 |
234,960 | def version_str ( version ) : if isinstance ( version , str ) : return version elif isinstance ( version , tuple ) : return '.' . join ( [ str ( int ( x ) ) for x in version ] ) else : raise ValueError ( "Invalid version: %s" % version ) | Convert a version tuple or string to a string . | 65 | 11 |
234,961 | def generate_http_basic_token ( username , password ) : token = base64 . b64encode ( '{}:{}' . format ( username , password ) . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) return token | Generates a HTTP basic token from username and password | 58 | 10 |
234,962 | def identifier ( self ) : if self . primary_key not in self . _data : return 'Unknown' return str ( self . _data [ self . primary_key ] ) | These models have server - generated identifiers . | 38 | 8 |
234,963 | def url ( self ) : if self . parent is None : # TODO: differing API Versions? pieces = [ self . client . base_url , 'api' , 'atlas' , 'v2' ] else : pieces = [ self . parent . url ] pieces . append ( self . model_class . path ) return '/' . join ( pieces ) | The url for this collection . | 78 | 6 |
234,964 | def inflate ( self ) : if not self . _is_inflated : self . check_version ( ) for k , v in self . _filter . items ( ) : if '[' in v : self . _filter [ k ] = ast . literal_eval ( v ) self . load ( self . client . get ( self . url , params = self . _filter ) ) self . _is_inflated = True return self | Load the collection from the server if necessary . | 95 | 9 |
234,965 | def load ( self , response ) : self . _models = [ ] if isinstance ( response , dict ) : for key in response . keys ( ) : model = self . model_class ( self , href = '' ) model . load ( response [ key ] ) self . _models . append ( model ) else : for item in response : model = self . model_class ( self , href = item . get ( 'href' ) ) model . load ( item ) self . _models . append ( model ) | Parse the GET response for the collection . | 108 | 9 |
234,966 | def create ( self , * args , * * kwargs ) : href = self . url if len ( args ) == 1 : kwargs [ self . model_class . primary_key ] = args [ 0 ] href = '/' . join ( [ href , args [ 0 ] ] ) model = self . model_class ( self , href = href . replace ( 'classifications/' , 'classification/' ) , data = kwargs ) model . create ( * * kwargs ) self . _models . append ( model ) return model | Add a resource to this collection . | 119 | 7 |
234,967 | def update ( self , * * kwargs ) : self . inflate ( ) for model in self . _models : model . update ( * * kwargs ) return self | Update all resources in this collection . | 38 | 7 |
234,968 | def delete ( self , * * kwargs ) : self . inflate ( ) for model in self . _models : model . delete ( * * kwargs ) return | Delete all resources in this collection . | 37 | 7 |
234,969 | def wait ( self , * * kwargs ) : if self . request : self . request . wait ( * * kwargs ) self . request = None return self . inflate ( ) | Wait until any pending asynchronous requests are finished for this collection . | 41 | 12 |
234,970 | def url ( self ) : if self . _href is not None : return self . _href if self . identifier : # for some reason atlas does not use classifications here in the path when considering one classification path = '/' . join ( [ self . parent . url . replace ( 'classifications/' , 'classficiation/' ) , self . identifier ] ) return path raise exceptions . ClientError ( "Not able to determine object URL" ) | Gets the url for the resource this model represents . | 97 | 11 |
234,971 | def inflate ( self ) : if not self . _is_inflated : if self . _is_inflating : # catch infinite recursion when attempting to inflate # an object that doesn't have enough data to inflate msg = ( "There is not enough data to inflate this object. " "Need either an href: {} or a {}: {}" ) msg = msg . format ( self . _href , self . primary_key , self . _data . get ( self . primary_key ) ) raise exceptions . ClientError ( msg ) self . _is_inflating = True try : params = self . searchParameters if hasattr ( self , 'searchParameters' ) else { } # To keep the method same as the original request. The default is GET self . load ( self . client . request ( self . method , self . url , * * params ) ) except Exception : self . load ( self . _data ) self . _is_inflated = True self . _is_inflating = False return self | Load the resource from the server if not already loaded . | 223 | 11 |
234,972 | def load ( self , response ) : if 'href' in response : self . _href = response . pop ( 'href' ) if self . data_key and self . data_key in response : self . _data . update ( response . pop ( self . data_key ) ) # preload related object collections, if received for rel in [ x for x in self . relationships if x in response and response [ x ] ] : rel_class = self . relationships [ rel ] collection = rel_class . collection_class ( self . client , rel_class , parent = self ) self . _relationship_cache [ rel ] = collection ( response [ rel ] ) else : self . _data . update ( response ) | The load method parses the raw JSON response from the server . | 153 | 13 |
234,973 | def delete ( self , * * kwargs ) : self . method = 'delete' if len ( kwargs ) > 0 : self . load ( self . client . delete ( self . url , params = kwargs ) ) else : self . load ( self . client . delete ( self . url ) ) self . parent . remove ( self ) return | Delete a resource by issuing a DELETE http request against it . | 76 | 14 |
234,974 | def publish ( obj , event , event_state , * * kwargs ) : # short-circuit if nothing is listening if len ( EVENT_HANDLERS ) == 0 : return if inspect . isclass ( obj ) : pub_cls = obj else : pub_cls = obj . __class__ potential = [ x . __name__ for x in inspect . getmro ( pub_cls ) ] # if we don't find a match for this event/event_state we fire the events # for this event/ANY instead for the closest match fallbacks = None callbacks = [ ] for cls in potential : event_key = '.' . join ( [ cls , event , event_state ] ) backup_key = '.' . join ( [ cls , event , states . ANY ] ) if event_key in EVENT_HANDLERS : callbacks = EVENT_HANDLERS [ event_key ] break elif fallbacks is None and backup_key in EVENT_HANDLERS : fallbacks = EVENT_HANDLERS [ backup_key ] if fallbacks is not None : callbacks = fallbacks for callback in callbacks : callback ( obj , * * kwargs ) return | Publish an event from an object . | 264 | 8 |
234,975 | def subscribe ( obj , event , callback , event_state = None ) : if inspect . isclass ( obj ) : cls = obj . __name__ else : cls = obj . __class__ . __name__ if event_state is None : event_state = states . ANY event_key = '.' . join ( [ cls , event , event_state ] ) if event_key not in EVENT_HANDLERS : EVENT_HANDLERS [ event_key ] = [ ] EVENT_HANDLERS [ event_key ] . append ( callback ) return | Subscribe an event from an class . | 125 | 7 |
234,976 | def clean_name ( self , suffix = True , prefix = False , middle = False , multi = False ) : name = self . business_name # Run it through the string_stripper once more name = self . string_stripper ( name ) loname = name . lower ( ) # return name without suffixed/prefixed/middle type term(s) for item in suffix_sort : if suffix : if loname . endswith ( " " + item ) : start = loname . find ( item ) end = len ( item ) name = name [ 0 : - end - 1 ] name = self . string_stripper ( name ) if multi == False : break if prefix : if loname . startswith ( item + ' ' ) : name = name [ len ( item ) + 1 : ] if multi == False : break if middle : term = ' ' + item + ' ' if term in loname : start = loname . find ( term ) end = start + len ( term ) name = name [ : start ] + " " + name [ end : ] if multi == False : break return self . string_stripper ( name ) | return cleared version of the business name | 252 | 7 |
234,977 | def _add_nodes ( self ) : for n , atom in enumerate ( self . ast . select ( 'atom' ) ) : self . add_node ( n , atom = atom ) self . _atom_indices [ id ( atom ) ] = n | Add all atoms in the SMARTS string as nodes in the graph . | 57 | 15 |
234,978 | def _add_edges ( self , ast_node , trunk = None ) : atom_indices = self . _atom_indices for atom in ast_node . tail : if atom . head == 'atom' : atom_idx = atom_indices [ id ( atom ) ] if atom . is_first_kid and atom . parent ( ) . head == 'branch' : trunk_idx = atom_indices [ id ( trunk ) ] self . add_edge ( atom_idx , trunk_idx ) if not atom . is_last_kid : if atom . next_kid . head == 'atom' : next_idx = atom_indices [ id ( atom . next_kid ) ] self . add_edge ( atom_idx , next_idx ) elif atom . next_kid . head == 'branch' : trunk = atom else : # We traveled through the whole branch. return elif atom . head == 'branch' : self . _add_edges ( atom , trunk ) | Add all bonds in the SMARTS string as edges in the graph . | 226 | 15 |
234,979 | def _add_label_edges ( self ) : labels = self . ast . select ( 'atom_label' ) if not labels : return # We need each individual label and atoms with multiple ring labels # would yield e.g. the string '12' so split those up. label_digits = defaultdict ( list ) for label in labels : digits = list ( label . tail [ 0 ] ) for digit in digits : label_digits [ digit ] . append ( label . parent ( ) ) for label , ( atom1 , atom2 ) in label_digits . items ( ) : atom1_idx = self . _atom_indices [ id ( atom1 ) ] atom2_idx = self . _atom_indices [ id ( atom2 ) ] self . add_edge ( atom1_idx , atom2_idx ) | Add edges between all atoms with the same atom_label in rings . | 185 | 14 |
234,980 | def find_matches ( self , topology ) : # Note: Needs to be updated in sync with the grammar in `smarts.py`. ring_tokens = [ 'ring_size' , 'ring_count' ] has_ring_rules = any ( self . ast . select ( token ) for token in ring_tokens ) _prepare_atoms ( topology , compute_cycles = has_ring_rules ) top_graph = nx . Graph ( ) top_graph . add_nodes_from ( ( ( a . index , { 'atom' : a } ) for a in topology . atoms ( ) ) ) top_graph . add_edges_from ( ( ( b [ 0 ] . index , b [ 1 ] . index ) for b in topology . bonds ( ) ) ) if self . _graph_matcher is None : atom = nx . get_node_attributes ( self , name = 'atom' ) [ 0 ] if len ( atom . select ( 'atom_symbol' ) ) == 1 and not atom . select ( 'not_expression' ) : try : element = atom . select ( 'atom_symbol' ) . strees [ 0 ] . tail [ 0 ] except IndexError : try : atomic_num = atom . select ( 'atomic_num' ) . strees [ 0 ] . tail [ 0 ] element = pt . Element [ int ( atomic_num ) ] except IndexError : element = None else : element = None self . _graph_matcher = SMARTSMatcher ( top_graph , self , node_match = self . _node_match , element = element ) matched_atoms = set ( ) for mapping in self . _graph_matcher . subgraph_isomorphisms_iter ( ) : mapping = { node_id : atom_id for atom_id , node_id in mapping . items ( ) } # The first node in the smarts graph always corresponds to the atom # that we are trying to match. atom_index = mapping [ 0 ] # Don't yield duplicate matches found via matching the pattern in a # different order. if atom_index not in matched_atoms : matched_atoms . add ( atom_index ) yield atom_index | Return sets of atoms that match this SMARTS pattern in a topology . | 488 | 16 |
234,981 | def candidate_pairs_iter ( self ) : # All computations are done using the current state! G2_nodes = self . G2_nodes # First we compute the inout-terminal sets. T1_inout = set ( self . inout_1 . keys ( ) ) - set ( self . core_1 . keys ( ) ) T2_inout = set ( self . inout_2 . keys ( ) ) - set ( self . core_2 . keys ( ) ) # If T1_inout and T2_inout are both nonempty. # P(s) = T1_inout x {min T2_inout} if T1_inout and T2_inout : for node in T1_inout : yield node , min ( T2_inout ) else : # First we determine the candidate node for G2 other_node = min ( G2_nodes - set ( self . core_2 ) ) host_nodes = self . valid_nodes if other_node == 0 else self . G1 . nodes ( ) for node in host_nodes : if node not in self . core_1 : yield node , other_node | Iterator over candidate pairs of nodes in G1 and G2 . | 265 | 13 |
234,982 | def find_atomtypes ( topology , forcefield , max_iter = 10 ) : rules = _load_rules ( forcefield ) # Only consider rules for elements found in topology subrules = dict ( ) system_elements = { a . element . symbol for a in topology . atoms ( ) } for key , val in rules . items ( ) : atom = val . node [ 0 ] [ 'atom' ] if len ( atom . select ( 'atom_symbol' ) ) == 1 and not atom . select ( 'not_expression' ) : try : element = atom . select ( 'atom_symbol' ) . strees [ 0 ] . tail [ 0 ] except IndexError : try : atomic_num = atom . select ( 'atomic_num' ) . strees [ 0 ] . tail [ 0 ] element = pt . Element [ int ( atomic_num ) ] except IndexError : element = None else : element = None if element is None or element in system_elements : subrules [ key ] = val rules = subrules _iterate_rules ( rules , topology , max_iter = max_iter ) _resolve_atomtypes ( topology ) | Determine atomtypes for all atoms . | 254 | 9 |
234,983 | def _load_rules ( forcefield ) : rules = dict ( ) for rule_name , smarts in forcefield . atomTypeDefinitions . items ( ) : overrides = forcefield . atomTypeOverrides . get ( rule_name ) if overrides is not None : overrides = set ( overrides ) else : overrides = set ( ) rules [ rule_name ] = SMARTSGraph ( smarts_string = smarts , parser = forcefield . parser , name = rule_name , overrides = overrides ) return rules | Load atomtyping rules from a forcefield into SMARTSGraphs . | 117 | 16 |
234,984 | def _iterate_rules ( rules , topology , max_iter ) : atoms = list ( topology . atoms ( ) ) for _ in range ( max_iter ) : max_iter -= 1 found_something = False for rule in rules . values ( ) : for match_index in rule . find_matches ( topology ) : atom = atoms [ match_index ] if rule . name not in atom . whitelist : atom . whitelist . add ( rule . name ) atom . blacklist |= rule . overrides found_something = True if not found_something : break else : warn ( "Reached maximum iterations. Something probably went wrong." ) | Iteratively run all the rules until the white - and backlists converge . | 140 | 15 |
234,985 | def _resolve_atomtypes ( topology ) : for atom in topology . atoms ( ) : atomtype = [ rule_name for rule_name in atom . whitelist - atom . blacklist ] if len ( atomtype ) == 1 : atom . id = atomtype [ 0 ] elif len ( atomtype ) > 1 : raise FoyerError ( "Found multiple types for atom {} ({}): {}." . format ( atom . index , atom . element . name , atomtype ) ) else : raise FoyerError ( "Found no types for atom {} ({})." . format ( atom . index , atom . element . name ) ) | Determine the final atomtypes from the white - and blacklists . | 136 | 15 |
234,986 | def generate_topology ( non_omm_topology , non_element_types = None , residues = None ) : if non_element_types is None : non_element_types = set ( ) if isinstance ( non_omm_topology , pmd . Structure ) : return _topology_from_parmed ( non_omm_topology , non_element_types ) elif has_mbuild : mb = import_ ( 'mbuild' ) if ( non_omm_topology , mb . Compound ) : pmdCompoundStructure = non_omm_topology . to_parmed ( residues = residues ) return _topology_from_parmed ( pmdCompoundStructure , non_element_types ) else : raise FoyerError ( 'Unknown topology format: {}\n' 'Supported formats are: ' '"parmed.Structure", ' '"mbuild.Compound", ' '"openmm.app.Topology"' . format ( non_omm_topology ) ) | Create an OpenMM Topology from another supported topology structure . | 226 | 13 |
234,987 | def _topology_from_parmed ( structure , non_element_types ) : topology = app . Topology ( ) residues = dict ( ) for pmd_residue in structure . residues : chain = topology . addChain ( ) omm_residue = topology . addResidue ( pmd_residue . name , chain ) residues [ pmd_residue ] = omm_residue atoms = dict ( ) # pmd.Atom: omm.Atom for pmd_atom in structure . atoms : name = pmd_atom . name if pmd_atom . name in non_element_types : element = non_element_types [ pmd_atom . name ] else : if ( isinstance ( pmd_atom . atomic_number , int ) and pmd_atom . atomic_number != 0 ) : element = elem . Element . getByAtomicNumber ( pmd_atom . atomic_number ) else : element = elem . Element . getBySymbol ( pmd_atom . name ) omm_atom = topology . addAtom ( name , element , residues [ pmd_atom . residue ] ) atoms [ pmd_atom ] = omm_atom omm_atom . bond_partners = [ ] for bond in structure . bonds : atom1 = atoms [ bond . atom1 ] atom2 = atoms [ bond . atom2 ] topology . addBond ( atom1 , atom2 ) atom1 . bond_partners . append ( atom2 ) atom2 . bond_partners . append ( atom1 ) if structure . box_vectors and np . any ( [ x . _value for x in structure . box_vectors ] ) : topology . setPeriodicBoxVectors ( structure . box_vectors ) positions = structure . positions return topology , positions | Convert a ParmEd Structure to an OpenMM Topology . | 408 | 13 |
234,988 | def _topology_from_residue ( res ) : topology = app . Topology ( ) chain = topology . addChain ( ) new_res = topology . addResidue ( res . name , chain ) atoms = dict ( ) # { omm.Atom in res : omm.Atom in *new* topology } for res_atom in res . atoms ( ) : topology_atom = topology . addAtom ( name = res_atom . name , element = res_atom . element , residue = new_res ) atoms [ res_atom ] = topology_atom topology_atom . bond_partners = [ ] for bond in res . bonds ( ) : atom1 = atoms [ bond . atom1 ] atom2 = atoms [ bond . atom2 ] topology . addBond ( atom1 , atom2 ) atom1 . bond_partners . append ( atom2 ) atom2 . bond_partners . append ( atom1 ) return topology | Converts a openmm . app . Topology . Residue to openmm . app . Topology . | 216 | 23 |
234,989 | def _check_independent_residues ( topology ) : for res in topology . residues ( ) : atoms_in_residue = set ( [ atom for atom in res . atoms ( ) ] ) bond_partners_in_residue = [ item for sublist in [ atom . bond_partners for atom in res . atoms ( ) ] for item in sublist ] # Handle the case of a 'residue' with no neighbors if not bond_partners_in_residue : continue if set ( atoms_in_residue ) != set ( bond_partners_in_residue ) : return False return True | Check to see if residues will constitute independent graphs . | 143 | 10 |
234,990 | def _update_atomtypes ( unatomtyped_topology , res_name , prototype ) : for res in unatomtyped_topology . residues ( ) : if res . name == res_name : for old_atom , new_atom_id in zip ( [ atom for atom in res . atoms ( ) ] , [ atom . id for atom in prototype . atoms ( ) ] ) : old_atom . id = new_atom_id | Update atomtypes in residues in a topology using a prototype topology . | 97 | 15 |
234,991 | def registerAtomType ( self , parameters ) : name = parameters [ 'name' ] if name in self . _atomTypes : raise ValueError ( 'Found multiple definitions for atom type: ' + name ) atom_class = parameters [ 'class' ] mass = _convertParameterToNumber ( parameters [ 'mass' ] ) element = None if 'element' in parameters : element , custom = self . _create_element ( parameters [ 'element' ] , mass ) if custom : self . non_element_types [ element . symbol ] = element self . _atomTypes [ name ] = self . __class__ . _AtomType ( name , atom_class , mass , element ) if atom_class in self . _atomClasses : type_set = self . _atomClasses [ atom_class ] else : type_set = set ( ) self . _atomClasses [ atom_class ] = type_set type_set . add ( name ) self . _atomClasses [ '' ] . add ( name ) name = parameters [ 'name' ] if 'def' in parameters : self . atomTypeDefinitions [ name ] = parameters [ 'def' ] if 'overrides' in parameters : overrides = set ( atype . strip ( ) for atype in parameters [ 'overrides' ] . split ( "," ) ) if overrides : self . atomTypeOverrides [ name ] = overrides if 'des' in parameters : self . atomTypeDesc [ name ] = parameters [ 'desc' ] if 'doi' in parameters : dois = set ( doi . strip ( ) for doi in parameters [ 'doi' ] . split ( ',' ) ) self . atomTypeRefs [ name ] = dois | Register a new atom type . | 374 | 6 |
234,992 | def run_atomtyping ( self , topology , use_residue_map = True ) : if use_residue_map : independent_residues = _check_independent_residues ( topology ) if independent_residues : residue_map = dict ( ) for res in topology . residues ( ) : if res . name not in residue_map . keys ( ) : residue = _topology_from_residue ( res ) find_atomtypes ( residue , forcefield = self ) residue_map [ res . name ] = residue for key , val in residue_map . items ( ) : _update_atomtypes ( topology , key , val ) else : find_atomtypes ( topology , forcefield = self ) else : find_atomtypes ( topology , forcefield = self ) if not all ( [ a . id for a in topology . atoms ( ) ] [ 0 ] ) : raise ValueError ( 'Not all atoms in topology have atom types' ) return topology | Atomtype the topology | 222 | 6 |
234,993 | def cd ( directory ) : old_dir = os . getcwd ( ) try : os . chdir ( directory ) yield finally : os . chdir ( old_dir ) | Change the current working directory temporarily . | 38 | 7 |
234,994 | def mkdtemp ( hint = '' ) : dirname = tempfile . mkdtemp ( prefix = 'check-manifest-' , suffix = hint ) try : yield dirname finally : rmtree ( dirname ) | Create a temporary directory then clean it up . | 47 | 9 |
234,995 | def chmod_plus ( path , add_bits = stat . S_IWUSR ) : try : os . chmod ( path , stat . S_IMODE ( os . stat ( path ) . st_mode ) | add_bits ) except OSError : # pragma: nocover pass | Change a file s mode by adding a few bits . | 68 | 11 |
234,996 | def rmtree ( path ) : def onerror ( func , path , exc_info ) : # Did you know what on Python 3.3 on Windows os.remove() and # os.unlink() are distinct functions? if func is os . remove or func is os . unlink or func is os . rmdir : if sys . platform != 'win32' : chmod_plus ( os . path . dirname ( path ) , stat . S_IWUSR | stat . S_IXUSR ) chmod_plus ( path ) func ( path ) else : raise shutil . rmtree ( path , onerror = onerror ) | A version of rmtree that can deal with read - only files and directories . | 141 | 17 |
234,997 | def copy_files ( filelist , destdir ) : for filename in filelist : destfile = os . path . join ( destdir , filename ) # filename should not be absolute, but let's double-check assert destfile . startswith ( destdir + os . path . sep ) destfiledir = os . path . dirname ( destfile ) if not os . path . isdir ( destfiledir ) : os . makedirs ( destfiledir ) if os . path . isdir ( filename ) : os . mkdir ( destfile ) else : shutil . copy2 ( filename , destfile ) | Copy a list of files to destdir preserving directory structure . | 135 | 12 |
234,998 | def get_one_file_in ( dirname ) : files = os . listdir ( dirname ) if len ( files ) > 1 : raise Failure ( 'More than one file exists in %s:\n%s' % ( dirname , '\n' . join ( sorted ( files ) ) ) ) elif not files : raise Failure ( 'No files found in %s' % dirname ) return os . path . join ( dirname , files [ 0 ] ) | Return the pathname of the one file in a directory . | 102 | 12 |
234,999 | def unicodify ( filename ) : if isinstance ( filename , bytes ) : return filename . decode ( locale . getpreferredencoding ( ) ) else : return filename | Make sure filename is Unicode . | 36 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.