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,800 | def get_dependencies ( self ) : all_deps = OrderedSet ( ) for key , _ in list ( self . __config . items ( ) ) : if key in self . __cli : continue if key . endswith ( 'sources' ) : all_deps |= self . get_sources ( key [ : len ( 'sources' ) * - 1 - 1 ] ) for key , _ in list ( self . __cli . items ( ) ) : if key . endswith ( 'sources' ) : all_deps |= self . get_sources ( key [ : len ( 'sources' ) * - 1 - 1 ] ) if self . conf_file is not None : all_deps . add ( self . conf_file ) all_deps . add ( self . get_path ( "sitemap" , rel_to_cwd = True ) ) cwd = os . getcwd ( ) return [ os . path . relpath ( fname , cwd ) for fname in all_deps if fname ] | Retrieve the set of all dependencies for a given configuration . | 237 | 12 |
234,801 | def dump ( self , conf_file = None ) : if conf_file : conf_dir = os . path . dirname ( conf_file ) if not conf_dir : conf_dir = self . __invoke_dir elif not os . path . exists ( conf_dir ) : os . makedirs ( conf_dir ) else : conf_dir = self . __conf_dir final_conf = { } for key , value in list ( self . __config . items ( ) ) : if key in self . __cli : continue final_conf [ key ] = value for key , value in list ( self . __cli . items ( ) ) : if key . endswith ( 'index' ) or key in [ 'sitemap' , 'output' ] : path = self . __abspath ( value , from_conf = False ) if path : relpath = os . path . relpath ( path , conf_dir ) final_conf [ key ] = relpath elif key . endswith ( 'sources' ) or key . endswith ( 'source_filters' ) : new_list = [ ] for path in value : path = self . __abspath ( path , from_conf = False ) if path : relpath = os . path . relpath ( path , conf_dir ) new_list . append ( relpath ) final_conf [ key ] = new_list elif key not in [ 'command' , 'output_conf_file' ] : final_conf [ key ] = value with open ( conf_file or self . conf_file or 'hotdoc.json' , 'w' ) as _ : _ . write ( json . dumps ( final_conf , sort_keys = True , indent = 4 ) ) | Dump the possibly updated config to a file . | 383 | 10 |
234,802 | def _update_submodules ( repo_dir ) : subprocess . check_call ( "git submodule init" , cwd = repo_dir , shell = True ) subprocess . check_call ( "git submodule update --recursive" , cwd = repo_dir , shell = True ) | update submodules in a repo | 65 | 6 |
234,803 | def require_clean_submodules ( repo_root , submodules ) : # PACKAGERS: Add a return here to skip checks for git submodules # don't do anything if nothing is actually supposed to happen for do_nothing in ( '-h' , '--help' , '--help-commands' , 'clean' , 'submodule' ) : if do_nothing in sys . argv : return status = _check_submodule_status ( repo_root , submodules ) if status == "missing" : print ( "checking out submodules for the first time" ) _update_submodules ( repo_root ) elif status == "unclean" : print ( UNCLEAN_SUBMODULES_MSG ) | Check on git submodules before distutils can do anything Since distutils cannot be trusted to update the tree after everything has been set in motion this is not a distutils command . | 160 | 36 |
234,804 | def symlink ( source , link_name ) : if os . path . islink ( link_name ) and os . readlink ( link_name ) == source : return os_symlink = getattr ( os , "symlink" , None ) if callable ( os_symlink ) : os_symlink ( source , link_name ) else : import ctypes csl = ctypes . windll . kernel32 . CreateSymbolicLinkW csl . argtypes = ( ctypes . c_wchar_p , ctypes . c_wchar_p , ctypes . c_uint32 ) csl . restype = ctypes . c_ubyte flags = 1 if os . path . isdir ( source ) else 0 if csl ( link_name , source , flags ) == 0 : raise ctypes . WinError ( ) | Method to allow creating symlinks on Windows | 190 | 8 |
234,805 | def pkgconfig ( * packages , * * kw ) : config = kw . setdefault ( 'config' , { } ) optional_args = kw . setdefault ( 'optional' , '' ) # { <distutils Extension arg>: [<pkg config option>, <prefix length to strip>], ...} flag_map = { 'include_dirs' : [ '--cflags-only-I' , 2 ] , 'library_dirs' : [ '--libs-only-L' , 2 ] , 'libraries' : [ '--libs-only-l' , 2 ] , 'extra_compile_args' : [ '--cflags-only-other' , 0 ] , 'extra_link_args' : [ '--libs-only-other' , 0 ] , } for package in packages : for distutils_key , ( pkg_option , n ) in flag_map . items ( ) : items = subprocess . check_output ( [ 'pkg-config' , optional_args , pkg_option , package ] ) . decode ( 'utf8' ) . split ( ) config . setdefault ( distutils_key , [ ] ) . extend ( [ i [ n : ] for i in items ] ) return config | Query pkg - config for library compile and linking options . Return configuration in distutils Extension format . | 278 | 20 |
234,806 | def register_error_code ( code , exception_type , domain = 'core' ) : Logger . _error_code_to_exception [ code ] = ( exception_type , domain ) Logger . _domain_codes [ domain ] . add ( code ) | Register a new error code | 58 | 5 |
234,807 | def register_warning_code ( code , exception_type , domain = 'core' ) : Logger . _warning_code_to_exception [ code ] = ( exception_type , domain ) Logger . _domain_codes [ domain ] . add ( code ) | Register a new warning code | 58 | 5 |
234,808 | def _log ( code , message , level , domain ) : entry = LogEntry ( level , domain , code , message ) Logger . journal . append ( entry ) if Logger . silent : return if level >= Logger . _verbosity : _print_entry ( entry ) | Call this to add an entry in the journal | 59 | 9 |
234,809 | def error ( code , message , * * kwargs ) : assert code in Logger . _error_code_to_exception exc_type , domain = Logger . _error_code_to_exception [ code ] exc = exc_type ( message , * * kwargs ) Logger . _log ( code , exc . message , ERROR , domain ) raise exc | Call this to raise an exception and have it stored in the journal | 82 | 13 |
234,810 | def warn ( code , message , * * kwargs ) : if code in Logger . _ignored_codes : return assert code in Logger . _warning_code_to_exception exc_type , domain = Logger . _warning_code_to_exception [ code ] if domain in Logger . _ignored_domains : return level = WARNING if Logger . fatal_warnings : level = ERROR exc = exc_type ( message , * * kwargs ) Logger . _log ( code , exc . message , level , domain ) if Logger . fatal_warnings : raise exc | Call this to store a warning in the journal . | 133 | 10 |
234,811 | def debug ( message , domain ) : if domain in Logger . _ignored_domains : return Logger . _log ( None , message , DEBUG , domain ) | Log debugging information | 36 | 3 |
234,812 | def info ( message , domain ) : if domain in Logger . _ignored_domains : return Logger . _log ( None , message , INFO , domain ) | Log simple info | 36 | 3 |
234,813 | def get_issues ( ) : issues = [ ] for entry in Logger . journal : if entry . level >= WARNING : issues . append ( entry ) return issues | Get actual issues in the journal . | 34 | 7 |
234,814 | def reset ( ) : Logger . journal = [ ] Logger . fatal_warnings = False Logger . _ignored_codes = set ( ) Logger . _ignored_domains = set ( ) Logger . _verbosity = 2 Logger . _last_checkpoint = 0 | Resets Logger to its initial state | 64 | 8 |
234,815 | def walk ( self , action , user_data = None ) : action ( self . index_file , self . __root , 0 , user_data ) self . __do_walk ( self . __root , 1 , action , user_data ) | Walk the hierarchy applying action to each filename . | 53 | 9 |
234,816 | def parse ( self , filename ) : with io . open ( filename , 'r' , encoding = 'utf-8' ) as _ : lines = _ . readlines ( ) all_source_files = set ( ) source_map = { } lineno = 0 root = None index = None cur_level = - 1 parent_queue = [ ] for line in lines : try : level , line = dedent ( line ) if line . startswith ( '#' ) : lineno += 1 continue elif line . startswith ( '\\#' ) : line = line [ 1 : ] except IndentError as exc : error ( 'bad-indent' , 'Invalid indentation' , filename = filename , lineno = lineno , column = exc . column ) if not line : lineno += 1 continue source_file = dequote ( line ) if not source_file : lineno += 1 continue if source_file in all_source_files : error ( 'sitemap-duplicate' , 'Filename listed twice' , filename = filename , lineno = lineno , column = level * 8 + 1 ) all_source_files . add ( source_file ) source_map [ source_file ] = ( lineno , level * 8 + 1 ) page = OrderedDict ( ) if root is not None and level == 0 : error ( 'sitemap-error' , 'Sitemaps only support one root' , filename = filename , lineno = lineno , column = 0 ) if root is None : root = page index = source_file else : lvl_diff = cur_level - level while lvl_diff >= 0 : parent_queue . pop ( ) lvl_diff -= 1 parent_queue [ - 1 ] [ source_file ] = page parent_queue . append ( page ) cur_level = level lineno += 1 return Sitemap ( root , filename , index , source_map ) | Parse a sitemap file . | 415 | 8 |
234,817 | def parse_comment ( self , comment , filename , lineno , endlineno , include_paths = None , stripped = False ) : if not stripped and not self . __validate_c_comment ( comment . strip ( ) ) : return None title_offset = 0 column_offset = 0 raw_comment = comment if not stripped : try : while comment [ column_offset * - 1 - 1 ] != '\n' : column_offset += 1 except IndexError : column_offset = 0 comment , title_offset = self . __strip_comment ( comment ) title_and_params , description = self . __extract_titles_params_and_description ( comment ) try : block_name , parameters , annotations , is_section = self . __parse_title_and_parameters ( filename , title_and_params ) except HotdocSourceException as _ : warn ( 'gtk-doc-bad-syntax' , message = _ . message , filename = filename , lineno = lineno + title_offset ) return None params_offset = 0 for param in parameters : param . filename = filename param . lineno = lineno param_offset = param . line_offset param . line_offset = title_offset + params_offset + 1 params_offset += param_offset param . col_offset = column_offset if not block_name : return None description_offset = 0 meta = { } tags = [ ] if description is not None : n_lines = len ( comment . split ( '\n' ) ) description_offset = ( title_offset + n_lines - len ( description . split ( '\n' ) ) ) meta [ 'description' ] , tags = self . __parse_description_and_tags ( description ) actual_parameters = OrderedDict ( { } ) for param in parameters : if is_section : cleaned_up_name = param . name . lower ( ) . replace ( '_' , '-' ) if cleaned_up_name in [ 'symbols' , 'private-symbols' , 'auto-sort' , 'sources' ] : meta . update ( self . __parse_yaml_comment ( param , filename ) ) if cleaned_up_name == 'sources' : sources_paths = [ os . path . abspath ( os . path . join ( os . path . dirname ( filename ) , path ) ) for path in meta [ cleaned_up_name ] ] meta [ cleaned_up_name ] = sources_paths else : meta [ param . name ] = param . description else : actual_parameters [ param . name ] = param annotations = { annotation . name : annotation for annotation in annotations } tags = { tag . name . lower ( ) : tag for tag in tags } block = Comment ( name = block_name , filename = filename , lineno = lineno , endlineno = endlineno , annotations = annotations , params = actual_parameters , tags = tags , raw_comment = raw_comment , meta = meta , toplevel = is_section ) block . line_offset = description_offset block . col_offset = column_offset return block | Returns a Comment given a string | 684 | 6 |
234,818 | def comment_to_ast ( self , comment , link_resolver ) : assert comment is not None text = comment . description if ( self . remove_xml_tags or comment . filename in self . gdbus_codegen_sources ) : text = re . sub ( '<.*?>' , '' , text ) if self . escape_html : # pylint: disable=deprecated-method text = cgi . escape ( text ) ast , diagnostics = cmark . gtkdoc_to_ast ( text , link_resolver ) for diag in diagnostics : if ( comment . filename and comment . filename not in self . gdbus_codegen_sources ) : column = diag . column + comment . col_offset if diag . lineno == 0 : column += comment . initial_col_offset lines = text . split ( '\n' ) line = lines [ diag . lineno ] i = 0 while line [ i ] == ' ' : i += 1 column += i - 1 if diag . lineno > 0 and any ( [ c != ' ' for c in lines [ diag . lineno - 1 ] ] ) : column += 1 lineno = - 1 if comment . lineno != - 1 : lineno = ( comment . lineno - 1 + comment . line_offset + diag . lineno ) warn ( diag . code , message = diag . message , filename = comment . filename , lineno = lineno , column = column ) return ast | Given a gtk - doc comment string returns an opaque PyCapsule containing the document root . | 327 | 20 |
234,819 | 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 . | 39 | 11 |
234,820 | 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 . | 68 | 17 |
234,821 | 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 | 32 |
234,822 | 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 : # 00000000 raise UnicodeDecodeError ( NAME , data , i , i + 1 , "embedded zero-byte not allowed" ) elif d & 0x80 : # 1xxxxxxx if d & 0x40 : # 11xxxxxx if d & 0x20 : # 111xxxxx if d & 0x10 : # 1111xxxx raise UnicodeDecodeError ( NAME , data , i , i + 1 , "invalid encoding character" ) elif d == 0xED : value = 0 for i1 , dm in enumerate ( DECODE_MAP [ 6 ] ) : d1 = next_byte ( it , i , i1 + 1 ) value = dm . apply ( d1 , value , data , i , i1 + 1 ) else : # 1110xxxx value = d & 0x0F for i1 , dm in enumerate ( DECODE_MAP [ 3 ] ) : d1 = next_byte ( it , i , i1 + 1 ) value = dm . apply ( d1 , value , data , i , i1 + 1 ) else : # 110xxxxx value = d & 0x1F for i1 , dm in enumerate ( DECODE_MAP [ 2 ] ) : d1 = next_byte ( it , i , i1 + 1 ) value = dm . apply ( d1 , value , data , i , i1 + 1 ) else : # 10xxxxxx raise UnicodeDecodeError ( NAME , data , i , i + 1 , "misplaced continuation character" ) else : # 0xxxxxxx value = d # noinspection PyCompatibility yield mutf8_unichr ( value ) | This generator processes a sequence of bytes in Modified UTF - 8 encoding and produces a sequence of unicode string characters . | 442 | 23 |
234,823 | 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" : value += u"\uFFFD" length += 1 return value , length | 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 . | 107 | 32 |
234,824 | 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 . | 78 | 19 |
234,825 | def load ( file_object , * transformers , * * kwargs ) : # Read keyword argument ignore_remaining_data = kwargs . get ( "ignore_remaining_data" , False ) marshaller = JavaObjectUnmarshaller ( file_object , kwargs . get ( "use_numpy_arrays" , False ) ) # Add custom transformers first for transformer in transformers : marshaller . add_transformer ( transformer ) marshaller . add_transformer ( DefaultObjectTransformer ( ) ) # Read the file object return marshaller . readObject ( ignore_remaining_data = ignore_remaining_data ) | Deserializes Java primitive data and objects serialized using ObjectOutputStream from a file - like object . | 147 | 21 |
234,826 | def loads ( string , * transformers , * * kwargs ) : # Read keyword argument ignore_remaining_data = kwargs . get ( "ignore_remaining_data" , False ) # Reuse the load method (avoid code duplication) return load ( BytesIO ( string ) , * transformers , ignore_remaining_data = ignore_remaining_data ) | Deserializes Java objects and primitive data serialized using ObjectOutputStream from a string . | 83 | 18 |
234,827 | 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 | 44 | 19 |
234,828 | 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 | 45 | 13 |
234,829 | 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 | 85 | 11 |
234,830 | 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 IOError ( "Unexpected opcode 0x{0:X} -- {1} (at offset 0x{2:X})" . format ( opid , OpCodeDebug . op_id ( opid ) , position ) ) try : handler = self . opmap [ opid ] except KeyError : raise RuntimeError ( "Unknown OpCode in the stream: 0x{0:X} (at offset 0x{1:X})" . format ( opid , position ) ) else : return opid , handler ( ident = ident ) | Reads the next opcode and executes its handler | 232 | 10 |
234,831 | 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 | 52 | 9 |
234,832 | def do_array ( self , parent = None , ident = 0 ) : # TC_ARRAY classDesc newHandle (int)<size> values[size] 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 , ident ) ( size , ) = self . _readStruct ( ">i" ) log_debug ( "size: {0}" . format ( size ) , ident ) type_char = classdesc . name [ 0 ] assert type_char == self . TYPE_ARRAY type_char = classdesc . name [ 1 ] if type_char == self . TYPE_OBJECT or type_char == self . TYPE_ARRAY : for _ in range ( size ) : _ , res = self . _read_and_exec_opcode ( ident = ident + 1 ) log_debug ( "Object value: {0}" . format ( res ) , ident ) array . append ( res ) elif type_char == self . TYPE_BYTE : array = JavaByteArray ( self . object_stream . read ( size ) , classdesc ) elif self . use_numpy_arrays : import numpy array = numpy . fromfile ( self . object_stream , dtype = JavaObjectConstants . NUMPY_TYPE_MAP [ type_char ] , count = size , ) else : for _ in range ( size ) : res = self . _read_value ( type_char , ident ) log_debug ( "Native value: {0}" . format ( repr ( res ) ) , ident ) array . append ( res ) return array | Handles a TC_ARRAY opcode | 417 | 9 |
234,833 | 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 ) return ref | Handles a TC_REFERENCE opcode | 108 | 10 |
234,834 | def do_enum ( self , parent = None , ident = 0 ) : # TC_ENUM classDesc newHandle enumConstantName 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 ) _ , enumConstantName = self . _read_and_exec_opcode ( ident = ident + 1 , expect = ( self . TC_STRING , self . TC_REFERENCE ) ) enum . constant = enumConstantName return enum | Handles a TC_ENUM opcode | 173 | 9 |
234,835 | 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 ) # Convert raw data to str (Python 3 compatibility) src = to_str ( src , "latin-1" ) result = [ ] for i in range ( 0 , len ( src ) , length ) : s = src [ i : i + length ] hexa = " " . join ( "{0:02X}" . format ( ord ( x ) ) for x in s ) printable = s . translate ( FILTER ) result . append ( pattern . format ( i + start_offset , hexa , printable ) ) return "" . join ( result ) | Prepares an hexadecimal dump string | 209 | 9 |
234,836 | 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 . | 91 | 11 |
234,837 | 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 | 86 | 9 |
234,838 | 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!):" ) # Do not use a keyword argument self . object_stream . seek ( - 16 , os . SEEK_CUR ) position = self . object_stream . tell ( ) the_rest = self . object_stream . read ( ) if not ignore_remaining_data and len ( the_rest ) : log_error ( "Warning!!!!: Stream still has {0} bytes left:\n{1}" . format ( len ( the_rest ) , self . _create_hexdump ( the_rest , position ) ) ) log_error ( "=" * 30 ) | Log a deserialization error | 206 | 6 |
234,839 | 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 | 58 | 11 |
234,840 | def writeObject ( self , obj ) : log_debug ( "Writing object of type {0}" . format ( type ( obj ) . __name__ ) ) if isinstance ( obj , JavaArray ) : # Deserialized Java array self . write_array ( obj ) elif isinstance ( obj , JavaEnum ) : # Deserialized Java Enum self . write_enum ( obj ) elif isinstance ( obj , JavaObject ) : # Deserialized Java object self . write_object ( obj ) elif isinstance ( obj , JavaString ) : # Deserialized String self . write_string ( obj ) elif isinstance ( obj , JavaClass ) : # Java class self . write_class ( obj ) elif obj is None : # Null self . write_null ( ) elif type ( obj ) is str : # String value self . write_blockdata ( obj ) else : # Unhandled type raise RuntimeError ( "Object serialization of type {0} is not " "supported." . format ( type ( obj ) ) ) | Appends an object to the serialization stream | 226 | 9 |
234,841 | def _writeString ( self , obj , use_reference = True ) : # TODO: Convert to "modified UTF-8" # http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#modified-utf-8 string = to_bytes ( obj , "utf-8" ) if use_reference and isinstance ( obj , JavaString ) : try : idx = self . references . index ( obj ) except ValueError : # First appearance of the string self . references . append ( obj ) logging . debug ( "*** Adding ref 0x%X for string: %s" , len ( self . references ) - 1 + self . BASE_REFERENCE_IDX , obj , ) self . _writeStruct ( ">H" , 2 , ( len ( string ) , ) ) self . object_stream . write ( string ) else : # Write a reference to the previous type logging . debug ( "*** Reusing ref 0x%X for string: %s" , idx + self . BASE_REFERENCE_IDX , obj , ) self . write_reference ( idx ) else : self . _writeStruct ( ">H" , 2 , ( len ( string ) , ) ) self . object_stream . write ( string ) | Appends a string to the serialization stream | 283 | 9 |
234,842 | def write_string ( self , obj , use_reference = True ) : if use_reference and isinstance ( obj , JavaString ) : try : idx = self . references . index ( obj ) except ValueError : # String is not referenced: let _writeString store it self . _writeStruct ( ">B" , 1 , ( self . TC_STRING , ) ) self . _writeString ( obj , use_reference ) else : # Reuse the referenced string logging . debug ( "*** Reusing ref 0x%X for String: %s" , idx + self . BASE_REFERENCE_IDX , obj , ) self . write_reference ( idx ) else : # Don't use references self . _writeStruct ( ">B" , 1 , ( self . TC_STRING , ) ) self . _writeString ( obj , use_reference ) | Writes a Java string with the TC_STRING type marker | 190 | 13 |
234,843 | def write_enum ( self , obj ) : # FIXME: the output doesn't have the same references as the real # serializable form self . _writeStruct ( ">B" , 1 , ( self . TC_ENUM , ) ) try : idx = self . references . index ( obj ) except ValueError : # New reference self . references . append ( obj ) logging . debug ( "*** Adding ref 0x%X for enum: %s" , len ( self . references ) - 1 + self . BASE_REFERENCE_IDX , obj , ) self . write_classdesc ( obj . get_class ( ) ) else : self . write_reference ( idx ) self . write_string ( obj . constant ) | Writes an Enum value | 158 | 6 |
234,844 | def write_blockdata ( self , obj , parent = None ) : if type ( obj ) is str : # Latin-1: keep bytes as is obj = to_bytes ( obj , "latin-1" ) length = len ( obj ) if length <= 256 : # Small block data # TC_BLOCKDATA (unsigned byte)<size> (byte)[size] self . _writeStruct ( ">B" , 1 , ( self . TC_BLOCKDATA , ) ) self . _writeStruct ( ">B" , 1 , ( length , ) ) else : # Large block data # TC_BLOCKDATALONG (unsigned int)<size> (byte)[size] self . _writeStruct ( ">B" , 1 , ( self . TC_BLOCKDATALONG , ) ) self . _writeStruct ( ">I" , 1 , ( length , ) ) self . object_stream . write ( obj ) | Appends a block of data to the serialization stream | 204 | 11 |
234,845 | def write_object ( self , obj , parent = None ) : # Transform object 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 ) # Add reference self . references . append ( [ ] ) logging . debug ( "*** Adding ref 0x%X for object %s" , len ( self . references ) - 1 + self . BASE_REFERENCE_IDX , obj , ) all_names = collections . deque ( ) all_types = collections . deque ( ) tmpcls = cls while tmpcls : all_names . extendleft ( reversed ( tmpcls . fields_names ) ) all_types . extendleft ( reversed ( tmpcls . fields_types ) ) tmpcls = tmpcls . superclass del tmpcls logging . debug ( "<=> Field names: %s" , all_names ) logging . debug ( "<=> Field types: %s" , all_types ) for field_name , field_type in zip ( all_names , all_types ) : try : logging . debug ( "Writing field %s (%s): %s" , field_name , field_type , getattr ( obj , field_name ) , ) self . _write_value ( field_type , getattr ( obj , field_name ) ) except AttributeError as ex : log_error ( "No attribute {0} for object {1}\nDir: {2}" . format ( ex , repr ( obj ) , dir ( obj ) ) ) raise del all_names , all_types if ( cls . flags & self . SC_SERIALIZABLE and cls . flags & self . SC_WRITE_METHOD or cls . flags & self . SC_EXTERNALIZABLE and cls . flags & self . SC_BLOCK_DATA ) : for annotation in obj . annotations : log_debug ( "Write annotation {0} for {1}" . format ( repr ( annotation ) , repr ( obj ) ) ) if annotation is None : self . write_null ( ) else : self . writeObject ( annotation ) self . _writeStruct ( ">B" , 1 , ( self . TC_ENDBLOCKDATA , ) ) | Writes an object header to the serialization stream | 534 | 10 |
234,846 | def write_class ( self , obj , parent = None ) : self . _writeStruct ( ">B" , 1 , ( self . TC_CLASS , ) ) self . write_classdesc ( obj ) | Writes a class to the stream | 45 | 7 |
234,847 | def write_classdesc ( self , obj , parent = None ) : if obj not in self . references : # Add reference 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 , ) ) self . _writeString ( obj . name ) self . _writeStruct ( ">qB" , 1 , ( obj . serialVersionUID , obj . flags ) ) self . _writeStruct ( ">H" , 1 , ( len ( obj . fields_names ) , ) ) for field_name , field_type in zip ( obj . fields_names , obj . fields_types ) : self . _writeStruct ( ">B" , 1 , ( self . _convert_type_to_char ( field_type ) , ) ) self . _writeString ( field_name ) if field_type [ 0 ] in ( self . TYPE_OBJECT , self . TYPE_ARRAY ) : try : idx = self . references . index ( field_type ) except ValueError : # First appearance of the type self . references . append ( field_type ) logging . debug ( "*** Adding ref 0x%X for field type %s" , len ( self . references ) - 1 + self . BASE_REFERENCE_IDX , field_type , ) self . write_string ( field_type , False ) else : # Write a reference to the previous type logging . debug ( "*** Reusing ref 0x%X for %s (%s)" , idx + self . BASE_REFERENCE_IDX , field_type , field_name , ) self . write_reference ( idx ) self . _writeStruct ( ">B" , 1 , ( self . TC_ENDBLOCKDATA , ) ) if obj . superclass : self . write_classdesc ( obj . superclass ) else : self . write_null ( ) else : # Use reference self . write_reference ( self . references . index ( obj ) ) | Writes a class description | 481 | 5 |
234,848 | 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 ) , ) ) # Add reference self . references . append ( obj ) logging . debug ( "*** Adding ref 0x%X for array []" , len ( self . references ) - 1 + self . BASE_REFERENCE_IDX , ) type_char = classdesc . name [ 0 ] assert type_char == self . TYPE_ARRAY type_char = classdesc . name [ 1 ] if type_char == self . TYPE_OBJECT : for o in obj : self . _write_value ( classdesc . name [ 1 : ] , o ) elif type_char == self . TYPE_ARRAY : for a in obj : self . write_array ( a ) else : log_debug ( "Write array of type %s" % type_char ) for v in obj : log_debug ( "Writing: %s" % v ) self . _write_value ( type_char , v ) | Writes a JavaArray | 267 | 5 |
234,849 | def _write_value ( self , field_type , value ) : if len ( field_type ) > 1 : # We don't need details for arrays and objects 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_CHAR : self . _writeStruct ( ">H" , 1 , ( ord ( value ) , ) ) elif field_type == self . TYPE_SHORT : self . _writeStruct ( ">h" , 1 , ( value , ) ) elif field_type == self . TYPE_INTEGER : self . _writeStruct ( ">i" , 1 , ( value , ) ) elif field_type == self . TYPE_LONG : self . _writeStruct ( ">q" , 1 , ( value , ) ) elif field_type == self . TYPE_FLOAT : self . _writeStruct ( ">f" , 1 , ( value , ) ) elif field_type == self . TYPE_DOUBLE : self . _writeStruct ( ">d" , 1 , ( value , ) ) elif field_type == self . TYPE_OBJECT or field_type == self . TYPE_ARRAY : if value is None : self . write_null ( ) elif isinstance ( value , JavaEnum ) : self . write_enum ( value ) elif isinstance ( value , ( JavaArray , JavaByteArray ) ) : self . write_array ( value ) elif isinstance ( value , JavaObject ) : self . write_object ( value ) elif isinstance ( value , JavaString ) : self . write_string ( value ) elif isinstance ( value , str ) : self . write_blockdata ( value ) else : raise RuntimeError ( "Unknown typecode: {0}" . format ( field_type ) ) else : raise RuntimeError ( "Unknown typecode: {0}" . format ( field_type ) ) | Writes an item of an array | 485 | 7 |
234,850 | 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 ord ( self . TYPE_ARRAY ) raise RuntimeError ( "Typecode {0} ({1}) isn't supported." . format ( type_char , typecode ) ) | Converts the given type code to an int | 144 | 9 |
234,851 | def create ( self , classdesc , unmarshaller = None ) : # type: (JavaClass, JavaObjectUnmarshaller) -> JavaObject try : mapped_type = self . TYPE_MAPPER [ classdesc . name ] except KeyError : # Return a JavaObject by default return JavaObject ( ) else : log_debug ( "---" ) log_debug ( classdesc . name ) log_debug ( "---" ) java_object = mapped_type ( unmarshaller ) log_debug ( ">>> java_object: {0}" . format ( java_object ) ) return java_object | Transforms a deserialized Java object into a Python object | 133 | 12 |
234,852 | 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 ( coeff ) ) ) data , coeff = PMAT ( data , atype ) , PMAT ( coeff , atype ) probs = mnl_probs ( data , coeff , numalts ) if returnprobs : return np . transpose ( probs . get_mat ( ) ) # convert to cpu from here on - gpu doesn't currently support these ops if probs . typ == 'cuda' : probs = PMAT ( probs . get_mat ( ) ) probs = probs . cumsum ( axis = 0 ) r = pmat . random ( probs . size ( ) // numalts ) choices = probs . subtract ( r , inplace = True ) . firstpositive ( axis = 0 ) logger . debug ( 'finish: MNL simulation' ) return choices . get_mat ( ) | Get the probabilities for each chooser choosing between numalts alternatives . | 292 | 14 |
234,853 | 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 = data . shape [ 0 ] // numalts if chosen is None : chosen = np . ones ( ( numobs , numalts ) ) # used for latent classes data = np . transpose ( data ) chosen = np . transpose ( chosen ) data , chosen = PMAT ( data , atype ) , PMAT ( chosen , atype ) if weights is not None : weights = PMAT ( np . transpose ( weights ) , atype ) if beta is None : beta = np . zeros ( numvars ) bounds = [ coeffrange ] * numvars with log_start_finish ( 'scipy optimization for MNL fit' , logger ) : args = ( data , chosen , numalts , weights , lcgrad ) bfgs_result = scipy . optimize . fmin_l_bfgs_b ( mnl_loglik , beta , args = args , fprime = None , factr = 10 , approx_grad = False , bounds = bounds ) if bfgs_result [ 2 ] [ 'warnflag' ] > 0 : logger . warn ( "mnl did not converge correctly: %s" , bfgs_result ) beta = bfgs_result [ 0 ] stderr = mnl_loglik ( beta , data , chosen , numalts , weights , stderr = 1 , lcgrad = lcgrad ) l0beta = np . zeros ( numvars ) l0 = - 1 * mnl_loglik ( l0beta , * args ) [ 0 ] l1 = - 1 * mnl_loglik ( beta , * args ) [ 0 ] log_likelihood = { 'null' : float ( l0 [ 0 ] [ 0 ] ) , 'convergence' : float ( l1 [ 0 ] [ 0 ] ) , 'ratio' : float ( ( 1 - ( l1 / l0 ) ) [ 0 ] [ 0 ] ) } fit_parameters = pd . DataFrame ( { 'Coefficient' : beta , 'Std. Error' : stderr , 'T-Score' : beta / stderr } ) logger . debug ( 'finish: MNL fit' ) return log_likelihood , fit_parameters | Calculate coefficients of the MNL model . | 600 | 10 |
234,854 | 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' ) , choosers_fit_filters = cfg . get ( 'choosers_fit_filters' , None ) , choosers_predict_filters = cfg . get ( 'choosers_predict_filters' , None ) , alts_fit_filters = cfg . get ( 'alts_fit_filters' , None ) , alts_predict_filters = cfg . get ( 'alts_predict_filters' , None ) , interaction_predict_filters = cfg . get ( 'interaction_predict_filters' , None ) , estimation_sample_size = cfg . get ( 'estimation_sample_size' , None ) , prediction_sample_size = cfg . get ( 'prediction_sample_size' , None ) , choice_column = cfg . get ( 'choice_column' , None ) , name = cfg . get ( 'name' , None ) ) if cfg . get ( 'log_likelihoods' , None ) : model . log_likelihoods = cfg [ 'log_likelihoods' ] if cfg . get ( 'fit_parameters' , None ) : model . fit_parameters = pd . DataFrame ( cfg [ 'fit_parameters' ] ) logger . debug ( 'loaded LCM model {} from YAML' . format ( model . name ) ) return model | Create a DiscreteChoiceModel instance from a saved YAML configuration . Arguments are mutally exclusive . | 437 | 22 |
234,855 | 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 . estimation_sample_size : choosers = choosers . loc [ np . random . choice ( choosers . index , min ( self . estimation_sample_size , len ( choosers ) ) , replace = False ) ] current_choice = current_choice . loc [ choosers . index ] _ , merged , chosen = interaction . mnl_interaction_dataset ( choosers , alternatives , self . sample_size , current_choice ) model_design = dmatrix ( self . str_model_expression , data = merged , return_type = 'dataframe' ) if len ( merged ) != model_design . as_matrix ( ) . shape [ 0 ] : 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.' ) self . log_likelihoods , self . fit_parameters = mnl . mnl_estimate ( model_design . as_matrix ( ) , chosen , self . sample_size ) self . fit_parameters . index = model_design . columns logger . debug ( 'finish: fit LCM model {}' . format ( self . name ) ) return self . log_likelihoods | Fit and save model parameters based on given data . | 367 | 10 |
234,856 | 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_sample_size is not None : sample_size = self . prediction_sample_size else : sample_size = len ( alternatives ) if self . probability_mode == 'single_chooser' : _ , merged , _ = interaction . mnl_interaction_dataset ( choosers . head ( 1 ) , alternatives , sample_size ) elif self . probability_mode == 'full_product' : _ , merged , _ = interaction . mnl_interaction_dataset ( choosers , alternatives , sample_size ) else : raise ValueError ( 'Unrecognized probability_mode option: {}' . format ( self . probability_mode ) ) merged = util . apply_filter_query ( merged , self . interaction_predict_filters ) model_design = dmatrix ( self . str_model_expression , data = merged , return_type = 'dataframe' ) if len ( merged ) != model_design . as_matrix ( ) . shape [ 0 ] : raise ModelEvaluationError ( 'Simulated data does not have the same length as input. ' 'This suggests there are null values in one or more of ' 'the input columns.' ) # get the order of the coefficients in the same order as the # columns in the design matrix coeffs = [ self . fit_parameters [ 'Coefficient' ] [ x ] for x in model_design . columns ] # probabilities are returned from mnl_simulate as a 2d array # with choosers along rows and alternatives along columns if self . probability_mode == 'single_chooser' : numalts = len ( merged ) else : numalts = sample_size probabilities = mnl . mnl_simulate ( model_design . as_matrix ( ) , coeffs , numalts = numalts , returnprobs = True ) # want to turn probabilities into a Series with a MultiIndex # of chooser IDs and alternative IDs. # indexing by chooser ID will get you the probabilities # across alternatives for that chooser mi = pd . MultiIndex . from_arrays ( [ merged [ 'join_index' ] . values , merged . index . values ] , names = ( 'chooser_id' , 'alternative_id' ) ) probabilities = pd . Series ( probabilities . flatten ( ) , index = mi ) logger . debug ( 'finish: calculate probabilities for LCM model {}' . format ( self . name ) ) return probabilities | Returns the probabilities for a set of choosers to choose from among a set of alternatives . | 619 | 19 |
234,857 | 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 ) # groupby the the alternatives ID and sum if self . probability_mode == 'single_chooser' : return ( normalize ( probs ) * len ( choosers ) ) . reset_index ( level = 0 , drop = True ) elif self . probability_mode == 'full_product' : return probs . groupby ( level = 0 ) . apply ( normalize ) . groupby ( level = 1 ) . sum ( ) else : raise ValueError ( 'Unrecognized probability_mode option: {}' . format ( self . probability_mode ) ) | Calculate total probability associated with each alternative . | 195 | 10 |
234,858 | 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 ) == 0 : return pd . Series ( index = choosers . index ) probabilities = self . probabilities ( choosers , alternatives , filter_tables = False ) if debug : self . sim_pdf = probabilities if self . choice_mode == 'aggregate' : choices = unit_choice ( choosers . index . values , probabilities . index . get_level_values ( 'alternative_id' ) . values , probabilities . values ) elif self . choice_mode == 'individual' : def mkchoice ( probs ) : probs . reset_index ( 0 , drop = True , inplace = True ) return np . random . choice ( probs . index . values , p = probs . values / probs . sum ( ) ) choices = probabilities . groupby ( level = 'chooser_id' , sort = False ) . apply ( mkchoice ) else : raise ValueError ( 'Unrecognized choice_mode option: {}' . format ( self . choice_mode ) ) logger . debug ( 'finish: predict LCM model {}' . format ( self . name ) ) return choices | Choose from among alternatives for a group of agents . | 327 | 10 |
234,859 | 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 , 'choosers_predict_filters' : self . choosers_predict_filters , 'alts_fit_filters' : self . alts_fit_filters , 'alts_predict_filters' : self . alts_predict_filters , 'interaction_predict_filters' : self . interaction_predict_filters , 'estimation_sample_size' : self . estimation_sample_size , 'prediction_sample_size' : self . prediction_sample_size , 'choice_column' : self . choice_column , 'fitted' : self . fitted , 'log_likelihoods' : self . log_likelihoods , 'fit_parameters' : ( yamlio . frame_to_yaml_safe ( self . fit_parameters ) if self . fitted else None ) } | Return a dict respresentation of an MNLDiscreteChoiceModel instance . | 295 | 16 |
234,860 | 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 . | 73 | 14 |
234,861 | 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 . | 64 | 28 |
234,862 | 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 ) else : msg = 'predict_from_cfg requires a configuration via the cfgname or cfg arguments' logger . error ( msg ) raise ValueError ( msg ) if len ( alternatives ) > len ( choosers ) * alternative_ratio : logger . info ( ( "Alternative ratio exceeded: %d alternatives " "and only %d choosers" ) % ( len ( alternatives ) , len ( choosers ) ) ) idxes = np . random . choice ( alternatives . index , size = int ( len ( choosers ) * alternative_ratio ) , replace = False ) alternatives = alternatives . loc [ idxes ] logger . info ( " after sampling %d alternatives are available\n" % len ( alternatives ) ) new_units = lcm . predict ( choosers , alternatives , debug = debug ) print ( "Assigned %d choosers to new units" % len ( new_units . dropna ( ) ) ) logger . debug ( 'finish: predict from configuration {}' . format ( cfgname ) ) return new_units , lcm | Simulate choices for the specified choosers | 342 | 9 |
234,863 | 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 = None , prediction_sample_size = None , choice_column = None ) : logger . debug ( 'adding model {} to LCM group {}' . format ( name , self . name ) ) self . models [ name ] = MNLDiscreteChoiceModel ( model_expression , sample_size , probability_mode , choice_mode , choosers_fit_filters , choosers_predict_filters , alts_fit_filters , alts_predict_filters , interaction_predict_filters , estimation_sample_size , prediction_sample_size , choice_column , name ) | Add a model by passing parameters through to MNLDiscreteChoiceModel . | 232 | 15 |
234,864 | 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 ( ch ) , pd . concat ( alts ) | Filter choosers and alternatives for fitting . This is done by filtering each submodel and concatenating the results . | 111 | 24 |
234,865 | 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 . | 82 | 17 |
234,866 | 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 . | 31 | 10 |
234,867 | 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 ( self . models [ name ] . summed_probabilities ( df , alternatives ) ) add = tz . curry ( pd . Series . add , fill_value = 0 ) probs = tz . reduce ( add , probs ) logger . debug ( 'finish: calculate summed probabilities in LCM group {}' . format ( self . name ) ) return probs | Returns the sum of probabilities for alternatives across all chooser segments . | 170 | 13 |
234,868 | 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 [ 'choosers_fit_filters' ] , cfg [ 'choosers_predict_filters' ] , cfg [ 'alts_fit_filters' ] , cfg [ 'alts_predict_filters' ] , cfg [ 'interaction_predict_filters' ] , cfg [ 'estimation_sample_size' ] , cfg [ 'prediction_sample_size' ] , cfg [ 'choice_column' ] , default_model_expr , cfg [ 'remove_alts' ] , 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 [ 'sample_size' ] = cfg [ 'sample_size' ] m [ 'probability_mode' ] = cfg [ 'probability_mode' ] m [ 'choice_mode' ] = cfg [ 'choice_mode' ] m [ 'choosers_fit_filters' ] = None m [ 'choosers_predict_filters' ] = None m [ 'alts_fit_filters' ] = None m [ 'alts_predict_filters' ] = None m [ 'interaction_predict_filters' ] = cfg [ 'interaction_predict_filters' ] m [ 'estimation_sample_size' ] = cfg [ 'estimation_sample_size' ] m [ 'prediction_sample_size' ] = cfg [ 'prediction_sample_size' ] m [ 'choice_column' ] = cfg [ 'choice_column' ] model = MNLDiscreteChoiceModel . from_yaml ( yamlio . convert_to_yaml ( m , None ) ) seg . _group . add_model ( model ) logger . debug ( 'loaded segmented LCM model {} from YAML' . format ( seg . name ) ) return seg | Create a SegmentedMNLDiscreteChoiceModel instance from a saved YAML configuration . Arguments are mutally exclusive . | 602 | 27 |
234,869 | 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_expression = self . default_model_expr # we'll take care of some of the filtering this side before # segmentation self . _group . add_model_from_params ( name = name , model_expression = model_expression , sample_size = self . sample_size , probability_mode = self . probability_mode , choice_mode = self . choice_mode , choosers_fit_filters = None , choosers_predict_filters = None , alts_fit_filters = None , alts_predict_filters = None , interaction_predict_filters = self . interaction_predict_filters , estimation_sample_size = self . estimation_sample_size , choice_column = self . choice_column ) | Add a new segment with its own model expression . | 247 | 10 |
234,870 | 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 ( ) # 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 : self . add_segment ( x ) results = self . _group . fit ( choosers , alternatives , current_choice ) logger . debug ( 'finish: fit models in segmented LCM {}' . format ( self . name ) ) return results | 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 . | 228 | 34 |
234,871 | 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 . | 69 | 12 |
234,872 | 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 attrib_ext == '.lf4' : attrib_data = np . fromfile ( attrib , np . float32 ) table [ attrib_name ] = attrib_data elif attrib_ext == '.li2' : attrib_data = np . fromfile ( attrib , np . int16 ) table [ attrib_name ] = attrib_data elif attrib_ext == '.li4' : attrib_data = np . fromfile ( attrib , np . int32 ) table [ attrib_name ] = attrib_data elif attrib_ext == '.li8' : attrib_data = np . fromfile ( attrib , np . int64 ) table [ attrib_name ] = attrib_data elif attrib_ext == '.ib1' : attrib_data = np . fromfile ( attrib , np . bool_ ) table [ attrib_name ] = attrib_data elif attrib_ext . startswith ( '.iS' ) : length_string = int ( attrib_ext [ 3 : ] ) attrib_data = np . fromfile ( attrib , ( 'a' + str ( length_string ) ) ) table [ attrib_name ] = attrib_data else : print ( 'Array {} is not a recognized data type' . format ( attrib ) ) df = pd . DataFrame ( table ) return df | Convert a directory of binary array data files to a Pandas DataFrame . | 423 | 16 |
234,873 | 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 found matching known data.' ) store = pd . HDFStore ( hdf_name , mode = 'w' , complevel = complevel , complib = complib ) for dirpath in dirs : dirname = os . path . basename ( dirpath ) print ( dirname ) df = cache_to_df ( dirpath ) if dirname == 'travel_data' : keys = [ 'from_zone_id' , 'to_zone_id' ] elif dirname == 'annual_employment_control_totals' : keys = [ 'sector_id' , 'year' , 'home_based_status' ] elif dirname == 'annual_job_relocation_rates' : keys = [ 'sector_id' ] elif dirname == 'annual_household_control_totals' : keys = [ 'year' ] elif dirname == 'annual_household_relocation_rates' : keys = [ 'age_of_head_max' , 'age_of_head_min' , 'income_min' , 'income_max' ] elif dirname == 'building_sqft_per_job' : keys = [ 'zone_id' , 'building_type_id' ] elif dirname == 'counties' : keys = [ 'county_id' ] elif dirname == 'development_event_history' : keys = [ 'building_id' ] elif dirname == 'target_vacancies' : keys = [ 'building_type_id' , 'year' ] else : keys = [ dirname [ : - 1 ] + '_id' ] if dirname != 'annual_household_relocation_rates' : df = df . set_index ( keys ) for colname in df . columns : if df [ colname ] . dtype == np . float64 : df [ colname ] = df [ colname ] . astype ( np . float32 ) elif df [ colname ] . dtype == np . int64 : df [ colname ] = df [ colname ] . astype ( np . int32 ) else : df [ colname ] = df [ colname ] df . info ( ) print ( os . linesep ) store . put ( dirname , df ) store . close ( ) | Convert nested set of directories to | 617 | 7 |
234,874 | 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 num | Get a run number for this execution of the model system for identifying the output hdf5 files ) . | 122 | 21 |
234,875 | 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 ) . attr . apply ( agg ) | Compute a zone - based accessibility query using the urbansim format travel data dataframe . | 108 | 20 |
234,876 | def reindex ( series1 , series2 ) : # turns out the merge is much faster than the .loc below 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 . | 87 | 51 |
234,877 | 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 . | 64 | 22 |
234,878 | 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 . | 58 | 21 |
234,879 | def pandasdfsummarytojson ( df , ndigits = 3 ) : df = df . transpose ( ) return { k : _pandassummarytojson ( v , ndigits ) for k , v in df . iterrows ( ) } | Convert the result of a | 56 | 6 |
234,880 | 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 ( ) ) ) if foundcols != columns : raise RuntimeError ( 'Not all required columns were found. ' 'Missing: {}' . format ( list ( columns - foundcols ) ) ) return colmap | Take a list of tables and a list of column names and resolve which columns come from which table . | 137 | 20 |
234,881 | 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 . | 62 | 22 |
234,882 | def accounting_sample_replace ( total , data , accounting_column , prob_column = None , max_iterations = 50 ) : # check for probabilities p = get_probs ( data , prob_column ) # determine avg number of accounting items per sample (e.g. persons per household) per_sample = data [ accounting_column ] . sum ( ) / ( 1.0 * len ( data . index . values ) ) curr_total = 0 remaining = total sample_rows = pd . DataFrame ( ) closest = None closest_remain = total matched = False for i in range ( 0 , max_iterations ) : # stop if we've hit the control if remaining == 0 : matched = True break # if sampling with probabilities, re-caclc the # of items per sample # after the initial sample, this way the sample size reflects the probabilities if p is not None and i == 1 : per_sample = sample_rows [ accounting_column ] . sum ( ) / ( 1.0 * len ( sample_rows ) ) # update the sample num_samples = int ( math . ceil ( math . fabs ( remaining ) / per_sample ) ) if remaining > 0 : # we're short, add to the sample curr_ids = np . random . choice ( data . index . values , num_samples , p = p ) sample_rows = pd . concat ( [ sample_rows , data . loc [ curr_ids ] ] ) else : # we've overshot, remove from existing samples (FIFO) sample_rows = sample_rows . iloc [ num_samples : ] . copy ( ) # update the total and check for the closest result curr_total = sample_rows [ accounting_column ] . sum ( ) remaining = total - curr_total if abs ( remaining ) < closest_remain : closest_remain = abs ( remaining ) closest = sample_rows return closest , matched | Sample rows with accounting with replacement . | 422 | 7 |
234,883 | def accounting_sample_no_replace ( total , data , accounting_column , prob_column = None ) : # make sure this is even feasible if total > data [ accounting_column ] . sum ( ) : raise ValueError ( 'Control total exceeds the available samples' ) # check for probabilities p = get_probs ( data , prob_column ) # shuffle the rows if p is None : # random shuffle shuff_idx = np . random . permutation ( data . index . values ) else : # weighted shuffle ran_p = pd . Series ( np . power ( np . random . rand ( len ( p ) ) , 1.0 / p ) , index = data . index ) ran_p . sort_values ( ascending = False ) shuff_idx = ran_p . index . values # get the initial sample shuffle = data . loc [ shuff_idx ] csum = np . cumsum ( shuffle [ accounting_column ] . values ) pos = np . searchsorted ( csum , total , 'right' ) sample = shuffle . iloc [ : pos ] # refine the sample sample_idx = sample . index . values sample_total = sample [ accounting_column ] . sum ( ) shortage = total - sample_total matched = False for idx , row in shuffle . iloc [ pos : ] . iterrows ( ) : if shortage == 0 : # we've matached matched = True break # add the current element if it doesnt exceed the total cnt = row [ accounting_column ] if cnt <= shortage : sample_idx = np . append ( sample_idx , idx ) shortage -= cnt return shuffle . loc [ sample_idx ] . copy ( ) , matched | Samples rows with accounting without replacement . | 368 | 8 |
234,884 | 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 . array ( [ self . forms [ k ] . get ( use , 0.0 ) for use in self . uses ] ) # normalize if not already self . forms [ k ] /= self . forms [ k ] . sum ( ) self . res_ratios [ k ] = pd . Series ( self . forms [ k ] ) [ self . residential_uses ] . sum ( ) self . costs = np . transpose ( np . array ( [ self . costs [ use ] for use in self . uses ] ) ) | convert lists and dictionaries that are useful for users to np vectors that are usable by machines | 210 | 19 |
234,885 | def _building_cost ( self , use_mix , stories ) : c = self . config # stories to heights heights = stories * c . height_per_story # cost index for this height costs = np . searchsorted ( c . heights_for_costs , heights ) # this will get set to nan later costs [ np . isnan ( heights ) ] = 0 # compute cost with matrix multiply costs = np . dot ( np . squeeze ( c . costs [ costs . astype ( 'int32' ) ] ) , use_mix ) # some heights aren't allowed - cost should be nan costs [ np . isnan ( stories ) . flatten ( ) ] = np . nan return costs . flatten ( ) | Generate building cost for a set of buildings | 154 | 9 |
234,886 | 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 ( columns = "parking_config" , values = "max_profit" ) . idxmax ( axis = 1 ) . to_frame ( "parking_config" ) df . set_index ( [ "parking_config" ] , append = True , inplace = True ) max_profit_ind . set_index ( [ "parking_config" ] , append = True , inplace = True ) # get the max_profit idx return df . loc [ max_profit_ind . index ] . reset_index ( 1 ) | This function does the developer model lookups for all the actual input data . | 215 | 15 |
234,887 | 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 : logger . debug ( "\n" + str ( key ) + "\n" ) logger . debug ( self . get_ave_cost_sqft ( form , "surface" ) ) keys = c . forms . keys ( ) keys = sorted ( keys ) cnt = 1 share = None fig = plt . figure ( figsize = ( 12 , 3 * len ( keys ) ) ) fig . suptitle ( 'Profitable rents by use' , fontsize = 40 ) for name in keys : sumdf = None for parking_config in c . parking_configs : df = df_d [ ( name , parking_config ) ] if sumdf is None : sumdf = pd . DataFrame ( df [ 'far' ] ) sumdf [ parking_config ] = df [ 'ave_cost_sqft' ] far = sumdf [ 'far' ] del sumdf [ 'far' ] if share is None : share = plt . subplot ( len ( keys ) / 2 , 2 , cnt ) else : plt . subplot ( len ( keys ) / 2 , 2 , cnt , sharex = share , sharey = share ) handles = plt . plot ( far , sumdf ) plt . ylabel ( 'even_rent' ) plt . xlabel ( 'FAR' ) plt . title ( 'Rents for use type %s' % name ) plt . legend ( handles , c . parking_configs , loc = 'lower right' , title = 'Parking type' ) cnt += 1 plt . savefig ( 'even_rents.png' , bbox_inches = 0 ) | this code creates the debugging plots to understand the behavior of the hypothetical building model | 460 | 15 |
234,888 | 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 = sample_rows ( nrows , data , accounting_column = accounting_column ) copied_index = new_rows . index added_index = pd . Index ( np . arange ( starting_index , starting_index + len ( new_rows . index ) , dtype = np . int ) ) new_rows . index = added_index logger . debug ( 'finish: added {} rows in transition model' . format ( len ( new_rows ) ) ) return pd . concat ( [ data , new_rows ] ) , added_index , copied_index | Add rows to data table according to a given nrows . New rows will have their IDs set to NaN . | 214 | 23 |
234,889 | def remove_rows ( data , nrows , accounting_column = None ) : logger . debug ( 'start: removing {} rows in transition model' . format ( nrows ) ) nrows = abs ( nrows ) # in case a negative number came in unit_check = data [ accounting_column ] . sum ( ) if accounting_column else len ( data ) if nrows == 0 : return data , _empty_index ( ) elif nrows > unit_check : raise ValueError ( 'Number of rows to remove exceeds number of records in table.' ) remove_rows = sample_rows ( nrows , data , accounting_column = accounting_column , replace = False ) remove_index = remove_rows . index logger . debug ( 'finish: removed {} rows in transition model' . format ( nrows ) ) return data . loc [ data . index . difference ( remove_index ) ] , remove_index | Remove a random nrows number of rows from a table . | 195 | 12 |
234,890 | def _update_linked_table ( table , col_name , added , copied , removed ) : logger . debug ( 'start: update linked table after transition' ) # handle removals table = table . loc [ ~ table [ col_name ] . isin ( set ( removed ) ) ] if ( added is None or len ( added ) == 0 ) : return table # map new IDs to the IDs from which they were copied id_map = pd . concat ( [ pd . Series ( copied , name = col_name ) , pd . Series ( added , name = 'temp_id' ) ] , axis = 1 ) # join to linked table and assign new id new_rows = id_map . merge ( table , on = col_name ) new_rows . drop ( col_name , axis = 1 , inplace = True ) new_rows . rename ( columns = { 'temp_id' : col_name } , inplace = True ) # index the new rows starting_index = table . index . values . max ( ) + 1 new_rows . index = np . arange ( starting_index , starting_index + len ( new_rows ) , dtype = np . int ) logger . debug ( 'finish: update linked table after transition' ) return pd . concat ( [ table , new_rows ] ) | Copy and update rows in a table that has a column referencing another table that has had rows added via copying . | 291 | 22 |
234,891 | 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 ) in linked_tables . items ( ) : logger . debug ( 'updating linked table {}' . format ( table_name ) ) updated_links [ table_name ] = _update_linked_table ( table , col , added , copied , removed ) logger . debug ( 'finish: transition' ) return updated , added , updated_links | Add or remove rows from a table based on population targets . | 164 | 12 |
234,892 | 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 . | 91 | 26 |
234,893 | 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 . | 87 | 28 |
234,894 | 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' , 'estimation_sample_size' , 'prediction_sample_size' , 'model_expression' , 'ytransform' , 'min_segment_size' , 'default_config' , 'models' , 'coefficients' , 'fitted' ] s = [ ] for key in order : if key not in cfg : continue s . append ( yaml . dump ( { key : cfg [ key ] } , default_flow_style = False , indent = 4 ) ) for key in cfg : if key in order : continue s . append ( yaml . dump ( { key : cfg [ key ] } , default_flow_style = False , indent = 4 ) ) return '\n' . join ( s ) | Convert a dictionary to a YAML string with preferential ordering for some keys . Converted string is meant to be fairly human readable . | 282 | 27 |
234,895 | 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 . | 108 | 27 |
234,896 | 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 . | 47 | 8 |
234,897 | 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 . | 39 | 12 |
234,898 | 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 . DataFrame ( columns = COLS + col_names ) return pd . DataFrame ( rows , columns = COLS + col_names ) | Return transactions as a pandas DataFrame . | 131 | 9 |
234,899 | 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 . | 79 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.