idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
245,100
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 = ...
Recursively remove a file or dir by pattern .
245,101
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
245,102
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 ( "ht...
Deletes dev files
245,103
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
245,104
def coverage ( ) : 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 .
245,105
def venv ( ) : try : import virtualenv 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 .
245,106
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 .
245,107
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 ) +...
Compute hash of each payload block . Used to prevent payload corruption and tampering .
245,108
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 = bloc...
Decrypt blocks .
245,109
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 = ...
Encrypt blocks .
245,110
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 ) transformed_key = key_composite for _ in range ( 0 , rounds ) : transformed_key = cipher . encrypt ( transformed_key ) return ha...
Set up a context for AES128 - ECB encryption to find transformed_key
245,111
def compute_key_composite ( password = None , keyfile = None ) : if password : password_composite = hashlib . sha256 ( password . encode ( 'utf-8' ) ) . digest ( ) else : password_composite = b'' if keyfile : try : with open ( keyfile , 'r' ) as f : tree = etree . parse ( f ) . getroot ( ) keyfile_composite = base64 . ...
Compute composite key . Used in header verification and payload decryption .
245,112
def compute_master ( context ) : 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 .
245,113
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 ) , } , de...
Select stream cipher based on protected_stream_id
245,114
def encrypt ( self , plaintext , n = '' ) : self . ed = 'e' if self . mode == MODE_XTS : return self . chain . update ( plaintext , 'e' , n ) else : return self . chain . update ( plaintext , 'e' )
Encrypt some plaintext
245,115
def decrypt ( self , ciphertext , n = '' ) : self . ed = 'd' if self . mode == MODE_XTS : return self . chain . update ( ciphertext , 'd' , n ) else : return self . chain . update ( ciphertext , 'd' )
Decrypt some ciphertext
245,116
def final ( self , style = 'pkcs7' ) : assert self . mode not in ( MODE_XTS , MODE_CMAC ) if self . ed == b'e' : if self . mode in ( MODE_OFB , MODE_CFB , MODE_CTR ) : dummy = b'0' * ( self . chain . totalbytes % self . blocksize ) else : dummy = self . chain . cache pdata = pad ( dummy , self . blocksize , style = sty...
Finalizes the encryption by padding the cache
245,117
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
245,118
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'...
Convert datetime to base64 or plaintext string
245,119
def _decode_time ( self , text ) : if self . _kp . version >= ( 4 , 0 ) : 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 = { ...
Convert base64 time or plaintext time to datetime
245,120
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 : nrecord...
Load images from a Spark RDD .
245,121
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...
Load images from an array .
245,122
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...
Load images from a list of items using the given accessor .
245,123
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 ) ( engin...
Load images from a path using the given accessor .
245,124
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...
Loads images from single or multi - page TIF files .
245,125
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 ( fbu...
Load images from PNG files .
245,126
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 .
245,127
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 ( pat...
Load example image data .
245,128
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 ...
Reconstitute the chunked array back into a full ndarray .
245,129
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...
Created a chunked array from a full array and a chunk size .
245,130
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 ...
Filter array along an axis .
245,131
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_...
Apply an array - > array function across an axis .
245,132
def _reduce ( self , func , axis = 0 ) : if self . mode == 'local' : axes = sorted ( tupleize ( axis ) ) if isinstance ( func , ufunc ) : inshape ( self . shape , axes ) reduced = func . reduce ( self , axis = tuple ( axes ) ) else : reshaped = self . _align ( axes ) reduced = reduce ( func , reshaped ) expected_shape ...
Reduce an array along an axis .
245,133
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...
Apply an elementwise operation to data .
245,134
def clip ( self , min = None , max = None ) : return self . _constructor ( self . values . clip ( min = min , max = max ) ) . __finalize__ ( self )
Clip values above and below .
245,135
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 ...
Load series data from a Spark RDD .
245,136
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 ind...
Load series data from an array .
245,137
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...
Load series data from a list with an optional accessor function .
245,138
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 , spar...
Loads series data from text files .
245,139
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 ...
Load series data from flat binary files .
245,140
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 . de...
Collects parameters to use for binary series loading .
245,141
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 , dataset...
Load example series data .
245,142
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 ) : firstke...
Writes out data to binary format .
245,143
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 = overwrit...
Write a conf . json file with required information to load Series binary data .
245,144
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_...
Convert to blocks which represent subdivisions of the images data .
245,145
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 (...
Converts to series data .
245,146
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 = eng...
Convert to distributed spark mode .
245,147
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 .
245,148
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 ...
Extract a random sample of images .
245,149
def var ( self ) : return self . _constructor ( self . values . var ( axis = 0 , keepdims = True ) )
Compute the variance across images .
245,150
def std ( self ) : return self . _constructor ( self . values . std ( axis = 0 , keepdims = True ) )
Compute the standard deviation across images .
245,151
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 .
245,152
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 : ...
Compute maximum projections of images along a dimension .
245,153
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 ...
Compute maximum - minimum projection along a dimension .
245,154
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 ( f...
Downsample images by an integer factor .
245,155
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 .
245,156
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_sh...
Generic function for maping a filtering operation over images .
245,157
def localcorr ( self , size = 2 ) : from thunder . images . readers import fromarray , fromrdd from numpy import corrcoef , concatenate nimages = self . shape [ 0 ] blurred = self . uniform_filter ( size ) if self . mode == 'spark' : combined = self . values . concatenate ( blurred . values ) combined_images = fromrdd ...
Correlate every pixel in an image sequence to the average of its local neighborhood .
245,158
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 . valu...
Subtract a constant value or an image from all images .
245,159
def topng ( self , path , prefix = 'image' , overwrite = False ) : from thunder . images . writers import topng topng ( self , path , prefix = prefix , overwrite = overwrite )
Write 2d images as PNG files .
245,160
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 ) retu...
Efficiently apply a function to images as series data .
245,161
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 .
245,162
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
245,163
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
245,164
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 .
245,165
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...
Converts blocks to series .
245,166
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
245,167
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
245,168
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 ....
Convert to spark mode .
245,169
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 :...
Extract random sample of records .
245,170
def map ( self , func , index = None , value_shape = None , dtype = None , with_keys = False ) : 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 , dtyp...
Map an array - > array function over each record .
245,171
def mean ( self ) : return self . _constructor ( self . values . mean ( axis = self . baseaxes , keepdims = True ) )
Compute the mean across records
245,172
def sum ( self ) : return self . _constructor ( self . values . sum ( axis = self . baseaxes , keepdims = True ) )
Compute the sum across records .
245,173
def max ( self ) : return self . _constructor ( self . values . max ( axis = self . baseaxes , keepdims = True ) )
Compute the max across records .
245,174
def min ( self ) : return self . _constructor ( self . values . min ( axis = self . baseaxes , keepdims = True ) )
Compute the min across records .
245,175
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...
Reshape the Series object
245,176
def between ( self , left , right ) : crit = lambda x : left <= x < right return self . select ( crit )
Select subset of values within the given index range .
245,177
def select ( self , crit ) : import types if not isinstance ( crit , types . FunctionType ) : if isinstance ( crit , string_types ) : critlist = set ( [ crit ] ) else : try : critlist = set ( crit ) except TypeError : critlist = set ( [ crit ] ) crit = lambda x : x in critlist index = self . index if size ( index ) == ...
Select subset of values that match a given index criterion .
245,178
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 .
245,179
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 .
245,180
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 .
245,181
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 .
245,182
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 ...
Correlate records against one or many one - dimensional arrays .
245,183
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 .
245,184
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 .
245,185
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 : ...
Internal function for generating masks for selecting values based on multi - index values .
245,186
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 ...
An internal function for maping a function to groups of values based on a multi - index
245,187
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 .
245,188
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 i...
Compute gramian of a distributed matrix .
245,189
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 ]...
Multiply a matrix by another one .
245,190
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 wind...
Make masks used by windowing functions
245,191
def mean_by_window ( self , indices , window ) : masks = self . _makewindows ( indices , window ) newindex = arange ( 0 , len ( masks [ 0 ] ) ) return self . map ( lambda x : mean ( [ x [ m ] for m in masks ] , axis = 0 ) , index = newindex )
Average series across multiple windows specified by their centers .
245,192
def subsample ( self , sample_factor = 2 ) : if sample_factor < 0 : raise Exception ( 'Factor for subsampling must be postive, got %g' % sample_factor ) s = slice ( 0 , len ( self . index ) , sample_factor ) newindex = self . index [ s ] return self . map ( lambda v : v [ s ] , index = newindex )
Subsample series by an integer factor .
245,193
def downsample ( self , sample_factor = 2 ) : if sample_factor < 0 : raise Exception ( 'Factor for subsampling must be postive, got %g' % sample_factor ) newlength = floor ( len ( self . index ) / sample_factor ) func = lambda v : v [ 0 : int ( newlength * sample_factor ) ] . reshape ( - 1 , sample_factor ) . mean ( ax...
Downsample series by an integer factor by averaging .
245,194
def fourier ( self , freq = None ) : def get ( y , freq ) : y = y - mean ( y ) nframes = len ( y ) ft = fft . fft ( y ) ft = ft [ 0 : int ( fix ( nframes / 2 ) ) ] ampFt = 2 * abs ( ft ) / nframes amp = ampFt [ freq ] ampSum = sqrt ( sum ( ampFt ** 2 ) ) co = amp / ampSum ph = - ( pi / 2 ) - angle ( ft [ freq ] ) if ph...
Compute statistics of a Fourier decomposition on series data .
245,195
def convolve ( self , signal , mode = 'full' ) : from numpy import convolve s = asarray ( signal ) n = size ( self . index ) m = size ( s ) if mode == 'same' : newmax = max ( n , m ) elif mode == 'valid' : newmax = max ( m , n ) - min ( m , n ) + 1 else : newmax = n + m - 1 newindex = arange ( 0 , newmax ) return self ...
Convolve series data against another signal .
245,196
def crosscorr ( self , signal , lag = 0 ) : from scipy . linalg import norm s = asarray ( signal ) s = s - mean ( s ) s = s / norm ( s ) if size ( s ) != size ( self . index ) : raise Exception ( 'Size of signal to cross correlate with, %g, ' 'does not match size of series' % size ( s ) ) if lag is not 0 : shifts = ran...
Cross correlate series data against another signal .
245,197
def detrend ( self , method = 'linear' , order = 5 ) : check_options ( method , [ 'linear' , 'nonlinear' ] ) if method == 'linear' : order = 1 def func ( y ) : x = arange ( len ( y ) ) p = polyfit ( x , y , order ) p [ - 1 ] = 0 yy = polyval ( p , x ) return y - yy return self . map ( func )
Detrend series data with linear or nonlinear detrending .
245,198
def normalize ( self , method = 'percentile' , window = None , perc = 20 , offset = 0.1 ) : check_options ( method , [ 'mean' , 'percentile' , 'window' , 'window-exact' ] ) from warnings import warn if not ( method == 'window' or method == 'window-exact' ) and window is not None : warn ( 'Setting window without using m...
Normalize by subtracting and dividing by a baseline .
245,199
def toimages ( self , chunk_size = 'auto' ) : from thunder . images . images import Images if chunk_size is 'auto' : chunk_size = str ( max ( [ int ( 1e5 / prod ( self . baseshape ) ) , 1 ] ) ) n = len ( self . shape ) - 1 if self . mode == 'spark' : return Images ( self . values . swap ( tuple ( range ( n ) ) , ( 0 , ...
Converts to images data .