idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
56,200
def get_uri ( self ) : if self . source_file and os . path . exists ( self . source_file . path ) : return self . source_file . path elif self . source_url : return self . source_url return None
Return the Item source
56,201
def get_audio_duration ( self ) : decoder = timeside . core . get_processor ( 'file_decoder' ) ( uri = self . get_uri ( ) ) return decoder . uri_total_duration
Return item audio duration
56,202
def get_results_path ( self ) : result_path = os . path . join ( RESULTS_ROOT , self . uuid ) if not os . path . exists ( result_path ) : os . makedirs ( result_path ) return result_path
Return Item result path
56,203
def get_uri ( source ) : import gst src_info = source_info ( source ) if src_info [ 'is_file' ] : return get_uri ( src_info [ 'uri' ] ) elif gst . uri_is_valid ( source ) : uri_protocol = gst . uri_get_protocol ( source ) if gst . uri_protocol_is_supported ( gst . URI_SRC , uri_protocol ) : return source else : raise I...
Check a media source as a valid file or uri and return the proper uri
56,204
def sha1sum_file ( filename ) : import hashlib import io sha1 = hashlib . sha1 ( ) chunk_size = sha1 . block_size * io . DEFAULT_BUFFER_SIZE with open ( filename , 'rb' ) as f : for chunk in iter ( lambda : f . read ( chunk_size ) , b'' ) : sha1 . update ( chunk ) return sha1 . hexdigest ( )
Return the secure hash digest with sha1 algorithm for a given file
56,205
def sha1sum_url ( url ) : import hashlib import urllib from contextlib import closing sha1 = hashlib . sha1 ( ) chunk_size = sha1 . block_size * 8192 max_file_size = 10 * 1024 * 1024 total_read = 0 with closing ( urllib . urlopen ( url ) ) as url_obj : for chunk in iter ( lambda : url_obj . read ( chunk_size ) , b'' ) ...
Return the secure hash digest with sha1 algorithm for a given url
56,206
def sha1sum_numpy ( np_array ) : import hashlib return hashlib . sha1 ( np_array . view ( np . uint8 ) ) . hexdigest ( )
Return the secure hash digest with sha1 algorithm for a numpy array
56,207
def import_module_with_exceptions ( name , package = None ) : from timeside . core import _WITH_AUBIO , _WITH_YAAFE , _WITH_VAMP if name . count ( '.server.' ) : return try : import_module ( name , package ) except VampImportError : if _WITH_VAMP : raise VampImportError else : return except ImportError as e : if str ( ...
Wrapper around importlib . import_module to import TimeSide subpackage and ignoring ImportError if Aubio Yaafe and Vamp Host are not available
56,208
def check_vamp ( ) : "Check Vamp host availability" try : from timeside . plugins . analyzer . externals import vamp_plugin except VampImportError : warnings . warn ( 'Vamp host is not available' , ImportWarning , stacklevel = 2 ) _WITH_VAMP = False else : _WITH_VAMP = True del vamp_plugin return _WITH_VAMP
Check Vamp host availability
56,209
def im_watermark ( im , inputtext , font = None , color = None , opacity = .6 , margin = ( 30 , 30 ) ) : if im . mode != "RGBA" : im = im . convert ( "RGBA" ) textlayer = Image . new ( "RGBA" , im . size , ( 0 , 0 , 0 , 0 ) ) textdraw = ImageDraw . Draw ( textlayer ) textsize = textdraw . textsize ( inputtext , font = ...
imprints a PIL image with the indicated text in lower - right corner
56,210
def nextpow2 ( value ) : if value >= 1 : return 2 ** np . ceil ( np . log2 ( value ) ) . astype ( int ) elif value > 0 : return 1 elif value == 0 : return 0 else : raise ValueError ( 'Value must be positive' )
Compute the nearest power of two greater or equal to the input value
56,211
def blocksize ( self , input_totalframes ) : blocksize = input_totalframes if self . pad : mod = input_totalframes % self . buffer_size if mod : blocksize += self . buffer_size - mod return blocksize
Return the total number of frames that this adapter will output according to the input_totalframes argument
56,212
def append_processor ( self , proc , source_proc = None ) : "Append a new processor to the pipe" if source_proc is None and len ( self . processors ) : source_proc = self . processors [ 0 ] if source_proc and not isinstance ( source_proc , Processor ) : raise TypeError ( 'source_proc must be a Processor or None' ) if n...
Append a new processor to the pipe
56,213
def simple_host_process ( argslist ) : vamp_host = 'vamp-simple-host' command = [ vamp_host ] command . extend ( argslist ) stdout = subprocess . check_output ( command , stderr = subprocess . STDOUT ) . splitlines ( ) return stdout
Call vamp - simple - host
56,214
def set_scale ( self ) : f_min = float ( self . lower_freq ) f_max = float ( self . higher_freq ) y_min = f_min y_max = f_max for y in range ( self . image_height ) : freq = y_min + y / ( self . image_height - 1.0 ) * ( y_max - y_min ) fft_bin = freq / f_max * ( self . fft_size / 2 + 1 ) if fft_bin < self . fft_size / ...
generate the lookup which translates y - coordinate to fft - bin
56,215
def dict_from_hdf5 ( dict_like , h5group ) : for name , value in h5group . attrs . items ( ) : dict_like [ name ] = value
Load a dictionnary - like object from a h5 file group
56,216
def get_frames ( self ) : "Define an iterator that will return frames at the given blocksize" nb_frames = self . input_totalframes // self . output_blocksize if self . input_totalframes % self . output_blocksize == 0 : nb_frames -= 1 for index in xrange ( 0 , nb_frames * self . output_blocksize , self . output_blocksiz...
Define an iterator that will return frames at the given blocksize
56,217
def implementations ( interface , recurse = True , abstract = False ) : result = [ ] find_implementations ( interface , recurse , abstract , result ) return result
Returns the components implementing interface and if recurse any of the descendants of interface . If abstract is True also return the abstract implementations .
56,218
def find_implementations ( interface , recurse , abstract , result ) : for item in MetaComponent . implementations : if ( item [ 'interface' ] == interface and ( abstract or not item [ 'abstract' ] ) ) : extend_unique ( result , [ item [ 'class' ] ] ) if recurse : subinterfaces = interface . __subclasses__ ( ) if subin...
Find implementations of an interface or of one of its descendants and extend result with the classes found .
56,219
def draw_peaks ( self , x , peaks , line_color ) : y1 = self . image_height * 0.5 - peaks [ 0 ] * ( self . image_height - 4 ) * 0.5 y2 = self . image_height * 0.5 - peaks [ 1 ] * ( self . image_height - 4 ) * 0.5 if self . previous_y : self . draw . line ( [ self . previous_x , self . previous_y , x , y1 , x , y2 ] , l...
Draw 2 peaks at x
56,220
def draw_peaks_inverted ( self , x , peaks , line_color ) : y1 = self . image_height * 0.5 - peaks [ 0 ] * ( self . image_height - 4 ) * 0.5 y2 = self . image_height * 0.5 - peaks [ 1 ] * ( self . image_height - 4 ) * 0.5 if self . previous_y and x < self . image_width - 1 : if y1 < y2 : self . draw . line ( ( x , 0 , ...
Draw 2 inverted peaks at x
56,221
def draw_anti_aliased_pixels ( self , x , y1 , y2 , color ) : y_max = max ( y1 , y2 ) y_max_int = int ( y_max ) alpha = y_max - y_max_int if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self . image_height : current_pix = self . pixel [ int ( x ) , y_max_int + 1 ] r = int ( ( 1 - alpha ) * current_pix [ 0 ] + alpha ...
vertical anti - aliasing at y1 and y2
56,222
def post_process ( self ) : self . image . putdata ( self . pixels ) self . image = self . image . transpose ( Image . ROTATE_90 )
Apply last 2D transforms
56,223
def write_metadata ( self ) : import mutagen from mutagen import id3 id3 = id3 . ID3 ( self . filename ) for tag in self . metadata . keys ( ) : value = self . metadata [ tag ] frame = mutagen . id3 . Frames [ tag ] ( 3 , value ) try : id3 . add ( frame ) except : raise IOError ( 'EncoderError: cannot tag "' + tag + '"...
Write all ID3v2 . 4 tags to file from self . metadata
56,224
def main ( args = sys . argv [ 1 : ] ) : opt = docopt ( main . __doc__ . strip ( ) , args , options_first = True ) config_logging ( opt [ '--verbose' ] ) if opt [ 'check' ] : check_backends ( opt [ '--title' ] ) elif opt [ 'extract' ] : handler = fulltext . get if opt [ '--file' ] : handler = _handle_open for path in o...
Extract text from a file .
56,225
def is_binary ( f ) : if getattr ( f , "encoding" , None ) : return False if not PY3 : return True try : if 'b' in getattr ( f , 'mode' , '' ) : return True except TypeError : import gzip if isinstance ( f , gzip . GzipFile ) : return True raise try : f . seek ( 0 , os . SEEK_CUR ) except ( AttributeError , IOError ) :...
Return True if binary mode .
56,226
def handle_path ( backend_inst , path , ** kwargs ) : if callable ( getattr ( backend_inst , 'handle_path' , None ) ) : LOGGER . debug ( "using handle_path" ) return backend_inst . handle_path ( path ) elif callable ( getattr ( backend_inst , 'handle_fobj' , None ) ) : LOGGER . debug ( "using handle_fobj" ) with open (...
Handle a path .
56,227
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 ) ) : LOGGER . debug ( "using handle_fobj" ) return backend . handle_fobj ( f ) elif callable ( getattr ( backend , 'handle_path' ,...
Handle a file - like object .
56,228
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 ( m...
Determine backend module object from a mime string .
56,229
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 : if e . errno != errno . ENOENT : raise msg = "No handler for %r, defaulting to %r" % ( ext , DEFAULT_MIME ) if 'FULLTEXT_TESTING' in os . environ ...
Determine backend module object from a file name .
56,230
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 ba...
Determine backend module object from a file object .
56,231
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 ( ** ...
Given a mod and a set of opts return an instantiated Backend class .
56,232
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 ,...
Get document full text .
56,233
def hilite ( s , ok = True , bold = False ) : if not term_supports_colors ( ) : return s attr = [ ] if ok is None : pass elif ok : attr . append ( '32' ) else : attr . append ( '31' ) if bold : attr . append ( '1' ) return '\x1b[%sm%s\x1b[0m' % ( ';' . join ( attr ) , s )
Return an highlighted version of string .
56,234
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 .
56,235
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 .
56,236
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
56,237
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
56,238
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
56,239
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 .
56,240
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 .
56,241
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 .
56,242
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 .
56,243
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 .
56,244
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 .
56,245
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
56,246
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 .
56,247
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 .
56,248
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
56,249
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
56,250
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
56,251
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
56,252
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
56,253
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
56,254
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
56,255
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 .
56,256
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 .
56,257
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 .
56,258
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 .
56,259
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 .
56,260
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 .
56,261
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 .
56,262
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 .
56,263
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 .
56,264
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 .
56,265
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 .
56,266
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 .
56,267
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 .
56,268
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 .
56,269
def clip ( self , min = None , max = None ) : return self . _constructor ( self . values . clip ( min = min , max = max ) ) . __finalize__ ( self )
Clip values above and below .
56,270
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 .
56,271
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 .
56,272
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 .
56,273
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 .
56,274
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 .
56,275
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 .
56,276
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 .
56,277
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 .
56,278
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 .
56,279
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 .
56,280
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 .
56,281
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 .
56,282
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 .
56,283
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 .
56,284
def var ( self ) : return self . _constructor ( self . values . var ( axis = 0 , keepdims = True ) )
Compute the variance across images .
56,285
def std ( self ) : return self . _constructor ( self . values . std ( axis = 0 , keepdims = True ) )
Compute the standard deviation across images .
56,286
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,287
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 .
56,288
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 .
56,289
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 .
56,290
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 .
56,291
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 .
56,292
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 .
56,293
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 .
56,294
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 .
56,295
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 .
56,296
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 .
56,297
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
56,298
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
56,299
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 .