idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
46,900
def ast_to_html ( self , ast , link_resolver ) : out , _ = cmark . ast_to_html ( ast , link_resolver ) return out
See the documentation of to_ast for more information .
46,901
def translate_comment ( self , comment , link_resolver ) : out = u'' self . translate_tags ( comment , link_resolver ) ast = self . comment_to_ast ( comment , link_resolver ) out += self . ast_to_html ( ast , link_resolver ) return out
Given a gtk - doc comment string returns the comment translated to the desired format .
46,902
def comment_from_tag ( tag ) : if not tag : return None comment = Comment ( name = tag . name , meta = { 'description' : tag . description } , annotations = tag . annotations ) return comment
Convenience function to create a full - fledged comment for a given tag for example it is convenient to assign a Comment to a ReturnValueSymbol .
46,903
def decoder ( data ) : def next_byte ( _it , start , count ) : try : return next ( _it ) [ 1 ] except StopIteration : raise UnicodeDecodeError ( NAME , data , start , start + count , "incomplete byte sequence" ) it = iter ( enumerate ( data ) ) for i , d in it : if d == 0x00 : raise UnicodeDecodeError ( NAME , data , i...
This generator processes a sequence of bytes in Modified UTF - 8 encoding and produces a sequence of unicode string characters .
46,904
def decode_modified_utf8 ( data , errors = "strict" ) : value , length = u"" , 0 it = iter ( decoder ( data ) ) while True : try : value += next ( it ) length += 1 except StopIteration : break except UnicodeDecodeError as e : if errors == "strict" : raise e elif errors == "ignore" : pass elif errors == "replace" : valu...
Decodes a sequence of bytes to a unicode text and length using Modified UTF - 8 . This function is designed to be used with Python codecs module .
46,905
def apply ( self , byte , value , data , i , count ) : if byte & self . mask == self . value : value <<= self . bits value |= byte & self . mask2 else : raise UnicodeDecodeError ( NAME , data , i , i + count , "invalid {}-byte sequence" . format ( self . count ) ) return value
Apply mask compare to expected value shift and return result . Eventually this could become a reduce function .
46,906
def load ( file_object , * transformers , ** kwargs ) : ignore_remaining_data = kwargs . get ( "ignore_remaining_data" , False ) marshaller = JavaObjectUnmarshaller ( file_object , kwargs . get ( "use_numpy_arrays" , False ) ) for transformer in transformers : marshaller . add_transformer ( transformer ) marshaller . a...
Deserializes Java primitive data and objects serialized using ObjectOutputStream from a file - like object .
46,907
def loads ( string , * transformers , ** kwargs ) : ignore_remaining_data = kwargs . get ( "ignore_remaining_data" , False ) return load ( BytesIO ( string ) , * transformers , ignore_remaining_data = ignore_remaining_data )
Deserializes Java objects and primitive data serialized using ObjectOutputStream from a string .
46,908
def read ( data , fmt_str ) : size = struct . calcsize ( fmt_str ) return struct . unpack ( fmt_str , data [ : size ] ) , data [ size : ]
Reads input bytes and extract the given structure . Returns both the read elements and the remaining data
46,909
def flags ( flags ) : names = sorted ( descr for key , descr in OpCodeDebug . STREAM_CONSTANT . items ( ) if key & flags ) return ", " . join ( names )
Returns the names of the class description flags found in the given integer
46,910
def _readStreamHeader ( self ) : ( magic , version ) = self . _readStruct ( ">HH" ) if magic != self . STREAM_MAGIC or version != self . STREAM_VERSION : raise IOError ( "The stream is not java serialized object. " "Invalid stream header: {0:04X}{1:04X}" . format ( magic , version ) )
Reads the magic header of a Java serialization stream
46,911
def _read_and_exec_opcode ( self , ident = 0 , expect = None ) : position = self . object_stream . tell ( ) ( opid , ) = self . _readStruct ( ">B" ) log_debug ( "OpCode: 0x{0:X} -- {1} (at offset 0x{2:X})" . format ( opid , OpCodeDebug . op_id ( opid ) , position ) , ident , ) if expect and opid not in expect : raise I...
Reads the next opcode and executes its handler
46,912
def do_string ( self , parent = None , ident = 0 ) : log_debug ( "[string]" , ident ) ba = JavaString ( self . _readString ( ) ) self . _add_reference ( ba , ident ) return ba
Handles a TC_STRING opcode
46,913
def do_array ( self , parent = None , ident = 0 ) : log_debug ( "[array]" , ident ) _ , classdesc = self . _read_and_exec_opcode ( ident = ident + 1 , expect = ( self . TC_CLASSDESC , self . TC_PROXYCLASSDESC , self . TC_NULL , self . TC_REFERENCE , ) , ) array = JavaArray ( classdesc ) self . _add_reference ( array , ...
Handles a TC_ARRAY opcode
46,914
def do_reference ( self , parent = None , ident = 0 ) : ( handle , ) = self . _readStruct ( ">L" ) log_debug ( "## Reference handle: 0x{0:X}" . format ( handle ) , ident ) ref = self . references [ handle - self . BASE_REFERENCE_IDX ] log_debug ( "###-> Type: {0} - Value: {1}" . format ( type ( ref ) , ref ) , ident ) ...
Handles a TC_REFERENCE opcode
46,915
def do_enum ( self , parent = None , ident = 0 ) : enum = JavaEnum ( ) _ , classdesc = self . _read_and_exec_opcode ( ident = ident + 1 , expect = ( self . TC_CLASSDESC , self . TC_PROXYCLASSDESC , self . TC_NULL , self . TC_REFERENCE , ) , ) enum . classdesc = classdesc self . _add_reference ( enum , ident ) _ , enumC...
Handles a TC_ENUM opcode
46,916
def _create_hexdump ( src , start_offset = 0 , length = 16 ) : FILTER = "" . join ( ( len ( repr ( chr ( x ) ) ) == 3 ) and chr ( x ) or "." for x in range ( 256 ) ) pattern = "{{0:04X}} {{1:<{0}}} {{2}}\n" . format ( length * 3 ) src = to_str ( src , "latin-1" ) result = [ ] for i in range ( 0 , len ( src ) , lengt...
Prepares an hexadecimal dump string
46,917
def _convert_char_to_type ( self , type_char ) : typecode = type_char if type ( type_char ) is int : typecode = chr ( type_char ) if typecode in self . TYPECODES_LIST : return typecode else : raise RuntimeError ( "Typecode {0} ({1}) isn't supported." . format ( type_char , typecode ) )
Ensures a read character is a typecode .
46,918
def _add_reference ( self , obj , ident = 0 ) : log_debug ( "## New reference handle 0x{0:X}: {1} -> {2}" . format ( len ( self . references ) + self . BASE_REFERENCE_IDX , type ( obj ) . __name__ , repr ( obj ) , ) , ident , ) self . references . append ( obj )
Adds a read reference to the marshaler storage
46,919
def _oops_dump_state ( self , ignore_remaining_data = False ) : log_error ( "==Oops state dump" + "=" * ( 30 - 17 ) ) log_error ( "References: {0}" . format ( self . references ) ) log_error ( "Stream seeking back at -16 byte (2nd line is an actual position!):" ) self . object_stream . seek ( - 16 , os . SEEK_CUR ) pos...
Log a deserialization error
46,920
def dump ( self , obj ) : self . references = [ ] self . object_obj = obj self . object_stream = BytesIO ( ) self . _writeStreamHeader ( ) self . writeObject ( obj ) return self . object_stream . getvalue ( )
Dumps the given object in the Java serialization format
46,921
def writeObject ( self , obj ) : log_debug ( "Writing object of type {0}" . format ( type ( obj ) . __name__ ) ) if isinstance ( obj , JavaArray ) : self . write_array ( obj ) elif isinstance ( obj , JavaEnum ) : self . write_enum ( obj ) elif isinstance ( obj , JavaObject ) : self . write_object ( obj ) elif isinstanc...
Appends an object to the serialization stream
46,922
def _writeString ( self , obj , use_reference = True ) : string = to_bytes ( obj , "utf-8" ) if use_reference and isinstance ( obj , JavaString ) : try : idx = self . references . index ( obj ) except ValueError : self . references . append ( obj ) logging . debug ( "*** Adding ref 0x%X for string: %s" , len ( self . r...
Appends a string to the serialization stream
46,923
def write_string ( self , obj , use_reference = True ) : if use_reference and isinstance ( obj , JavaString ) : try : idx = self . references . index ( obj ) except ValueError : self . _writeStruct ( ">B" , 1 , ( self . TC_STRING , ) ) self . _writeString ( obj , use_reference ) else : logging . debug ( "*** Reusing re...
Writes a Java string with the TC_STRING type marker
46,924
def write_enum ( self , obj ) : self . _writeStruct ( ">B" , 1 , ( self . TC_ENUM , ) ) try : idx = self . references . index ( obj ) except ValueError : self . references . append ( obj ) logging . debug ( "*** Adding ref 0x%X for enum: %s" , len ( self . references ) - 1 + self . BASE_REFERENCE_IDX , obj , ) self . w...
Writes an Enum value
46,925
def write_blockdata ( self , obj , parent = None ) : if type ( obj ) is str : obj = to_bytes ( obj , "latin-1" ) length = len ( obj ) if length <= 256 : self . _writeStruct ( ">B" , 1 , ( self . TC_BLOCKDATA , ) ) self . _writeStruct ( ">B" , 1 , ( length , ) ) else : self . _writeStruct ( ">B" , 1 , ( self . TC_BLOCKD...
Appends a block of data to the serialization stream
46,926
def write_object ( self , obj , parent = None ) : for transformer in self . object_transformers : tmp_object = transformer . transform ( obj ) if tmp_object is not obj : obj = tmp_object break self . _writeStruct ( ">B" , 1 , ( self . TC_OBJECT , ) ) cls = obj . get_class ( ) self . write_classdesc ( cls ) self . refer...
Writes an object header to the serialization stream
46,927
def write_class ( self , obj , parent = None ) : self . _writeStruct ( ">B" , 1 , ( self . TC_CLASS , ) ) self . write_classdesc ( obj )
Writes a class to the stream
46,928
def write_classdesc ( self , obj , parent = None ) : if obj not in self . references : self . references . append ( obj ) logging . debug ( "*** Adding ref 0x%X for classdesc %s" , len ( self . references ) - 1 + self . BASE_REFERENCE_IDX , obj . name , ) self . _writeStruct ( ">B" , 1 , ( self . TC_CLASSDESC , ) ) sel...
Writes a class description
46,929
def write_array ( self , obj ) : classdesc = obj . get_class ( ) self . _writeStruct ( ">B" , 1 , ( self . TC_ARRAY , ) ) self . write_classdesc ( classdesc ) self . _writeStruct ( ">i" , 1 , ( len ( obj ) , ) ) self . references . append ( obj ) logging . debug ( "*** Adding ref 0x%X for array []" , len ( self . refer...
Writes a JavaArray
46,930
def _write_value ( self , field_type , value ) : if len ( field_type ) > 1 : field_type = field_type [ 0 ] if field_type == self . TYPE_BOOLEAN : self . _writeStruct ( ">B" , 1 , ( 1 if value else 0 , ) ) elif field_type == self . TYPE_BYTE : self . _writeStruct ( ">b" , 1 , ( value , ) ) elif field_type == self . TYPE...
Writes an item of an array
46,931
def _convert_type_to_char ( self , type_char ) : typecode = type_char if type ( type_char ) is int : typecode = chr ( type_char ) if typecode in self . TYPECODES_LIST : return ord ( typecode ) elif len ( typecode ) > 1 : if typecode [ 0 ] == "L" : return ord ( self . TYPE_OBJECT ) elif typecode [ 0 ] == "[" : return or...
Converts the given type code to an int
46,932
def create ( self , classdesc , unmarshaller = None ) : try : mapped_type = self . TYPE_MAPPER [ classdesc . name ] except KeyError : return JavaObject ( ) else : log_debug ( "---" ) log_debug ( classdesc . name ) log_debug ( "---" ) java_object = mapped_type ( unmarshaller ) log_debug ( ">>> java_object: {0}" . format...
Transforms a deserialized Java object into a Python object
46,933
def mnl_simulate ( data , coeff , numalts , GPU = False , returnprobs = True ) : logger . debug ( 'start: MNL simulation with len(data)={} and numalts={}' . format ( len ( data ) , numalts ) ) atype = 'numpy' if not GPU else 'cuda' data = np . transpose ( data ) coeff = np . reshape ( np . array ( coeff ) , ( 1 , len (...
Get the probabilities for each chooser choosing between numalts alternatives .
46,934
def mnl_estimate ( data , chosen , numalts , GPU = False , coeffrange = ( - 3 , 3 ) , weights = None , lcgrad = False , beta = None ) : logger . debug ( 'start: MNL fit with len(data)={} and numalts={}' . format ( len ( data ) , numalts ) ) atype = 'numpy' if not GPU else 'cuda' numvars = data . shape [ 1 ] numobs = da...
Calculate coefficients of the MNL model .
46,935
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 .
46,936
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 .
46,937
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 .
46,938
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 .
46,939
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 .
46,940
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 .
46,941
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 .
46,942
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 .
46,943
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
46,944
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 .
46,945
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 .
46,946
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 .
46,947
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 .
46,948
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 .
46,949
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 .
46,950
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 .
46,951
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 .
46,952
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 .
46,953
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 .
46,954
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
46,955
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 ) .
46,956
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 .
46,957
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 .
46,958
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 .
46,959
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 .
46,960
def pandasdfsummarytojson ( df , ndigits = 3 ) : df = df . transpose ( ) return { k : _pandassummarytojson ( v , ndigits ) for k , v in df . iterrows ( ) }
Convert the result of a
46,961
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 .
46,962
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 .
46,963
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 .
46,964
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 .
46,965
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
46,966
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
46,967
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 .
46,968
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 .
46,969
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
46,970
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 .
46,971
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 .
46,972
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 .
46,973
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 .
46,974
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 .
46,975
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 .
46,976
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 .
46,977
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 .
46,978
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 .
46,979
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 .
46,980
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 .
46,981
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 .
46,982
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 .
46,983
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 .
46,984
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 .
46,985
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 .
46,986
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 .
46,987
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 .
46,988
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 .
46,989
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 .
46,990
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 .
46,991
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 .
46,992
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 .
46,993
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 .
46,994
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 .
46,995
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 .
46,996
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 .
46,997
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 .
46,998
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 .
46,999
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 .