idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
235,800
def from_yaml ( cls , yaml_str = None , str_or_buffer = None ) : cfg = yamlio . yaml_to_dict ( yaml_str , str_or_buffer ) model = cls ( cfg [ 'model_expression' ] , cfg [ 'sample_size' ] , probability_mode = cfg . get ( 'probability_mode' , 'full_product' ) , choice_mode = cfg . get ( 'choice_mode' , 'individual' ) , c...
Create a DiscreteChoiceModel instance from a saved YAML configuration . Arguments are mutally exclusive .
235,801
def fit ( self , choosers , alternatives , current_choice ) : logger . debug ( 'start: fit LCM model {}' . format ( self . name ) ) if not isinstance ( current_choice , pd . Series ) : current_choice = choosers [ current_choice ] choosers , alternatives = self . apply_fit_filters ( choosers , alternatives ) if self . e...
Fit and save model parameters based on given data .
235,802
def probabilities ( self , choosers , alternatives , filter_tables = True ) : logger . debug ( 'start: calculate probabilities for LCM model {}' . format ( self . name ) ) self . assert_fitted ( ) if filter_tables : choosers , alternatives = self . apply_predict_filters ( choosers , alternatives ) if self . prediction_...
Returns the probabilities for a set of choosers to choose from among a set of alternatives .
235,803
def summed_probabilities ( self , choosers , alternatives ) : def normalize ( s ) : return s / s . sum ( ) choosers , alternatives = self . apply_predict_filters ( choosers , alternatives ) probs = self . probabilities ( choosers , alternatives , filter_tables = False ) if self . probability_mode == 'single_chooser' : ...
Calculate total probability associated with each alternative .
235,804
def predict ( self , choosers , alternatives , debug = False ) : self . assert_fitted ( ) logger . debug ( 'start: predict LCM model {}' . format ( self . name ) ) choosers , alternatives = self . apply_predict_filters ( choosers , alternatives ) if len ( choosers ) == 0 : return pd . Series ( ) if len ( alternatives )...
Choose from among alternatives for a group of agents .
235,805
def to_dict ( self ) : return { 'model_type' : 'discretechoice' , 'model_expression' : self . model_expression , 'sample_size' : self . sample_size , 'name' : self . name , 'probability_mode' : self . probability_mode , 'choice_mode' : self . choice_mode , 'choosers_fit_filters' : self . choosers_fit_filters , 'chooser...
Return a dict respresentation of an MNLDiscreteChoiceModel instance .
235,806
def choosers_columns_used ( self ) : return list ( tz . unique ( tz . concatv ( util . columns_in_filters ( self . choosers_predict_filters ) , util . columns_in_filters ( self . choosers_fit_filters ) ) ) )
Columns from the choosers table that are used for filtering .
235,807
def interaction_columns_used ( self ) : return list ( tz . unique ( tz . concatv ( util . columns_in_filters ( self . interaction_predict_filters ) , util . columns_in_formula ( self . model_expression ) ) ) )
Columns from the interaction dataset used for filtering and in the model . These may come originally from either the choosers or alternatives tables .
235,808
def predict_from_cfg ( cls , choosers , alternatives , cfgname = None , cfg = None , alternative_ratio = 2.0 , debug = False ) : logger . debug ( 'start: predict from configuration {}' . format ( cfgname ) ) if cfgname : lcm = cls . from_yaml ( str_or_buffer = cfgname ) elif cfg : lcm = cls . from_yaml ( yaml_str = cfg...
Simulate choices for the specified choosers
235,809
def add_model_from_params ( self , name , model_expression , sample_size , probability_mode = 'full_product' , choice_mode = 'individual' , choosers_fit_filters = None , choosers_predict_filters = None , alts_fit_filters = None , alts_predict_filters = None , interaction_predict_filters = None , estimation_sample_size ...
Add a model by passing parameters through to MNLDiscreteChoiceModel .
235,810
def apply_fit_filters ( self , choosers , alternatives ) : ch = [ ] alts = [ ] for name , df in self . _iter_groups ( choosers ) : filtered_choosers , filtered_alts = self . models [ name ] . apply_fit_filters ( df , alternatives ) ch . append ( filtered_choosers ) alts . append ( filtered_alts ) return pd . concat ( c...
Filter choosers and alternatives for fitting . This is done by filtering each submodel and concatenating the results .
235,811
def fit ( self , choosers , alternatives , current_choice ) : with log_start_finish ( 'fit models in LCM group {}' . format ( self . name ) , logger ) : return { name : self . models [ name ] . fit ( df , alternatives , current_choice ) for name , df in self . _iter_groups ( choosers ) }
Fit and save models based on given data after segmenting the choosers table .
235,812
def fitted ( self ) : return ( all ( m . fitted for m in self . models . values ( ) ) if self . models else False )
Whether all models in the group have been fitted .
235,813
def summed_probabilities ( self , choosers , alternatives ) : if len ( alternatives ) == 0 or len ( choosers ) == 0 : return pd . Series ( ) logger . debug ( 'start: calculate summed probabilities in LCM group {}' . format ( self . name ) ) probs = [ ] for name , df in self . _iter_groups ( choosers ) : probs . append ...
Returns the sum of probabilities for alternatives across all chooser segments .
235,814
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' ] seg = cls ( cfg [ 'segmentation_col' ] , cfg [ 'sample_size' ] , cfg [ 'probability_mode' ] , cfg [ 'choice_mode' ] , cfg [ 'choo...
Create a SegmentedMNLDiscreteChoiceModel instance from a saved YAML configuration . Arguments are mutally exclusive .
235,815
def add_segment ( self , name , model_expression = None ) : logger . debug ( 'adding LCM model {} to segmented model {}' . format ( name , self . name ) ) if not model_expression : if not self . default_model_expr : raise ValueError ( 'No default model available, ' 'you must supply a model expression.' ) model_expressi...
Add a new segment with its own model expression .
235,816
def fit ( self , choosers , alternatives , current_choice ) : logger . debug ( 'start: fit models in segmented LCM {}' . format ( self . name ) ) choosers , alternatives = self . apply_fit_filters ( choosers , alternatives ) unique = choosers [ self . segmentation_col ] . unique ( ) gone = set ( self . _group . models ...
Fit and save models based on given data after segmenting the choosers table . Segments that have not already been explicitly added will be automatically added with default model .
235,817
def _filter_choosers_alts ( self , choosers , alternatives ) : return ( util . apply_filter_query ( choosers , self . choosers_predict_filters ) , util . apply_filter_query ( alternatives , self . alts_predict_filters ) )
Apply filters to the choosers and alts tables .
235,818
def cache_to_df ( dir_path ) : table = { } for attrib in glob . glob ( os . path . join ( dir_path , '*' ) ) : attrib_name , attrib_ext = os . path . splitext ( os . path . basename ( attrib ) ) if attrib_ext == '.lf8' : attrib_data = np . fromfile ( attrib , np . float64 ) table [ attrib_name ] = attrib_data elif attr...
Convert a directory of binary array data files to a Pandas DataFrame .
235,819
def convert_dirs ( base_dir , hdf_name , complib = None , complevel = 0 ) : print ( 'Converting directories in {}' . format ( base_dir ) ) dirs = glob . glob ( os . path . join ( base_dir , '*' ) ) dirs = { d for d in dirs if os . path . basename ( d ) in DIRECTORIES } if not dirs : raise RuntimeError ( 'No direcotries...
Convert nested set of directories to
235,820
def get_run_number ( ) : try : f = open ( os . path . join ( os . getenv ( 'DATA_HOME' , "." ) , 'RUNNUM' ) , 'r' ) num = int ( f . read ( ) ) f . close ( ) except Exception : num = 1 f = open ( os . path . join ( os . getenv ( 'DATA_HOME' , "." ) , 'RUNNUM' ) , 'w' ) f . write ( str ( num + 1 ) ) f . close ( ) return ...
Get a run number for this execution of the model system for identifying the output hdf5 files ) .
235,821
def compute_range ( travel_data , attr , travel_time_attr , dist , agg = np . sum ) : travel_data = travel_data . reset_index ( level = 1 ) travel_data = travel_data [ travel_data [ travel_time_attr ] < dist ] travel_data [ "attr" ] = attr [ travel_data . to_zone_id ] . values return travel_data . groupby ( level = 0 )...
Compute a zone - based accessibility query using the urbansim format travel data dataframe .
235,822
def reindex ( series1 , series2 ) : df = pd . merge ( pd . DataFrame ( { "left" : series2 } ) , pd . DataFrame ( { "right" : series1 } ) , left_on = "left" , right_index = True , how = "left" ) return df . right
This reindexes the first series by the second series . This is an extremely common operation that does not appear to be in Pandas at this time . If anyone knows of an easier way to do this in Pandas please inform the UrbanSim developers .
235,823
def df64bitto32bit ( tbl ) : newtbl = pd . DataFrame ( index = tbl . index ) for colname in tbl . columns : newtbl [ colname ] = series64bitto32bit ( tbl [ colname ] ) return newtbl
Convert a Pandas dataframe from 64 bit types to 32 bit types to save memory or disk space .
235,824
def series64bitto32bit ( s ) : if s . dtype == np . float64 : return s . astype ( 'float32' ) elif s . dtype == np . int64 : return s . astype ( 'int32' ) return s
Convert a Pandas series from 64 bit types to 32 bit types to save memory or disk space .
235,825
def pandasdfsummarytojson ( df , ndigits = 3 ) : df = df . transpose ( ) return { k : _pandassummarytojson ( v , ndigits ) for k , v in df . iterrows ( ) }
Convert the result of a
235,826
def column_map ( tables , columns ) : if not columns : return { t . name : None for t in tables } columns = set ( columns ) colmap = { t . name : list ( set ( t . columns ) . intersection ( columns ) ) for t in tables } foundcols = tz . reduce ( lambda x , y : x . union ( y ) , ( set ( v ) for v in colmap . values ( ) ...
Take a list of tables and a list of column names and resolve which columns come from which table .
235,827
def column_list ( tables , columns ) : columns = set ( columns ) foundcols = tz . reduce ( lambda x , y : x . union ( y ) , ( set ( t . columns ) for t in tables ) ) return list ( columns . intersection ( foundcols ) )
Take a list of tables and a list of column names and return the columns that are present in the tables .
235,828
def accounting_sample_replace ( total , data , accounting_column , prob_column = None , max_iterations = 50 ) : p = get_probs ( data , prob_column ) per_sample = data [ accounting_column ] . sum ( ) / ( 1.0 * len ( data . index . values ) ) curr_total = 0 remaining = total sample_rows = pd . DataFrame ( ) closest = Non...
Sample rows with accounting with replacement .
235,829
def accounting_sample_no_replace ( total , data , accounting_column , prob_column = None ) : if total > data [ accounting_column ] . sum ( ) : raise ValueError ( 'Control total exceeds the available samples' ) p = get_probs ( data , prob_column ) if p is None : shuff_idx = np . random . permutation ( data . index . val...
Samples rows with accounting without replacement .
235,830
def _convert_types ( self ) : self . fars = np . array ( self . fars ) self . parking_rates = np . array ( [ self . parking_rates [ use ] for use in self . uses ] ) self . res_ratios = { } assert len ( self . uses ) == len ( self . residential_uses ) for k , v in self . forms . items ( ) : self . forms [ k ] = np . arr...
convert lists and dictionaries that are useful for users to np vectors that are usable by machines
235,831
def _building_cost ( self , use_mix , stories ) : c = self . config heights = stories * c . height_per_story costs = np . searchsorted ( c . heights_for_costs , heights ) costs [ np . isnan ( heights ) ] = 0 costs = np . dot ( np . squeeze ( c . costs [ costs . astype ( 'int32' ) ] ) , use_mix ) costs [ np . isnan ( st...
Generate building cost for a set of buildings
235,832
def _generate_lookup ( self ) : c = self . config keys = c . forms . keys ( ) keys = sorted ( keys ) df_d = { } for name in keys : uses_distrib = c . forms [ name ] for parking_config in c . parking_configs : df = pd . DataFrame ( index = c . fars ) df [ 'far' ] = c . fars df [ 'pclsz' ] = c . tiled_parcel_sizes buildi...
Run the developer model on all possible inputs specified in the configuration object - not generally called by the user . This part computes the final cost per sqft of the building to construct and then turns it into the yearly rent necessary to make break even on that cost .
235,833
def lookup ( self , form , df , only_built = True , pass_through = None ) : df = pd . concat ( self . _lookup_parking_cfg ( form , parking_config , df , only_built , pass_through ) for parking_config in self . config . parking_configs ) if len ( df ) == 0 : return pd . DataFrame ( ) max_profit_ind = df . pivot ( column...
This function does the developer model lookups for all the actual input data .
235,834
def _debug_output ( self ) : import matplotlib matplotlib . use ( 'Agg' ) import matplotlib . pyplot as plt c = self . config df_d = self . dev_d keys = df_d . keys ( ) keys = sorted ( keys ) for key in keys : logger . debug ( "\n" + str ( key ) + "\n" ) logger . debug ( df_d [ key ] ) for form in self . config . forms...
this code creates the debugging plots to understand the behavior of the hypothetical building model
235,835
def add_rows ( data , nrows , starting_index = None , accounting_column = None ) : logger . debug ( 'start: adding {} rows in transition model' . format ( nrows ) ) if nrows == 0 : return data , _empty_index ( ) , _empty_index ( ) if not starting_index : starting_index = data . index . values . max ( ) + 1 new_rows = s...
Add rows to data table according to a given nrows . New rows will have their IDs set to NaN .
235,836
def remove_rows ( data , nrows , accounting_column = None ) : logger . debug ( 'start: removing {} rows in transition model' . format ( nrows ) ) nrows = abs ( nrows ) unit_check = data [ accounting_column ] . sum ( ) if accounting_column else len ( data ) if nrows == 0 : return data , _empty_index ( ) elif nrows > uni...
Remove a random nrows number of rows from a table .
235,837
def _update_linked_table ( table , col_name , added , copied , removed ) : logger . debug ( 'start: update linked table after transition' ) table = table . loc [ ~ table [ col_name ] . isin ( set ( removed ) ) ] if ( added is None or len ( added ) == 0 ) : return table id_map = pd . concat ( [ pd . Series ( copied , na...
Copy and update rows in a table that has a column referencing another table that has had rows added via copying .
235,838
def transition ( self , data , year , linked_tables = None ) : logger . debug ( 'start: transition' ) linked_tables = linked_tables or { } updated_links = { } with log_start_finish ( 'add/remove rows' , logger ) : updated , added , copied , removed = self . transitioner ( data , year ) for table_name , ( table , col ) ...
Add or remove rows from a table based on population targets .
235,839
def series_to_yaml_safe ( series , ordered = False ) : index = series . index . to_native_types ( quoting = True ) values = series . values . tolist ( ) if ordered : return OrderedDict ( tuple ( ( k , v ) ) for k , v in zip ( index , values ) ) else : return { i : v for i , v in zip ( index , values ) }
Convert a pandas Series to a dict that will survive YAML serialization and re - conversion back to a Series .
235,840
def frame_to_yaml_safe ( frame , ordered = False ) : if ordered : return OrderedDict ( tuple ( ( col , series_to_yaml_safe ( series , True ) ) for col , series in frame . iteritems ( ) ) ) else : return { col : series_to_yaml_safe ( series ) for col , series in frame . iteritems ( ) }
Convert a pandas DataFrame to a dictionary that will survive YAML serialization and re - conversion back to a DataFrame .
235,841
def ordered_yaml ( cfg , order = None ) : if order is None : order = [ 'name' , 'model_type' , 'segmentation_col' , 'fit_filters' , 'predict_filters' , 'choosers_fit_filters' , 'choosers_predict_filters' , 'alts_fit_filters' , 'alts_predict_filters' , 'interaction_predict_filters' , 'choice_column' , 'sample_size' , 'e...
Convert a dictionary to a YAML string with preferential ordering for some keys . Converted string is meant to be fairly human readable .
235,842
def convert_to_yaml ( cfg , str_or_buffer ) : order = None if isinstance ( cfg , OrderedDict ) : order = [ ] s = ordered_yaml ( cfg , order ) if not str_or_buffer : return s elif isinstance ( str_or_buffer , str ) : with open ( str_or_buffer , 'w' ) as f : f . write ( s ) else : str_or_buffer . write ( s )
Convert a dictionary to YAML and return the string or write it out depending on the type of str_or_buffer .
235,843
def add_transaction ( self , amount , subaccount = None , metadata = None ) : metadata = metadata or { } self . transactions . append ( Transaction ( amount , subaccount , metadata ) ) self . balance += amount
Add a new transaction to the account .
235,844
def total_transactions_by_subacct ( self , subaccount ) : return sum ( t . amount for t in self . transactions if t . subaccount == subaccount )
Get the sum of all transactions for a given subaccount .
235,845
def to_frame ( self ) : col_names = _column_names_from_metadata ( t . metadata for t in self . transactions ) def trow ( t ) : return tz . concatv ( ( t . amount , t . subaccount ) , ( t . metadata . get ( c ) for c in col_names ) ) rows = [ trow ( t ) for t in self . transactions ] if len ( rows ) == 0 : return pd . D...
Return transactions as a pandas DataFrame .
235,846
def apply_filter_query ( df , filters = None ) : with log_start_finish ( 'apply filter query: {!r}' . format ( filters ) , logger ) : if filters : if isinstance ( filters , str ) : query = filters else : query = ' and ' . join ( filters ) return df . query ( query ) else : return df
Use the DataFrame . query method to filter a table down to the desired rows .
235,847
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 ...
Turn a name and value into a string expression compatible the DataFrame . query method .
235,848
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 : left_side = None right_side = ' + ' . join ( expr ) if le...
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 .
235,849
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 yield prev , df . iloc [ start : ]
Perform a groupby on a DataFrame using a specific column and assuming that that column is sorted .
235,850
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 re...
Returns a list of the columns used in a set of query filters .
235,851
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 .
235,852
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 ...
Returns the names of all the columns used in a patsy formula .
235,853
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 v...
Use statsmodels OLS to construct a model relation .
235,854
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 a...
Apply model to new data to predict new dependent values .
235,855
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 .
235,856
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 .
235,857
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' ] ...
Create a RegressionModel instance from a saved YAML configuration . Arguments are mutually exclusive .
235,858
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 .
235,859
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 ...
Returns a dictionary representation of a RegressionModel instance .
235,860
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 .
235,861
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 .
235,862
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 ] = mo...
Add a model by passing arguments through to RegressionModel .
235,863
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 .
235,864
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' ] , c...
Create a SegmentedRegressionModel instance from a saved YAML configuration . Arguments are mutally exclusive .
235,865
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' : ytrans...
Add a new segment with its own model expression and ytransform .
235,866
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 ( ) gone = set ( self . _group . models ) - set ( unique ) for g in gone : del self . _group . mo...
Fit each segment . Segments that have not already been explicitly added will be automatically added with default model and ytransform .
235,867
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 .
235,868
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 } ) . in...
Returns an array of the indexes of the choosers that are slated to move .
235,869
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' ) demand = lcm . summed_probabilities ( choosers , alternatives ) demand = demand . groupby ( alt_segme...
Calculate adjustments to prices to compensate for supply and demand effects .
235,870
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' ) alternatives = alternatives . copy ( ) if...
Adjust real estate prices to compensate for supply and demand effects .
235,871
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 .
235,872
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 . in...
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 .
235,873
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...
Compute number of units to build to match target vacancy .
235,874
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 : return if form is None : df = self . feasi...
Choose the buildings from the list that are feasible to build in order to match the specified demand .
235,875
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 .
235,876
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 .
235,877
def _correlate ( self ) : a = self . algorithm ( ** self . algorithm_params ) self . correlation_result = a . run ( )
Run correlation algorithm .
235,878
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 room = ( end_t - ...
Analyzes if a matrix has anomalies . If any anomaly is found determine if the matrix correlates with any other matrixes . To be implemented .
235,879
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 : anom_scores [ timestamp ] = max ( anom_scores_ema [ timestamp ] , anom_scores_ema [ timestamp ] * DEFAULT_DETECTOR_EMA_...
Set anomaly scores using a weighted sum .
235,880
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 ...
Compute derivatives of the time series .
235,881
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 self . lag_window_size > D...
Check if there are enough data points .
235,882
def _generate_SAX ( self ) : sections = { } self . value_min = self . time_series . min ( ) self . value_max = self . time_series . max ( ) section_height = ( self . value_max - self . value_min ) / self . precision for section_number in range ( self . precision ) : sections [ section_number ] = self . value_min + sect...
Generate SAX representation for all values of the time series .
235,883
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...
Compute anomaly scores for the time series by sliding both lagging window and future window .
235,884
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...
Detect correlation by computing correlation coefficients for all allowed shift steps then take the maximum .
235,885
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 : ano...
Compute anomaly scores using a lagging window .
235,886
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...
Compute anomaly scores using a lagging window covering all the data points before .
235,887
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__ ) ...
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 .
235,888
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 .
235,889
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 ...
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 .
235,890
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 .
235,891
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 .
235,892
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 .
235,893
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 .
235,894
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 .
235,895
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 .
235,896
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 .
235,897
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 .
235,898
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 .
235,899
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 .