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 IOError ( 'Invalid URI source for Gstreamer' ) else : raise IOError ( 'Failed getting uri for path %s: no such file' % source ) | 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'' ) : sha1 . update ( chunk ) total_read += chunk_size if total_read > max_file_size : break return sha1 . hexdigest ( ) | 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 ( e ) . count ( 'yaafelib' ) and not _WITH_YAAFE : return elif str ( e ) . count ( 'aubio' ) and not _WITH_AUBIO : return elif str ( e ) . count ( 'DJANGO_SETTINGS_MODULE' ) : return else : print ( name , package ) raise e return name | 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 = font ) textpos = [ im . size [ i ] - textsize [ i ] - margin [ i ] for i in [ 0 , 1 ] ] textdraw . text ( textpos , inputtext , font = font , fill = color ) if opacity != 1 : textlayer = reduce_opacity ( textlayer , opacity ) return Image . composite ( textlayer , im , textlayer ) | 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 not isinstance ( proc , Processor ) : raise TypeError ( 'proc must be a Processor or None' ) if proc . type == 'decoder' and len ( self . processors ) : raise ValueError ( 'Only the first processor in a pipe could be a Decoder' ) if source_proc : for child in self . _graph . neighbors_iter ( source_proc . uuid ( ) ) : child_proc = self . _graph . node [ child ] [ 'processor' ] if proc == child_proc : proc . _uuid = child_proc . uuid ( ) proc . process_pipe = self break if not self . _graph . has_node ( proc . uuid ( ) ) : self . processors . append ( proc ) self . _graph . add_node ( proc . uuid ( ) , processor = proc , id = proc . id ( ) ) if source_proc : self . _graph . add_edge ( self . processors [ 0 ] . uuid ( ) , proc . uuid ( ) , type = 'audio_source' ) proc . process_pipe = self for parent in proc . parents . values ( ) : self . _graph . add_edge ( parent . uuid ( ) , proc . uuid ( ) , type = 'data_source' ) | 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 / 2 : alpha = fft_bin - int ( fft_bin ) self . y_to_bin . append ( ( int ( fft_bin ) , alpha * 255 ) ) | 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_blocksize ) : yield ( self . samples [ index : index + self . output_blocksize ] , False ) yield ( self . samples [ nb_frames * self . output_blocksize : ] , True ) | 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 subinterfaces : for i in subinterfaces : find_implementations ( i , recurse , abstract , result ) | 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 ] , line_color ) else : self . draw . line ( [ x , y1 , x , y2 ] , line_color ) self . draw_anti_aliased_pixels ( x , y1 , y2 , line_color ) self . previous_x , self . previous_y = x , y2 | 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 , x , y1 ) , line_color ) self . draw . line ( ( x , self . image_height , x , y2 ) , line_color ) else : self . draw . line ( ( x , 0 , x , y2 ) , line_color ) self . draw . line ( ( x , self . image_height , x , y1 ) , line_color ) else : self . draw . line ( ( x , 0 , x , self . image_height ) , line_color ) self . draw_anti_aliased_pixels ( x , y1 , y2 , line_color ) self . previous_x , self . previous_y = x , y1 | 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 * color [ 0 ] ) g = int ( ( 1 - alpha ) * current_pix [ 1 ] + alpha * color [ 1 ] ) b = int ( ( 1 - alpha ) * current_pix [ 2 ] + alpha * color [ 2 ] ) self . pixel [ x , y_max_int + 1 ] = ( r , g , b ) y_min = min ( y1 , y2 ) y_min_int = int ( y_min ) alpha = 1.0 - ( y_min - y_min_int ) if alpha > 0.0 and alpha < 1.0 and y_min_int - 1 >= 0 : current_pix = self . pixel [ x , y_min_int - 1 ] r = int ( ( 1 - alpha ) * current_pix [ 0 ] + alpha * color [ 0 ] ) g = int ( ( 1 - alpha ) * current_pix [ 1 ] + alpha * color [ 1 ] ) b = int ( ( 1 - alpha ) * current_pix [ 2 ] + alpha * color [ 2 ] ) self . pixel [ x , y_min_int - 1 ] = ( r , g , b ) | 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 + '"' ) try : id3 . save ( ) except : raise IOError ( 'EncoderError: cannot write tags' ) | 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 opt [ '<path>' ] : print ( handler ( path ) ) else : raise ValueError ( "don't know how to handle cmd" ) | 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 False byte = f . read ( 1 ) f . seek ( - 1 , os . SEEK_CUR ) return hasattr ( byte , 'decode' ) | 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 ( 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 . |
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' , None ) ) : 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 . |
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 ( mod_name ) return mod | 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 : 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 . |
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 backend_from_mime ( mime ) finally : f . seek ( offset ) | 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 ( ** 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 . |
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 , 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 . |
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 = onerror ) else : safe_print ( "rm %s" % path ) os . remove ( path ) | 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 ( "htmlcov" ) rm ( "tmp" ) rm ( "venv" ) | 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 ) + 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 . |
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 = block [ 16 : ] return plaintext | 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 = block [ 16 : ] return ciphertext | 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 hashlib . sha256 ( transformed_key ) . digest ( ) | 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 . b64decode ( tree . find ( 'Key/Data' ) . text ) 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 len ( key ) == 32 : keyfile_composite = key elif len ( key ) == 64 and is_hex : keyfile_composite = codecs . decode ( key , 'hex' ) else : keyfile_composite = hashlib . sha256 ( key ) . digest ( ) except : raise IOError ( 'Could not read keyfile' ) else : keyfile_composite = b'' return hashlib . sha256 ( password_composite + keyfile_composite ) . digest ( ) | 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 ) , } , default = subcon ) | 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 = style ) [ len ( dummy ) : ] return self . chain . update ( pdata , b'e' ) else : pass | 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' ) else : return self . _datetime_to_utc ( value ) . isoformat ( ) | 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 = { 'UTC' : tz . gettz ( 'UTC' ) } ) else : return parser . parse ( text , tzinfos = { 'UTC' : tz . gettz ( 'UTC' ) } ) | 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 : 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 . |
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 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 . |
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 , 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 . |
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 ) ( 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 . |
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 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 . |
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 ( 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 . |
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 ( 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 . |
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 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 . |
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 : 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 . |
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 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 . |
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_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 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 . |
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 = [ 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 . |
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 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 . |
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 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 . |
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 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 . |
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 , ) , 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 . |
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 , 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 . |
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 = 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 . |
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 . 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 . |
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 , 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 . |
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 ) : 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 . |
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 = 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 . |
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_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 . |
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 ( ( 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 . |
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 = engine ) | 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 , 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 . |
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 : amax ( x , axis ) , value_shape = new_value_shape ) | 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 x : amax ( x , axis ) + amin ( x , axis ) , value_shape = new_value_shape ) | 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 ( 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 . |
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_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 . |
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 ( combined . tordd ( ) ) else : combined = concatenate ( ( self . values , blurred . values ) , axis = 0 ) combined_images = fromarray ( combined ) 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 . |
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 . value_shape ) | 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 ) return blocks . map ( f , value_shape = dims , dtype = dtype ) . toimages ( ) | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.