idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
244,100
def handle_path ( backend_inst , path , * * kwargs ) : if callable ( getattr ( backend_inst , 'handle_path' , None ) ) : # Prefer handle_path() if present. LOGGER . debug ( "using handle_path" ) return backend_inst . handle_path ( path ) elif callable ( getattr ( backend_inst , 'handle_fobj' , None ) ) : # Fallback to handle_fobj(). No warning here since the performance hit # is minimal. LOGGER . debug ( "using handle_fobj" ) with open ( path , 'rb' ) as f : return backend_inst . handle_fobj ( f ) else : raise AssertionError ( 'Backend %s has no _get functions' % backend_inst . __name__ )
Handle a path .
180
4
244,101
def handle_fobj ( backend , f , * * kwargs ) : if not is_binary ( f ) : raise AssertionError ( 'File must be opened in binary mode.' ) if callable ( getattr ( backend , 'handle_fobj' , None ) ) : # Prefer handle_fobj() if present. LOGGER . debug ( "using handle_fobj" ) return backend . handle_fobj ( f ) elif callable ( getattr ( backend , 'handle_path' , None ) ) : # Fallback to handle_path(). Warn user since this is potentially # expensive. LOGGER . debug ( "using handle_path" ) LOGGER . warning ( "Using disk, %r backend does not provide `handle_fobj()`" , backend ) ext = '' if 'ext' in kwargs : ext = '.' + kwargs [ 'ext' ] with fobj_to_tempfile ( f , suffix = ext ) as fname : return backend . handle_path ( fname , * * kwargs ) else : raise AssertionError ( 'Backend %s has no _get functions' % backend . __name__ )
Handle a file - like object .
257
7
244,102
def backend_from_mime ( mime ) : try : mod_name = MIMETYPE_TO_BACKENDS [ mime ] except KeyError : msg = "No handler for %r, defaulting to %r" % ( mime , DEFAULT_MIME ) if 'FULLTEXT_TESTING' in os . environ : warn ( msg ) else : LOGGER . debug ( msg ) mod_name = MIMETYPE_TO_BACKENDS [ DEFAULT_MIME ] mod = import_mod ( mod_name ) return mod
Determine backend module object from a mime string .
126
12
244,103
def backend_from_fname ( name ) : ext = splitext ( name ) [ 1 ] try : mime = EXTS_TO_MIMETYPES [ ext ] except KeyError : try : f = open ( name , 'rb' ) except IOError as e : # The file may not exist, we are being asked to determine it's type # from it's name. Other errors are unexpected. if e . errno != errno . ENOENT : raise # We will have to fall back upon the default backend. msg = "No handler for %r, defaulting to %r" % ( ext , DEFAULT_MIME ) if 'FULLTEXT_TESTING' in os . environ : warn ( msg ) else : LOGGER . debug ( msg ) mod_name = MIMETYPE_TO_BACKENDS [ DEFAULT_MIME ] else : with f : return backend_from_fobj ( f ) else : mod_name = MIMETYPE_TO_BACKENDS [ mime ] mod = import_mod ( mod_name ) return mod
Determine backend module object from a file name .
239
11
244,104
def backend_from_fobj ( f ) : if magic is None : warn ( "magic lib is not installed; assuming mime type %r" % ( DEFAULT_MIME ) ) return backend_from_mime ( DEFAULT_MIME ) else : offset = f . tell ( ) try : f . seek ( 0 ) chunk = f . read ( MAGIC_BUFFER_SIZE ) mime = magic . from_buffer ( chunk , mime = True ) return backend_from_mime ( mime ) finally : f . seek ( offset )
Determine backend module object from a file object .
121
11
244,105
def backend_inst_from_mod ( mod , encoding , encoding_errors , kwargs ) : kw = dict ( encoding = encoding , encoding_errors = encoding_errors , kwargs = kwargs ) try : klass = getattr ( mod , "Backend" ) except AttributeError : raise AttributeError ( "%r mod does not define any backend class" % mod ) inst = klass ( * * kw ) try : inst . check ( title = False ) except Exception as err : bin_mod = "fulltext.backends.__bin" warn ( "can't use %r due to %r; use %r backend instead" % ( mod , str ( err ) , bin_mod ) ) inst = import_mod ( bin_mod ) . Backend ( * * kw ) inst . check ( title = False ) LOGGER . debug ( "using %r" % inst ) return inst
Given a mod and a set of opts return an instantiated Backend class .
199
17
244,106
def get ( path_or_file , default = SENTINAL , mime = None , name = None , backend = None , encoding = None , encoding_errors = None , kwargs = None , _wtitle = False ) : try : text , title = _get ( path_or_file , default = default , mime = mime , name = name , backend = backend , kwargs = kwargs , encoding = encoding , encoding_errors = encoding_errors , _wtitle = _wtitle ) if _wtitle : return ( text , title ) else : return text except Exception as e : if default is not SENTINAL : LOGGER . exception ( e ) return default raise
Get document full text .
150
5
244,107
def hilite ( s , ok = True , bold = False ) : if not term_supports_colors ( ) : return s attr = [ ] if ok is None : # no color pass elif ok : # green attr . append ( '32' ) else : # red attr . append ( '31' ) if bold : attr . append ( '1' ) return '\x1b[%sm%s\x1b[0m' % ( ';' . join ( attr ) , s )
Return an highlighted version of string .
117
7
244,108
def fobj_to_tempfile ( f , suffix = '' ) : with tempfile . NamedTemporaryFile ( dir = TEMPDIR , suffix = suffix , delete = False ) as t : shutil . copyfileobj ( f , t ) try : yield t . name finally : os . remove ( t . name )
Context manager which copies a file object to disk and return its name . When done the file is deleted .
70
21
244,109
def rm ( pattern ) : paths = glob . glob ( pattern ) for path in paths : if path . startswith ( '.git/' ) : continue if os . path . isdir ( path ) : def onerror ( fun , path , excinfo ) : exc = excinfo [ 1 ] if exc . errno != errno . ENOENT : raise safe_print ( "rmdir -f %s" % path ) shutil . rmtree ( path , onerror = onerror ) else : safe_print ( "rm %s" % path ) os . remove ( path )
Recursively remove a file or dir by pattern .
128
11
244,110
def help ( ) : safe_print ( 'Run "make [-p <PYTHON>] <target>" where <target> is one of:' ) for name in sorted ( _cmds ) : safe_print ( " %-20s %s" % ( name . replace ( '_' , '-' ) , _cmds [ name ] or '' ) ) sys . exit ( 1 )
Print this help
85
3
244,111
def clean ( ) : rm ( "$testfn*" ) rm ( "*.bak" ) rm ( "*.core" ) rm ( "*.egg-info" ) rm ( "*.orig" ) rm ( "*.pyc" ) rm ( "*.pyd" ) rm ( "*.pyo" ) rm ( "*.rej" ) rm ( "*.so" ) rm ( "*.~" ) rm ( "*__pycache__" ) rm ( ".coverage" ) rm ( ".tox" ) rm ( ".coverage" ) rm ( "build" ) rm ( "dist" ) rm ( "docs/_build" ) rm ( "htmlcov" ) rm ( "tmp" ) rm ( "venv" )
Deletes dev files
162
4
244,112
def lint ( ) : py_files = subprocess . check_output ( "git ls-files" ) if PY3 : py_files = py_files . decode ( ) py_files = [ x for x in py_files . split ( ) if x . endswith ( '.py' ) ] py_files = ' ' . join ( py_files ) sh ( "%s -m flake8 %s" % ( PYTHON , py_files ) , nolog = True )
Run flake8 against all py files
110
8
244,113
def coverage ( ) : # Note: coverage options are controlled by .coveragerc file install ( ) test_setup ( ) sh ( "%s -m coverage run %s" % ( PYTHON , TEST_SCRIPT ) ) sh ( "%s -m coverage report" % PYTHON ) sh ( "%s -m coverage html" % PYTHON ) sh ( "%s -m webbrowser -t htmlcov/index.html" % PYTHON )
Run coverage tests .
104
4
244,114
def venv ( ) : try : import virtualenv # NOQA except ImportError : sh ( "%s -m pip install virtualenv" % PYTHON ) if not os . path . isdir ( "venv" ) : sh ( "%s -m virtualenv venv" % PYTHON ) sh ( "venv\\Scripts\\pip install -r %s" % ( REQUIREMENTS_TXT ) )
Install venv + deps .
95
7
244,115
def compute_header_hmac_hash ( context ) : return hmac . new ( hashlib . sha512 ( b'\xff' * 8 + hashlib . sha512 ( context . _ . header . value . dynamic_header . master_seed . data + context . transformed_key + b'\x01' ) . digest ( ) ) . digest ( ) , context . _ . header . data , hashlib . sha256 ) . digest ( )
Compute HMAC - SHA256 hash of header . Used to prevent header tampering .
101
17
244,116
def compute_payload_block_hash ( this ) : return hmac . new ( hashlib . sha512 ( struct . pack ( '<Q' , this . _index ) + hashlib . sha512 ( this . _ . _ . header . value . dynamic_header . master_seed . data + this . _ . transformed_key + b'\x01' ) . digest ( ) ) . digest ( ) , struct . pack ( '<Q' , this . _index ) + struct . pack ( '<I' , len ( this . block_data ) ) + this . block_data , hashlib . sha256 ) . digest ( )
Compute hash of each payload block . Used to prevent payload corruption and tampering .
144
16
244,117
def decrypt ( self , block ) : if len ( block ) % 16 : raise ValueError ( "block size must be a multiple of 16" ) plaintext = b'' while block : a , b , c , d = struct . unpack ( "<4L" , block [ : 16 ] ) temp = [ a , b , c , d ] decrypt ( self . context , temp ) plaintext += struct . pack ( "<4L" , * temp ) block = block [ 16 : ] return plaintext
Decrypt blocks .
107
4
244,118
def encrypt ( self , block ) : if len ( block ) % 16 : raise ValueError ( "block size must be a multiple of 16" ) ciphertext = b'' while block : a , b , c , d = struct . unpack ( "<4L" , block [ 0 : 16 ] ) temp = [ a , b , c , d ] encrypt ( self . context , temp ) ciphertext += struct . pack ( "<4L" , * temp ) block = block [ 16 : ] return ciphertext
Encrypt blocks .
108
4
244,119
def aes_kdf ( key , rounds , password = None , keyfile = None ) : cipher = AES . new ( key , AES . MODE_ECB ) key_composite = compute_key_composite ( password = password , keyfile = keyfile ) # get the number of rounds from the header and transform the key_composite transformed_key = key_composite for _ in range ( 0 , rounds ) : transformed_key = cipher . encrypt ( transformed_key ) return hashlib . sha256 ( transformed_key ) . digest ( )
Set up a context for AES128 - ECB encryption to find transformed_key
125
15
244,120
def compute_key_composite ( password = None , keyfile = None ) : # hash the password if password : password_composite = hashlib . sha256 ( password . encode ( 'utf-8' ) ) . digest ( ) else : password_composite = b'' # hash the keyfile if keyfile : # try to read XML keyfile try : with open ( keyfile , 'r' ) as f : tree = etree . parse ( f ) . getroot ( ) keyfile_composite = base64 . b64decode ( tree . find ( 'Key/Data' ) . text ) # otherwise, try to read plain keyfile except ( etree . XMLSyntaxError , UnicodeDecodeError ) : try : with open ( keyfile , 'rb' ) as f : key = f . read ( ) try : int ( key , 16 ) is_hex = True except ValueError : is_hex = False # if the length is 32 bytes we assume it is the key if len ( key ) == 32 : keyfile_composite = key # if the length is 64 bytes we assume the key is hex encoded elif len ( key ) == 64 and is_hex : keyfile_composite = codecs . decode ( key , 'hex' ) # anything else may be a file to hash for the key else : keyfile_composite = hashlib . sha256 ( key ) . digest ( ) except : raise IOError ( 'Could not read keyfile' ) else : keyfile_composite = b'' # create composite key from password and keyfile composites return hashlib . sha256 ( password_composite + keyfile_composite ) . digest ( )
Compute composite key . Used in header verification and payload decryption .
375
14
244,121
def compute_master ( context ) : # combine the transformed key with the header master seed to find the master_key master_key = hashlib . sha256 ( context . _ . header . value . dynamic_header . master_seed . data + context . transformed_key ) . digest ( ) return master_key
Computes master key from transformed key and master seed . Used in payload decryption .
67
17
244,122
def Unprotect ( protected_stream_id , protected_stream_key , subcon ) : return Switch ( protected_stream_id , { 'arcfourvariant' : ARCFourVariantStream ( protected_stream_key , subcon ) , 'salsa20' : Salsa20Stream ( protected_stream_key , subcon ) , 'chacha20' : ChaCha20Stream ( protected_stream_key , subcon ) , } , default = subcon )
Select stream cipher based on protected_stream_id
103
10
244,123
def encrypt ( self , plaintext , n = '' ) : #self.ed = 'e' if chain is encrypting, 'd' if decrypting, # None if nothing happened with the chain yet #assert self.ed in ('e',None) # makes sure you don't encrypt with a cipher that has started decrypting self . ed = 'e' if self . mode == MODE_XTS : # data sequence number (or 'tweak') has to be provided when in XTS mode return self . chain . update ( plaintext , 'e' , n ) else : return self . chain . update ( plaintext , 'e' )
Encrypt some plaintext
138
5
244,124
def decrypt ( self , ciphertext , n = '' ) : #self.ed = 'e' if chain is encrypting, 'd' if decrypting, # None if nothing happened with the chain yet #assert self.ed in ('d',None) # makes sure you don't decrypt with a cipher that has started encrypting self . ed = 'd' if self . mode == MODE_XTS : # data sequence number (or 'tweak') has to be provided when in XTS mode return self . chain . update ( ciphertext , 'd' , n ) else : return self . chain . update ( ciphertext , 'd' )
Decrypt some ciphertext
138
5
244,125
def final ( self , style = 'pkcs7' ) : # TODO: after calling final, reset the IV? so the cipher is as good as new? assert self . mode not in ( MODE_XTS , MODE_CMAC ) # finalizing (=padding) doesn't make sense when in XTS or CMAC mode if self . ed == b'e' : # when the chain is in encryption mode, finalizing will pad the cache and encrypt this last block if self . mode in ( MODE_OFB , MODE_CFB , MODE_CTR ) : dummy = b'0' * ( self . chain . totalbytes % self . blocksize ) # a dummy string that will be used to get a valid padding else : #ECB, CBC dummy = self . chain . cache pdata = pad ( dummy , self . blocksize , style = style ) [ len ( dummy ) : ] #~ pad = padfct(dummy,padding.PAD,self.blocksize)[len(dummy):] # construct the padding necessary return self . chain . update ( pdata , b'e' ) # supply the padding to the update function => chain cache will be "cache+padding" else : # final function doesn't make sense when decrypting => padding should be removed manually pass
Finalizes the encryption by padding the cache
282
8
244,126
def _datetime_to_utc ( self , dt ) : if not dt . tzinfo : dt = dt . replace ( tzinfo = tz . gettz ( ) ) return dt . astimezone ( tz . gettz ( 'UTC' ) )
Convert naive datetimes to UTC
64
7
244,127
def _encode_time ( self , value ) : if self . _kp . version >= ( 4 , 0 ) : diff_seconds = int ( ( self . _datetime_to_utc ( value ) - datetime ( year = 1 , month = 1 , day = 1 , tzinfo = tz . gettz ( 'UTC' ) ) ) . total_seconds ( ) ) return base64 . b64encode ( struct . pack ( '<Q' , diff_seconds ) ) . decode ( 'utf-8' ) else : return self . _datetime_to_utc ( value ) . isoformat ( )
Convert datetime to base64 or plaintext string
139
11
244,128
def _decode_time ( self , text ) : if self . _kp . version >= ( 4 , 0 ) : # decode KDBX4 date from b64 format try : return ( datetime ( year = 1 , month = 1 , day = 1 , tzinfo = tz . gettz ( 'UTC' ) ) + timedelta ( seconds = struct . unpack ( '<Q' , base64 . b64decode ( text ) ) [ 0 ] ) ) except BinasciiError : return parser . parse ( text , tzinfos = { 'UTC' : tz . gettz ( 'UTC' ) } ) else : return parser . parse ( text , tzinfos = { 'UTC' : tz . gettz ( 'UTC' ) } )
Convert base64 time or plaintext time to datetime
171
12
244,129
def fromrdd ( rdd , dims = None , nrecords = None , dtype = None , labels = None , ordered = False ) : from . images import Images from bolt . spark . array import BoltArraySpark if dims is None or dtype is None : item = rdd . values ( ) . first ( ) dtype = item . dtype dims = item . shape if nrecords is None : nrecords = rdd . count ( ) def process_keys ( record ) : k , v = record if isinstance ( k , int ) : k = ( k , ) return k , v values = BoltArraySpark ( rdd . map ( process_keys ) , shape = ( nrecords , ) + tuple ( dims ) , dtype = dtype , split = 1 , ordered = ordered ) return Images ( values , labels = labels )
Load images from a Spark RDD .
189
8
244,130
def fromarray ( values , labels = None , npartitions = None , engine = None ) : from . images import Images import bolt if isinstance ( values , bolt . spark . array . BoltArraySpark ) : return Images ( values ) values = asarray ( values ) if values . ndim < 2 : raise ValueError ( 'Array for images must have at least 2 dimensions, got %g' % values . ndim ) if values . ndim == 2 : values = expand_dims ( values , 0 ) shape = None dtype = None for im in values : if shape is None : shape = im . shape dtype = im . dtype if not im . shape == shape : raise ValueError ( 'Arrays must all be of same shape; got both %s and %s' % ( str ( shape ) , str ( im . shape ) ) ) if not im . dtype == dtype : raise ValueError ( 'Arrays must all be of same data type; got both %s and %s' % ( str ( dtype ) , str ( im . dtype ) ) ) if spark and isinstance ( engine , spark ) : if not npartitions : npartitions = engine . defaultParallelism values = bolt . array ( values , context = engine , npartitions = npartitions , axis = ( 0 , ) ) values . _ordered = True return Images ( values ) return Images ( values , labels = labels )
Load images from an array .
308
6
244,131
def fromlist ( items , accessor = None , keys = None , dims = None , dtype = None , labels = None , npartitions = None , engine = None ) : if spark and isinstance ( engine , spark ) : nrecords = len ( items ) if keys : items = zip ( keys , items ) else : keys = [ ( i , ) for i in range ( nrecords ) ] items = zip ( keys , items ) if not npartitions : npartitions = engine . defaultParallelism rdd = engine . parallelize ( items , npartitions ) if accessor : rdd = rdd . mapValues ( accessor ) return fromrdd ( rdd , nrecords = nrecords , dims = dims , dtype = dtype , labels = labels , ordered = True ) else : if accessor : items = asarray ( [ accessor ( i ) for i in items ] ) return fromarray ( items , labels = labels )
Load images from a list of items using the given accessor .
212
13
244,132
def frompath ( path , accessor = None , ext = None , start = None , stop = None , recursive = False , npartitions = None , dims = None , dtype = None , labels = None , recount = False , engine = None , credentials = None ) : from thunder . readers import get_parallel_reader reader = get_parallel_reader ( path ) ( engine , credentials = credentials ) data = reader . read ( path , ext = ext , start = start , stop = stop , recursive = recursive , npartitions = npartitions ) if spark and isinstance ( engine , spark ) : if accessor : data = data . flatMap ( accessor ) if recount : nrecords = None def switch ( record ) : ary , idx = record return ( idx , ) , ary data = data . values ( ) . zipWithIndex ( ) . map ( switch ) else : nrecords = reader . nfiles return fromrdd ( data , nrecords = nrecords , dims = dims , dtype = dtype , labels = labels , ordered = True ) else : if accessor : data = [ accessor ( d ) for d in data ] flattened = list ( itertools . chain ( * data ) ) values = [ kv [ 1 ] for kv in flattened ] return fromarray ( values , labels = labels )
Load images from a path using the given accessor .
296
11
244,133
def fromtif ( path , ext = 'tif' , start = None , stop = None , recursive = False , nplanes = None , npartitions = None , labels = None , engine = None , credentials = None , discard_extra = False ) : from tifffile import TiffFile if nplanes is not None and nplanes <= 0 : raise ValueError ( 'nplanes must be positive if passed, got %d' % nplanes ) def getarray ( idx_buffer_filename ) : idx , buf , fname = idx_buffer_filename fbuf = BytesIO ( buf ) tfh = TiffFile ( fbuf ) ary = tfh . asarray ( ) pageCount = ary . shape [ 0 ] if nplanes is not None : extra = pageCount % nplanes if extra : if discard_extra : pageCount = pageCount - extra logging . getLogger ( 'thunder' ) . warn ( 'Ignored %d pages in file %s' % ( extra , fname ) ) else : raise ValueError ( "nplanes '%d' does not evenly divide '%d in file %s'" % ( nplanes , pageCount , fname ) ) values = [ ary [ i : ( i + nplanes ) ] for i in range ( 0 , pageCount , nplanes ) ] else : values = [ ary ] tfh . close ( ) if ary . ndim == 3 : values = [ val . squeeze ( ) for val in values ] nvals = len ( values ) keys = [ ( idx * nvals + timepoint , ) for timepoint in range ( nvals ) ] return zip ( keys , values ) recount = False if nplanes is None else True data = frompath ( path , accessor = getarray , ext = ext , start = start , stop = stop , recursive = recursive , npartitions = npartitions , recount = recount , labels = labels , engine = engine , credentials = credentials ) if engine is not None and npartitions is not None and data . npartitions ( ) < npartitions : data = data . repartition ( npartitions ) return data
Loads images from single or multi - page TIF files .
463
13
244,134
def frompng ( path , ext = 'png' , start = None , stop = None , recursive = False , npartitions = None , labels = None , engine = None , credentials = None ) : from scipy . misc import imread def getarray ( idx_buffer_filename ) : idx , buf , _ = idx_buffer_filename fbuf = BytesIO ( buf ) yield ( idx , ) , imread ( fbuf ) return frompath ( path , accessor = getarray , ext = ext , start = start , stop = stop , recursive = recursive , npartitions = npartitions , labels = labels , engine = engine , credentials = credentials )
Load images from PNG files .
147
6
244,135
def fromrandom ( shape = ( 10 , 50 , 50 ) , npartitions = 1 , seed = 42 , engine = None ) : seed = hash ( seed ) def generate ( v ) : random . seed ( seed + v ) return random . randn ( * shape [ 1 : ] ) return fromlist ( range ( shape [ 0 ] ) , accessor = generate , npartitions = npartitions , engine = engine )
Generate random image data .
91
6
244,136
def fromexample ( name = None , engine = None ) : datasets = [ 'mouse' , 'fish' ] if name is None : print ( 'Availiable example image datasets' ) for d in datasets : print ( '- ' + d ) return check_options ( name , datasets ) path = 's3n://thunder-sample-data/images/' + name if name == 'mouse' : data = frombinary ( path = path , npartitions = 1 , order = 'F' , engine = engine ) if name == 'fish' : data = fromtif ( path = path , npartitions = 1 , engine = engine ) if spark and isinstance ( engine , spark ) : data . cache ( ) data . compute ( ) return data
Load example image data .
162
5
244,137
def unchunk ( self ) : if self . padding != len ( self . shape ) * ( 0 , ) : shape = self . values . shape arr = empty ( shape , dtype = object ) for inds in product ( * [ arange ( s ) for s in shape ] ) : slices = [ ] for i , p , n in zip ( inds , self . padding , shape ) : start = None if ( i == 0 or p == 0 ) else p stop = None if ( i == n - 1 or p == 0 ) else - p slices . append ( slice ( start , stop , None ) ) arr [ inds ] = self . values [ inds ] [ tuple ( slices ) ] else : arr = self . values return allstack ( arr . tolist ( ) )
Reconstitute the chunked array back into a full ndarray .
168
16
244,138
def chunk ( arr , chunk_size = "150" , padding = None ) : plan , _ = LocalChunks . getplan ( chunk_size , arr . shape [ 1 : ] , arr . dtype ) plan = r_ [ arr . shape [ 0 ] , plan ] if padding is None : pad = arr . ndim * ( 0 , ) elif isinstance ( padding , int ) : pad = ( 0 , ) + ( arr . ndim - 1 ) * ( padding , ) else : pad = ( 0 , ) + padding shape = arr . shape if any ( [ x + y > z for x , y , z in zip ( plan , pad , shape ) ] ) : raise ValueError ( "Chunk sizes %s plus padding sizes %s cannot exceed value dimensions %s along any axis" % ( tuple ( plan ) , tuple ( pad ) , tuple ( shape ) ) ) if any ( [ x > y for x , y in zip ( pad , plan ) ] ) : raise ValueError ( "Padding sizes %s cannot exceed chunk sizes %s along any axis" % ( tuple ( pad ) , tuple ( plan ) ) ) def rectify ( x ) : x [ x < 0 ] = 0 return x breaks = [ r_ [ arange ( 0 , n , s ) , n ] for n , s in zip ( shape , plan ) ] limits = [ zip ( rectify ( b [ : - 1 ] - p ) , b [ 1 : ] + p ) for b , p in zip ( breaks , pad ) ] slices = product ( * [ [ slice ( x [ 0 ] , x [ 1 ] ) for x in l ] for l in limits ] ) vals = [ arr [ s ] for s in slices ] newarr = empty ( len ( vals ) , dtype = object ) for i in range ( len ( vals ) ) : newarr [ i ] = vals [ i ] newsize = [ b . shape [ 0 ] - 1 for b in breaks ] newarr = newarr . reshape ( * newsize ) return LocalChunks ( newarr , shape , plan , dtype = arr . dtype , padding = pad )
Created a chunked array from a full array and a chunk size .
466
14
244,139
def filter ( self , func ) : if self . mode == 'local' : reshaped = self . _align ( self . baseaxes ) filtered = asarray ( list ( filter ( func , reshaped ) ) ) if self . labels is not None : mask = asarray ( list ( map ( func , reshaped ) ) ) if self . mode == 'spark' : sort = False if self . labels is None else True filtered = self . values . filter ( func , axis = self . baseaxes , sort = sort ) if self . labels is not None : keys , vals = zip ( * self . values . map ( func , axis = self . baseaxes , value_shape = ( 1 , ) ) . tordd ( ) . collect ( ) ) perm = sorted ( range ( len ( keys ) ) , key = keys . __getitem__ ) mask = asarray ( vals ) [ perm ] if self . labels is not None : s1 = prod ( self . baseshape ) newlabels = self . labels . reshape ( s1 , 1 ) [ mask ] . squeeze ( ) else : newlabels = None return self . _constructor ( filtered , labels = newlabels ) . __finalize__ ( self , noprop = ( 'labels' , ) )
Filter array along an axis .
282
6
244,140
def map ( self , func , value_shape = None , dtype = None , with_keys = False ) : axis = self . baseaxes if self . mode == 'local' : axes = sorted ( tupleize ( axis ) ) key_shape = [ self . shape [ axis ] for axis in axes ] reshaped = self . _align ( axes , key_shape = key_shape ) if with_keys : keys = zip ( * unravel_index ( range ( prod ( key_shape ) ) , key_shape ) ) mapped = asarray ( list ( map ( func , zip ( keys , reshaped ) ) ) ) else : mapped = asarray ( list ( map ( func , reshaped ) ) ) try : elem_shape = mapped [ 0 ] . shape except : elem_shape = ( 1 , ) expand = list ( elem_shape ) expand = [ 1 ] if len ( expand ) == 0 else expand # invert the previous reshape operation, using the shape of the map result linearized_shape_inv = key_shape + expand reordered = mapped . reshape ( * linearized_shape_inv ) return self . _constructor ( reordered , mode = self . mode ) . __finalize__ ( self , noprop = ( 'index' ) ) if self . mode == 'spark' : expand = lambda x : array ( func ( x ) , ndmin = 1 ) mapped = self . values . map ( expand , axis , value_shape , dtype , with_keys ) return self . _constructor ( mapped , mode = self . mode ) . __finalize__ ( self , noprop = ( 'index' , ) )
Apply an array - > array function across an axis .
363
11
244,141
def _reduce ( self , func , axis = 0 ) : if self . mode == 'local' : axes = sorted ( tupleize ( axis ) ) # if the function is a ufunc, it can automatically handle reducing over multiple axes if isinstance ( func , ufunc ) : inshape ( self . shape , axes ) reduced = func . reduce ( self , axis = tuple ( axes ) ) else : reshaped = self . _align ( axes ) reduced = reduce ( func , reshaped ) # ensure that the shape of the reduced array is valid expected_shape = [ self . shape [ i ] for i in range ( len ( self . shape ) ) if i not in axes ] if reduced . shape != tuple ( expected_shape ) : raise ValueError ( "reduce did not yield an array with valid dimensions" ) return self . _constructor ( reduced [ newaxis , : ] ) . __finalize__ ( self ) if self . mode == 'spark' : reduced = self . values . reduce ( func , axis , keepdims = True ) return self . _constructor ( reduced ) . __finalize__ ( self )
Reduce an array along an axis .
243
8
244,142
def element_wise ( self , other , op ) : if not isscalar ( other ) and not self . shape == other . shape : raise ValueError ( "shapes %s and %s must be equal" % ( self . shape , other . shape ) ) if not isscalar ( other ) and isinstance ( other , Data ) and not self . mode == other . mode : raise NotImplementedError if isscalar ( other ) : return self . map ( lambda x : op ( x , other ) ) if self . mode == 'local' and isinstance ( other , ndarray ) : return self . _constructor ( op ( self . values , other ) ) . __finalize__ ( self ) if self . mode == 'local' and isinstance ( other , Data ) : return self . _constructor ( op ( self . values , other . values ) ) . __finalize__ ( self ) if self . mode == 'spark' and isinstance ( other , Data ) : def func ( record ) : ( k1 , x ) , ( k2 , y ) = record return k1 , op ( x , y ) rdd = self . tordd ( ) . zip ( other . tordd ( ) ) . map ( func ) barray = BoltArraySpark ( rdd , shape = self . shape , dtype = self . dtype , split = self . values . split ) return self . _constructor ( barray ) . __finalize__ ( self )
Apply an elementwise operation to data .
324
8
244,143
def clip ( self , min = None , max = None ) : return self . _constructor ( self . values . clip ( min = min , max = max ) ) . __finalize__ ( self )
Clip values above and below .
44
7
244,144
def fromrdd ( rdd , nrecords = None , shape = None , index = None , labels = None , dtype = None , ordered = False ) : from . series import Series from bolt . spark . array import BoltArraySpark if index is None or dtype is None : item = rdd . values ( ) . first ( ) if index is None : index = range ( len ( item ) ) if dtype is None : dtype = item . dtype if nrecords is None and shape is not None : nrecords = prod ( shape [ : - 1 ] ) if nrecords is None : nrecords = rdd . count ( ) if shape is None : shape = ( nrecords , asarray ( index ) . shape [ 0 ] ) def process_keys ( record ) : k , v = record if isinstance ( k , int ) : k = ( k , ) return k , v values = BoltArraySpark ( rdd . map ( process_keys ) , shape = shape , dtype = dtype , split = len ( shape ) - 1 , ordered = ordered ) return Series ( values , index = index , labels = labels )
Load series data from a Spark RDD .
251
9
244,145
def fromarray ( values , index = None , labels = None , npartitions = None , engine = None ) : from . series import Series import bolt if isinstance ( values , bolt . spark . array . BoltArraySpark ) : return Series ( values ) values = asarray ( values ) if values . ndim < 2 : values = expand_dims ( values , 0 ) if index is not None and not asarray ( index ) . shape [ 0 ] == values . shape [ - 1 ] : raise ValueError ( 'Index length %s not equal to record length %s' % ( asarray ( index ) . shape [ 0 ] , values . shape [ - 1 ] ) ) if index is None : index = arange ( values . shape [ - 1 ] ) if spark and isinstance ( engine , spark ) : axis = tuple ( range ( values . ndim - 1 ) ) values = bolt . array ( values , context = engine , npartitions = npartitions , axis = axis ) values . _ordered = True return Series ( values , index = index ) return Series ( values , index = index , labels = labels )
Load series data from an array .
241
7
244,146
def fromlist ( items , accessor = None , index = None , labels = None , dtype = None , npartitions = None , engine = None ) : if spark and isinstance ( engine , spark ) : if dtype is None : dtype = accessor ( items [ 0 ] ) . dtype if accessor else items [ 0 ] . dtype nrecords = len ( items ) keys = map ( lambda k : ( k , ) , range ( len ( items ) ) ) if not npartitions : npartitions = engine . defaultParallelism items = zip ( keys , items ) rdd = engine . parallelize ( items , npartitions ) if accessor : rdd = rdd . mapValues ( accessor ) return fromrdd ( rdd , nrecords = nrecords , index = index , labels = labels , dtype = dtype , ordered = True ) else : if accessor : items = [ accessor ( i ) for i in items ] return fromarray ( items , index = index , labels = labels )
Load series data from a list with an optional accessor function .
226
13
244,147
def fromtext ( path , ext = 'txt' , dtype = 'float64' , skip = 0 , shape = None , index = None , labels = None , npartitions = None , engine = None , credentials = None ) : from thunder . readers import normalize_scheme , get_parallel_reader path = normalize_scheme ( path , ext ) if spark and isinstance ( engine , spark ) : def parse ( line , skip ) : vec = [ float ( x ) for x in line . split ( ' ' ) ] return array ( vec [ skip : ] , dtype = dtype ) lines = engine . textFile ( path , npartitions ) data = lines . map ( lambda x : parse ( x , skip ) ) def switch ( record ) : ary , idx = record return ( idx , ) , ary rdd = data . zipWithIndex ( ) . map ( switch ) return fromrdd ( rdd , dtype = str ( dtype ) , shape = shape , index = index , ordered = True ) else : reader = get_parallel_reader ( path ) ( engine , credentials = credentials ) data = reader . read ( path , ext = ext ) values = [ ] for kv in data : for line in str ( kv [ 1 ] . decode ( 'utf-8' ) ) . split ( '\n' ) [ : - 1 ] : values . append ( fromstring ( line , sep = ' ' ) ) values = asarray ( values ) if skip > 0 : values = values [ : , skip : ] if shape : values = values . reshape ( shape ) return fromarray ( values , index = index , labels = labels )
Loads series data from text files .
365
8
244,148
def frombinary ( path , ext = 'bin' , conf = 'conf.json' , dtype = None , shape = None , skip = 0 , index = None , labels = None , engine = None , credentials = None ) : shape , dtype = _binaryconfig ( path , conf , dtype , shape , credentials ) from thunder . readers import normalize_scheme , get_parallel_reader path = normalize_scheme ( path , ext ) from numpy import dtype as dtype_func nelements = shape [ - 1 ] + skip recordsize = dtype_func ( dtype ) . itemsize * nelements if spark and isinstance ( engine , spark ) : lines = engine . binaryRecords ( path , recordsize ) raw = lines . map ( lambda x : frombuffer ( buffer ( x ) , offset = 0 , count = nelements , dtype = dtype ) [ skip : ] ) def switch ( record ) : ary , idx = record return ( idx , ) , ary rdd = raw . zipWithIndex ( ) . map ( switch ) if shape and len ( shape ) > 2 : expand = lambda k : unravel_index ( k [ 0 ] , shape [ 0 : - 1 ] ) rdd = rdd . map ( lambda kv : ( expand ( kv [ 0 ] ) , kv [ 1 ] ) ) if not index : index = arange ( shape [ - 1 ] ) return fromrdd ( rdd , dtype = dtype , shape = shape , index = index , ordered = True ) else : reader = get_parallel_reader ( path ) ( engine , credentials = credentials ) data = reader . read ( path , ext = ext ) values = [ ] for record in data : buf = record [ 1 ] offset = 0 while offset < len ( buf ) : v = frombuffer ( buffer ( buf ) , offset = offset , count = nelements , dtype = dtype ) values . append ( v [ skip : ] ) offset += recordsize if not len ( values ) == prod ( shape [ 0 : - 1 ] ) : raise ValueError ( 'Unexpected shape, got %g records but expected %g' % ( len ( values ) , prod ( shape [ 0 : - 1 ] ) ) ) values = asarray ( values , dtype = dtype ) if shape : values = values . reshape ( shape ) return fromarray ( values , index = index , labels = labels )
Load series data from flat binary files .
528
8
244,149
def _binaryconfig ( path , conf , dtype = None , shape = None , credentials = None ) : import json from thunder . readers import get_file_reader , FileNotFoundError reader = get_file_reader ( path ) ( credentials = credentials ) try : buf = reader . read ( path , filename = conf ) params = json . loads ( str ( buf . decode ( 'utf-8' ) ) ) except FileNotFoundError : params = { } if dtype : params [ 'dtype' ] = dtype if shape : params [ 'shape' ] = shape if 'dtype' not in params . keys ( ) : raise ValueError ( 'dtype not specified either in conf.json or as argument' ) if 'shape' not in params . keys ( ) : raise ValueError ( 'shape not specified either in conf.json or as argument' ) return params [ 'shape' ] , params [ 'dtype' ]
Collects parameters to use for binary series loading .
201
10
244,150
def fromexample ( name = None , engine = None ) : import os import tempfile import shutil from boto . s3 . connection import S3Connection datasets = [ 'iris' , 'mouse' , 'fish' ] if name is None : print ( 'Availiable example series datasets' ) for d in datasets : print ( '- ' + d ) return check_options ( name , datasets ) d = tempfile . mkdtemp ( ) try : os . mkdir ( os . path . join ( d , 'series' ) ) os . mkdir ( os . path . join ( d , 'series' , name ) ) conn = S3Connection ( anon = True ) bucket = conn . get_bucket ( 'thunder-sample-data' ) for key in bucket . list ( os . path . join ( 'series' , name ) + '/' ) : if not key . name . endswith ( '/' ) : key . get_contents_to_filename ( os . path . join ( d , key . name ) ) data = frombinary ( os . path . join ( d , 'series' , name ) , engine = engine ) if spark and isinstance ( engine , spark ) : data . cache ( ) data . compute ( ) finally : shutil . rmtree ( d ) return data
Load example series data .
285
5
244,151
def tobinary ( series , path , prefix = 'series' , overwrite = False , credentials = None ) : from six import BytesIO from thunder . utils import check_path from thunder . writers import get_parallel_writer if not overwrite : check_path ( path , credentials = credentials ) overwrite = True def tobuffer ( kv ) : firstkey = None buf = BytesIO ( ) for k , v in kv : if firstkey is None : firstkey = k buf . write ( v . tostring ( ) ) val = buf . getvalue ( ) buf . close ( ) if firstkey is None : return iter ( [ ] ) else : label = prefix + '-' + getlabel ( firstkey ) + ".bin" return iter ( [ ( label , val ) ] ) writer = get_parallel_writer ( path ) ( path , overwrite = overwrite , credentials = credentials ) if series . mode == 'spark' : binary = series . values . tordd ( ) . sortByKey ( ) . mapPartitions ( tobuffer ) binary . foreach ( writer . write ) else : basedims = [ series . shape [ d ] for d in series . baseaxes ] def split ( k ) : ind = unravel_index ( k , basedims ) return ind , series . values [ ind ] buf = tobuffer ( [ split ( i ) for i in range ( prod ( basedims ) ) ] ) [ writer . write ( b ) for b in buf ] shape = series . shape dtype = series . dtype write_config ( path , shape = shape , dtype = dtype , overwrite = overwrite , credentials = credentials )
Writes out data to binary format .
353
8
244,152
def write_config ( path , shape = None , dtype = None , name = "conf.json" , overwrite = True , credentials = None ) : import json from thunder . writers import get_file_writer writer = get_file_writer ( path ) conf = { 'shape' : shape , 'dtype' : str ( dtype ) } confwriter = writer ( path , name , overwrite = overwrite , credentials = credentials ) confwriter . write ( json . dumps ( conf , indent = 2 ) ) successwriter = writer ( path , "SUCCESS" , overwrite = overwrite , credentials = credentials ) successwriter . write ( '' )
Write a conf . json file with required information to load Series binary data .
136
15
244,153
def toblocks ( self , chunk_size = 'auto' , padding = None ) : from thunder . blocks . blocks import Blocks from thunder . blocks . local import LocalChunks if self . mode == 'spark' : if chunk_size is 'auto' : chunk_size = str ( max ( [ int ( 1e5 / self . shape [ 0 ] ) , 1 ] ) ) chunks = self . values . chunk ( chunk_size , padding = padding ) . keys_to_values ( ( 0 , ) ) if self . mode == 'local' : if chunk_size is 'auto' : chunk_size = self . shape [ 1 : ] chunks = LocalChunks . chunk ( self . values , chunk_size , padding = padding ) return Blocks ( chunks )
Convert to blocks which represent subdivisions of the images data .
165
13
244,154
def toseries ( self , chunk_size = 'auto' ) : from thunder . series . series import Series if chunk_size is 'auto' : chunk_size = str ( max ( [ int ( 1e5 / self . shape [ 0 ] ) , 1 ] ) ) n = len ( self . shape ) - 1 index = arange ( self . shape [ 0 ] ) if self . mode == 'spark' : return Series ( self . values . swap ( ( 0 , ) , tuple ( range ( n ) ) , size = chunk_size ) , index = index ) if self . mode == 'local' : return Series ( self . values . transpose ( tuple ( range ( 1 , n + 1 ) ) + ( 0 , ) ) , index = index )
Converts to series data .
165
6
244,155
def tospark ( self , engine = None ) : from thunder . images . readers import fromarray if self . mode == 'spark' : logging . getLogger ( 'thunder' ) . warn ( 'images already in spark mode' ) pass if engine is None : raise ValueError ( 'Must provide a SparkContext' ) return fromarray ( self . toarray ( ) , engine = engine )
Convert to distributed spark mode .
86
7
244,156
def foreach ( self , func ) : if self . mode == 'spark' : self . values . tordd ( ) . map ( lambda kv : ( kv [ 0 ] [ 0 ] , kv [ 1 ] ) ) . foreach ( func ) else : [ func ( kv ) for kv in enumerate ( self . values ) ]
Execute a function on each image .
78
8
244,157
def sample ( self , nsamples = 100 , seed = None ) : if nsamples < 1 : raise ValueError ( "Number of samples must be larger than 0, got '%g'" % nsamples ) if seed is None : seed = random . randint ( 0 , 2 ** 32 ) if self . mode == 'spark' : result = asarray ( self . values . tordd ( ) . values ( ) . takeSample ( False , nsamples , seed ) ) else : inds = [ int ( k ) for k in random . rand ( nsamples ) * self . shape [ 0 ] ] result = asarray ( [ self . values [ i ] for i in inds ] ) return self . _constructor ( result )
Extract a random sample of images .
158
8
244,158
def var ( self ) : return self . _constructor ( self . values . var ( axis = 0 , keepdims = True ) )
Compute the variance across images .
30
7
244,159
def std ( self ) : return self . _constructor ( self . values . std ( axis = 0 , keepdims = True ) )
Compute the standard deviation across images .
30
8
244,160
def squeeze ( self ) : axis = tuple ( range ( 1 , len ( self . shape ) - 1 ) ) if prod ( self . shape [ 1 : ] ) == 1 else None return self . map ( lambda x : x . squeeze ( axis = axis ) )
Remove single - dimensional axes from images .
56
8
244,161
def max_projection ( self , axis = 2 ) : if axis >= size ( self . value_shape ) : raise Exception ( 'Axis for projection (%s) exceeds ' 'image dimensions (%s-%s)' % ( axis , 0 , size ( self . value_shape ) - 1 ) ) new_value_shape = list ( self . value_shape ) del new_value_shape [ axis ] return self . map ( lambda x : amax ( x , axis ) , value_shape = new_value_shape )
Compute maximum projections of images along a dimension .
114
10
244,162
def max_min_projection ( self , axis = 2 ) : if axis >= size ( self . value_shape ) : raise Exception ( 'Axis for projection (%s) exceeds ' 'image dimensions (%s-%s)' % ( axis , 0 , size ( self . value_shape ) - 1 ) ) new_value_shape = list ( self . value_shape ) del new_value_shape [ axis ] return self . map ( lambda x : amax ( x , axis ) + amin ( x , axis ) , value_shape = new_value_shape )
Compute maximum - minimum projection along a dimension .
124
10
244,163
def subsample ( self , factor ) : value_shape = self . value_shape ndims = len ( value_shape ) if not hasattr ( factor , '__len__' ) : factor = [ factor ] * ndims factor = [ int ( sf ) for sf in factor ] if any ( ( sf <= 0 for sf in factor ) ) : raise ValueError ( 'All sampling factors must be positive; got ' + str ( factor ) ) def roundup ( a , b ) : return ( a + b - 1 ) // b slices = [ slice ( 0 , value_shape [ i ] , factor [ i ] ) for i in range ( ndims ) ] new_value_shape = tuple ( [ roundup ( value_shape [ i ] , factor [ i ] ) for i in range ( ndims ) ] ) return self . map ( lambda v : v [ slices ] , value_shape = new_value_shape )
Downsample images by an integer factor .
205
8
244,164
def gaussian_filter ( self , sigma = 2 , order = 0 ) : from scipy . ndimage . filters import gaussian_filter return self . map ( lambda v : gaussian_filter ( v , sigma , order ) , value_shape = self . value_shape )
Spatially smooth images with a gaussian filter .
64
11
244,165
def _image_filter ( self , filter = None , size = 2 ) : from numpy import isscalar from scipy . ndimage . filters import median_filter , uniform_filter FILTERS = { 'median' : median_filter , 'uniform' : uniform_filter } func = FILTERS [ filter ] mode = self . mode value_shape = self . value_shape ndims = len ( value_shape ) if ndims == 3 and isscalar ( size ) == 1 : size = [ size , size , size ] if ndims == 3 and size [ 2 ] == 0 : def filter_ ( im ) : if mode == 'spark' : im . setflags ( write = True ) else : im = im . copy ( ) for z in arange ( 0 , value_shape [ 2 ] ) : im [ : , : , z ] = func ( im [ : , : , z ] , size [ 0 : 2 ] ) return im else : filter_ = lambda x : func ( x , size ) return self . map ( lambda v : filter_ ( v ) , value_shape = self . value_shape )
Generic function for maping a filtering operation over images .
252
11
244,166
def localcorr ( self , size = 2 ) : from thunder . images . readers import fromarray , fromrdd from numpy import corrcoef , concatenate nimages = self . shape [ 0 ] # spatially average the original image set over the specified neighborhood blurred = self . uniform_filter ( size ) # union the averaged images with the originals to create an # Images object containing 2N images (where N is the original number of images), # ordered such that the first N images are the averaged ones. if self . mode == 'spark' : combined = self . values . concatenate ( blurred . values ) combined_images = fromrdd ( combined . tordd ( ) ) else : combined = concatenate ( ( self . values , blurred . values ) , axis = 0 ) combined_images = fromarray ( combined ) # correlate the first N (averaged) records with the last N (original) records series = combined_images . toseries ( ) corr = series . map ( lambda x : corrcoef ( x [ : nimages ] , x [ nimages : ] ) [ 0 , 1 ] ) return corr . toarray ( )
Correlate every pixel in an image sequence to the average of its local neighborhood .
251
17
244,167
def subtract ( self , val ) : if isinstance ( val , ndarray ) : if val . shape != self . value_shape : raise Exception ( 'Cannot subtract image with dimensions %s ' 'from images with dimension %s' % ( str ( val . shape ) , str ( self . value_shape ) ) ) return self . map ( lambda x : x - val , value_shape = self . value_shape )
Subtract a constant value or an image from all images .
92
13
244,168
def topng ( self , path , prefix = 'image' , overwrite = False ) : from thunder . images . writers import topng # TODO add back colormap and vmin/vmax topng ( self , path , prefix = prefix , overwrite = overwrite )
Write 2d images as PNG files .
57
8
244,169
def map_as_series ( self , func , value_size = None , dtype = None , chunk_size = 'auto' ) : blocks = self . toblocks ( chunk_size = chunk_size ) if value_size is not None : dims = list ( blocks . blockshape ) dims [ 0 ] = value_size else : dims = None def f ( block ) : return apply_along_axis ( func , 0 , block ) return blocks . map ( f , value_shape = dims , dtype = dtype ) . toimages ( )
Efficiently apply a function to images as series data .
124
12
244,170
def count ( self ) : if self . mode == 'spark' : return self . tordd ( ) . count ( ) if self . mode == 'local' : return prod ( self . values . values . shape )
Explicit count of the number of items .
48
9
244,171
def collect_blocks ( self ) : if self . mode == 'spark' : return self . values . tordd ( ) . sortByKey ( ) . values ( ) . collect ( ) if self . mode == 'local' : return self . values . values . flatten ( ) . tolist ( )
Collect the blocks in a list
67
6
244,172
def map ( self , func , value_shape = None , dtype = None ) : mapped = self . values . map ( func , value_shape = value_shape , dtype = dtype ) return self . _constructor ( mapped ) . __finalize__ ( self , noprop = ( 'dtype' , ) )
Apply an array - > array function to each block
72
10
244,173
def toimages ( self ) : from thunder . images . images import Images if self . mode == 'spark' : values = self . values . values_to_keys ( ( 0 , ) ) . unchunk ( ) if self . mode == 'local' : values = self . values . unchunk ( ) return Images ( values )
Convert blocks to images .
71
6
244,174
def toseries ( self ) : from thunder . series . series import Series if self . mode == 'spark' : values = self . values . values_to_keys ( tuple ( range ( 1 , len ( self . shape ) ) ) ) . unchunk ( ) if self . mode == 'local' : values = self . values . unchunk ( ) values = rollaxis ( values , 0 , values . ndim ) return Series ( values )
Converts blocks to series .
95
6
244,175
def toarray ( self ) : if self . mode == 'spark' : return self . values . unchunk ( ) . toarray ( ) if self . mode == 'local' : return self . values . unchunk ( )
Convert blocks to local ndarray
49
8
244,176
def flatten ( self ) : size = prod ( self . shape [ : - 1 ] ) return self . reshape ( size , self . shape [ - 1 ] )
Reshape all dimensions but the last into a single dimension
36
12
244,177
def tospark ( self , engine = None ) : from thunder . series . readers import fromarray if self . mode == 'spark' : logging . getLogger ( 'thunder' ) . warn ( 'images already in local mode' ) pass if engine is None : raise ValueError ( 'Must provide SparkContext' ) return fromarray ( self . toarray ( ) , index = self . index , labels = self . labels , engine = engine )
Convert to spark mode .
97
6
244,178
def sample ( self , n = 100 , seed = None ) : if n < 1 : raise ValueError ( "Number of samples must be larger than 0, got '%g'" % n ) if seed is None : seed = random . randint ( 0 , 2 ** 32 ) if self . mode == 'spark' : result = asarray ( self . values . tordd ( ) . values ( ) . takeSample ( False , n , seed ) ) else : basedims = [ self . shape [ d ] for d in self . baseaxes ] inds = [ unravel_index ( int ( k ) , basedims ) for k in random . rand ( n ) * prod ( basedims ) ] result = asarray ( [ self . values [ tupleize ( i ) + ( slice ( None , None ) , ) ] for i in inds ] ) return self . _constructor ( result , index = self . index )
Extract random sample of records .
199
7
244,179
def map ( self , func , index = None , value_shape = None , dtype = None , with_keys = False ) : # if new index is given, can infer missing value_shape if value_shape is None and index is not None : value_shape = len ( index ) if isinstance ( value_shape , int ) : values_shape = ( value_shape , ) new = super ( Series , self ) . map ( func , value_shape = value_shape , dtype = dtype , with_keys = with_keys ) if index is not None : new . index = index # if series shape did not change and no index was supplied, propagate original index else : if len ( new . index ) == len ( self . index ) : new . index = self . index return new
Map an array - > array function over each record .
171
11
244,180
def mean ( self ) : return self . _constructor ( self . values . mean ( axis = self . baseaxes , keepdims = True ) )
Compute the mean across records
34
6
244,181
def sum ( self ) : return self . _constructor ( self . values . sum ( axis = self . baseaxes , keepdims = True ) )
Compute the sum across records .
34
7
244,182
def max ( self ) : return self . _constructor ( self . values . max ( axis = self . baseaxes , keepdims = True ) )
Compute the max across records .
34
7
244,183
def min ( self ) : return self . _constructor ( self . values . min ( axis = self . baseaxes , keepdims = True ) )
Compute the min across records .
34
7
244,184
def reshape ( self , * shape ) : if prod ( self . shape ) != prod ( shape ) : raise ValueError ( "Reshaping must leave the number of elements unchanged" ) if self . shape [ - 1 ] != shape [ - 1 ] : raise ValueError ( "Reshaping cannot change the size of the constituent series (last dimension)" ) if self . labels is not None : newlabels = self . labels . reshape ( * shape [ : - 1 ] ) else : newlabels = None return self . _constructor ( self . values . reshape ( shape ) , labels = newlabels ) . __finalize__ ( self , noprop = ( 'labels' , ) )
Reshape the Series object
153
6
244,185
def between ( self , left , right ) : crit = lambda x : left <= x < right return self . select ( crit )
Select subset of values within the given index range .
27
10
244,186
def select ( self , crit ) : import types # handle lists, strings, and ints if not isinstance ( crit , types . FunctionType ) : # set("foo") -> {"f", "o"}; wrap in list to prevent: if isinstance ( crit , string_types ) : critlist = set ( [ crit ] ) else : try : critlist = set ( crit ) except TypeError : # typically means crit is not an iterable type; for instance, crit is an int critlist = set ( [ crit ] ) crit = lambda x : x in critlist # if only one index, return it directly or throw an error index = self . index if size ( index ) == 1 : if crit ( index [ 0 ] ) : return self else : raise Exception ( 'No indices found matching criterion' ) # determine new index and check the result newindex = [ i for i in index if crit ( i ) ] if len ( newindex ) == 0 : raise Exception ( 'No indices found matching criterion' ) if array ( newindex == index ) . all ( ) : return self # use fast logical indexing to get the new values subinds = where ( [ crit ( i ) for i in index ] ) new = self . map ( lambda x : x [ subinds ] , index = newindex ) # if singleton, need to check whether it's an array or a scalar/int # if array, recompute a new set of indices if len ( newindex ) == 1 : new = new . map ( lambda x : x [ 0 ] , index = newindex ) val = new . first ( ) if size ( val ) == 1 : newindex = [ newindex [ 0 ] ] else : newindex = arange ( 0 , size ( val ) ) new . _index = newindex return new
Select subset of values that match a given index criterion .
386
11
244,187
def center ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : x - mean ( x ) ) elif axis == 0 : meanval = self . mean ( ) . toarray ( ) return self . map ( lambda x : x - meanval ) else : raise Exception ( 'Axis must be 0 or 1' )
Subtract the mean either within or across records .
77
11
244,188
def standardize ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : x / std ( x ) ) elif axis == 0 : stdval = self . std ( ) . toarray ( ) return self . map ( lambda x : x / stdval ) else : raise Exception ( 'Axis must be 0 or 1' )
Divide by standard deviation either within or across records .
78
11
244,189
def zscore ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : ( x - mean ( x ) ) / std ( x ) ) elif axis == 0 : meanval = self . mean ( ) . toarray ( ) stdval = self . std ( ) . toarray ( ) return self . map ( lambda x : ( x - meanval ) / stdval ) else : raise Exception ( 'Axis must be 0 or 1' )
Subtract the mean and divide by standard deviation within or across records .
103
15
244,190
def squelch ( self , threshold ) : func = lambda x : zeros ( x . shape ) if max ( x ) < threshold else x return self . map ( func )
Set all records that do not exceed the given threhsold to 0 .
38
16
244,191
def correlate ( self , signal ) : s = asarray ( signal ) if s . ndim == 1 : if size ( s ) != self . shape [ - 1 ] : raise ValueError ( "Length of signal '%g' does not match record length '%g'" % ( size ( s ) , self . shape [ - 1 ] ) ) return self . map ( lambda x : corrcoef ( x , s ) [ 0 , 1 ] , index = [ 1 ] ) elif s . ndim == 2 : if s . shape [ 1 ] != self . shape [ - 1 ] : raise ValueError ( "Length of signal '%g' does not match record length '%g'" % ( s . shape [ 1 ] , self . shape [ - 1 ] ) ) newindex = arange ( 0 , s . shape [ 0 ] ) return self . map ( lambda x : array ( [ corrcoef ( x , y ) [ 0 , 1 ] for y in s ] ) , index = newindex ) else : raise Exception ( 'Signal to correlate with must have 1 or 2 dimensions' )
Correlate records against one or many one - dimensional arrays .
238
13
244,192
def _check_panel ( self , length ) : n = len ( self . index ) if divmod ( n , length ) [ 1 ] != 0 : raise ValueError ( "Panel length '%g' must evenly divide length of series '%g'" % ( length , n ) ) if n == length : raise ValueError ( "Panel length '%g' cannot be length of series '%g'" % ( length , n ) )
Check that given fixed panel length evenly divides index .
93
10
244,193
def mean_by_panel ( self , length ) : self . _check_panel ( length ) func = lambda v : v . reshape ( - 1 , length ) . mean ( axis = 0 ) newindex = arange ( length ) return self . map ( func , index = newindex )
Compute the mean across fixed sized panels of each record .
63
12
244,194
def _makemasks ( self , index = None , level = 0 ) : if index is None : index = self . index try : dims = len ( array ( index ) . shape ) if dims == 1 : index = array ( index , ndmin = 2 ) . T except : raise TypeError ( 'A multi-index must be convertible to a numpy ndarray' ) try : index = index [ : , level ] except : raise ValueError ( "Levels must be indices into individual elements of the index" ) lenIdx = index . shape [ 0 ] nlevels = index . shape [ 1 ] combs = product ( * [ unique ( index . T [ i , : ] ) for i in range ( nlevels ) ] ) combs = array ( [ l for l in combs ] ) masks = array ( [ [ array_equal ( index [ i ] , c ) for i in range ( lenIdx ) ] for c in combs ] ) return zip ( * [ ( masks [ x ] , combs [ x ] ) for x in range ( len ( masks ) ) if masks [ x ] . any ( ) ] )
Internal function for generating masks for selecting values based on multi - index values .
247
15
244,195
def _map_by_index ( self , function , level = 0 ) : if type ( level ) is int : level = [ level ] masks , ind = self . _makemasks ( index = self . index , level = level ) nMasks = len ( masks ) newindex = array ( ind ) if len ( newindex [ 0 ] ) == 1 : newindex = ravel ( newindex ) return self . map ( lambda v : asarray ( [ array ( function ( v [ masks [ x ] ] ) ) for x in range ( nMasks ) ] ) , index = newindex )
An internal function for maping a function to groups of values based on a multi - index
129
18
244,196
def aggregate_by_index ( self , function , level = 0 ) : result = self . _map_by_index ( function , level = level ) return result . map ( lambda v : array ( v ) , index = result . index )
Aggregrate data in each record grouping by index values .
52
13
244,197
def gramian ( self ) : if self . mode == 'spark' : rdd = self . values . tordd ( ) from pyspark . accumulators import AccumulatorParam class MatrixAccumulator ( AccumulatorParam ) : def zero ( self , value ) : return zeros ( shape ( value ) ) def addInPlace ( self , val1 , val2 ) : val1 += val2 return val1 global mat init = zeros ( ( self . shape [ 1 ] , self . shape [ 1 ] ) ) mat = rdd . context . accumulator ( init , MatrixAccumulator ( ) ) def outer_sum ( x ) : global mat mat += outer ( x , x ) rdd . values ( ) . foreach ( outer_sum ) return self . _constructor ( mat . value , index = self . index ) if self . mode == 'local' : return self . _constructor ( dot ( self . values . T , self . values ) , index = self . index )
Compute gramian of a distributed matrix .
218
9
244,198
def times ( self , other ) : if isinstance ( other , ScalarType ) : other = asarray ( other ) index = self . index else : if isinstance ( other , list ) : other = asarray ( other ) if isinstance ( other , ndarray ) and other . ndim < 2 : other = expand_dims ( other , 1 ) if not self . shape [ 1 ] == other . shape [ 0 ] : raise ValueError ( 'shapes %s and %s are not aligned' % ( self . shape , other . shape ) ) index = arange ( other . shape [ 1 ] ) if self . mode == 'local' and isinstance ( other , Series ) and other . mode == 'spark' : raise NotImplementedError if self . mode == 'spark' and isinstance ( other , Series ) and other . mode == 'spark' : raise NotImplementedError if self . mode == 'local' and isinstance ( other , ( ndarray , ScalarType ) ) : return self . _constructor ( dot ( self . values , other ) , index = index ) if self . mode == 'local' and isinstance ( other , Series ) : return self . _constructor ( dot ( self . values , other . values ) , index = index ) if self . mode == 'spark' and isinstance ( other , ( ndarray , ScalarType ) ) : return self . map ( lambda x : dot ( x , other ) , index = index ) if self . mode == 'spark' and isinstance ( other , Series ) : return self . map ( lambda x : dot ( x , other . values ) , index = index )
Multiply a matrix by another one .
366
9
244,199
def _makewindows ( self , indices , window ) : div = divmod ( window , 2 ) before = div [ 0 ] after = div [ 0 ] + div [ 1 ] index = asarray ( self . index ) indices = asarray ( indices ) if where ( index == max ( indices ) ) [ 0 ] [ 0 ] + after > len ( index ) : raise ValueError ( "Maximum requested index %g, with window %g, exceeds length %g" % ( max ( indices ) , window , len ( index ) ) ) if where ( index == min ( indices ) ) [ 0 ] [ 0 ] - before < 0 : raise ValueError ( "Minimum requested index %g, with window %g, is less than 0" % ( min ( indices ) , window ) ) masks = [ arange ( where ( index == i ) [ 0 ] [ 0 ] - before , where ( index == i ) [ 0 ] [ 0 ] + after , dtype = 'int' ) for i in indices ] return masks
Make masks used by windowing functions
216
7