idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
59,000 | def xfmsta ( input_state , input_coord_sys , output_coord_sys , body ) : input_state = stypes . toDoubleVector ( input_state ) input_coord_sys = stypes . stringToCharP ( input_coord_sys ) output_coord_sys = stypes . stringToCharP ( output_coord_sys ) body = stypes . stringToCharP ( body ) output_state = stypes . emptyD... | Transform a state between coordinate systems . |
59,001 | def xpose ( m ) : m = stypes . toDoubleMatrix ( m ) mout = stypes . emptyDoubleMatrix ( x = 3 , y = 3 ) libspice . xpose_c ( m , mout ) return stypes . cMatrixToNumpy ( mout ) | Transpose a 3x3 matrix |
59,002 | def xpose6 ( m ) : m = stypes . toDoubleMatrix ( m ) mout = stypes . emptyDoubleMatrix ( x = 6 , y = 6 ) libspice . xpose6_c ( m , mout ) return stypes . cMatrixToNumpy ( mout ) | Transpose a 6x6 matrix |
59,003 | def xposeg ( matrix , nrow , ncol ) : matrix = stypes . toDoubleMatrix ( matrix ) mout = stypes . emptyDoubleMatrix ( x = ncol , y = nrow ) ncol = ctypes . c_int ( ncol ) nrow = ctypes . c_int ( nrow ) libspice . xposeg_c ( matrix , nrow , ncol , mout ) return stypes . cMatrixToNumpy ( mout ) | Transpose a matrix of arbitrary size in place the matrix need not be square . |
59,004 | def CallUDFUNS ( f , x ) : value = c_double ( ) f ( x , byref ( value ) ) return value . value | We are given a UDF CFUNCTYPE and want to call it in python |
59,005 | def updateD_G ( self , x ) : self . precompute ( x ) g = zeros ( len ( x ) ) Ai = zeros ( self . A . shape [ 0 ] ) for i in range ( len ( g ) ) : Ai = self . A [ : , i ] g [ i ] = ( self . E * ( dot ( self . AD , outer ( self . R [ : , i ] , Ai ) ) + dot ( outer ( Ai , self . R [ i , : ] ) , self . ADt ) ) ) . sum ( ) ... | Compute Gradient for update of D |
59,006 | def updateD_H ( self , x ) : self . precompute ( x ) H = zeros ( ( len ( x ) , len ( x ) ) ) Ai = zeros ( self . A . shape [ 0 ] ) Aj = zeros ( Ai . shape ) for i in range ( len ( x ) ) : Ai = self . A [ : , i ] ti = dot ( self . AD , outer ( self . R [ : , i ] , Ai ) ) + dot ( outer ( Ai , self . R [ i , : ] ) , self ... | Compute Hessian for update of D |
59,007 | def is_sequence ( obj ) : try : from collections import Sequence except ImportError : from operator import isSequenceType return isSequenceType ( obj ) else : return isinstance ( obj , Sequence ) | Helper function to determine sequences across Python 2 . x and 3 . x |
59,008 | def is_number ( obj ) : try : from numbers import Number except ImportError : from operator import isNumberType return isNumberType ( obj ) else : return isinstance ( obj , Number ) | Helper function to determine numbers across Python 2 . x and 3 . x |
59,009 | def func_attr ( f , attr ) : if hasattr ( f , 'func_%s' % attr ) : return getattr ( f , 'func_%s' % attr ) elif hasattr ( f , '__%s__' % attr ) : return getattr ( f , '__%s__' % attr ) else : raise ValueError ( 'Object %s has no attr' % ( str ( f ) , attr ) ) | Helper function to get the attribute of a function like name code defaults across Python 2 . x and 3 . x |
59,010 | def from_to_without ( frm , to , without , step = 1 , skip = 1 , reverse = False , separate = False ) : if reverse : frm , to = ( to - 1 ) , ( frm - 1 ) step *= - 1 skip *= - 1 a = list ( range ( frm , without , step ) ) b = list ( range ( without + skip , to , step ) ) if separate : return a , b else : return a + b | Helper function to create ranges with missing entries |
59,011 | def unfold ( self , mode ) : sz = array ( self . shape ) N = len ( sz ) order = ( [ mode ] , from_to_without ( N - 1 , - 1 , mode , step = - 1 , skip = - 1 ) ) newsz = ( sz [ order [ 0 ] ] [ 0 ] , prod ( sz [ order [ 1 ] ] ) ) arr = self . transpose ( axes = ( order [ 0 ] + order [ 1 ] ) ) arr = arr . reshape ( newsz )... | Unfolds a dense tensor in mode n . |
59,012 | def accum ( subs , vals , func = np . sum , issorted = False , with_subs = False ) : if not issorted : sidx = lexsort ( subs , axis = 0 ) subs = [ sub [ sidx ] for sub in subs ] vals = vals [ sidx ] idx = np . where ( np . diff ( subs ) . any ( axis = 0 ) ) [ 0 ] + 1 idx = np . concatenate ( ( [ 0 ] , idx , [ subs [ 0 ... | NumPy implementation for Matlab s accumarray |
59,013 | def hooi ( X , rank , ** kwargs ) : ainit = kwargs . pop ( 'init' , __DEF_INIT ) maxIter = kwargs . pop ( 'maxIter' , __DEF_MAXITER ) conv = kwargs . pop ( 'conv' , __DEF_CONV ) dtype = kwargs . pop ( 'dtype' , X . dtype ) if not len ( kwargs ) == 0 : raise ValueError ( 'Unknown keywords (%s)' % ( kwargs . keys ( ) ) )... | Compute Tucker decomposition of a tensor using Higher - Order Orthogonal Iterations . |
59,014 | def uttkrp ( self , U , mode ) : N = self . ndim if mode == 1 : R = U [ 1 ] . shape [ 1 ] else : R = U [ 0 ] . shape [ 1 ] W = np . tile ( self . lmbda , 1 , R ) for i in range ( mode ) + range ( mode + 1 , N ) : W = W * dot ( self . U [ i ] . T , U [ i ] ) return dot ( self . U [ mode ] , W ) | Unfolded tensor times Khatri - Rao product for Kruskal tensors |
59,015 | def norm ( self ) : N = len ( self . shape ) coef = outer ( self . lmbda , self . lmbda ) for i in range ( N ) : coef = coef * dot ( self . U [ i ] . T , self . U [ i ] ) return np . sqrt ( coef . sum ( ) ) | Efficient computation of the Frobenius norm for ktensors |
59,016 | def innerprod ( self , X ) : N = len ( self . shape ) R = len ( self . lmbda ) res = 0 for r in range ( R ) : vecs = [ ] for n in range ( N ) : vecs . append ( self . U [ n ] [ : , r ] ) res += self . lmbda [ r ] * X . ttv ( tuple ( vecs ) ) return res | Efficient computation of the inner product of a ktensor with another tensor |
59,017 | def toarray ( self ) : A = dot ( self . lmbda , khatrirao ( tuple ( self . U ) ) . T ) return A . reshape ( self . shape ) | Converts a ktensor into a dense multidimensional ndarray |
59,018 | def fromarray ( A ) : subs = np . nonzero ( A ) vals = A [ subs ] return sptensor ( subs , vals , shape = A . shape , dtype = A . dtype ) | Create a sptensor from a dense numpy array |
59,019 | def _ttm_me_compute ( self , V , edims , sdims , transp ) : shapeY = np . copy ( self . shape ) for n in np . union1d ( edims , sdims ) : shapeY [ n ] = V [ n ] . shape [ 1 ] if transp else V [ n ] . shape [ 0 ] Y = zeros ( shapeY ) shapeY = array ( shapeY ) v = [ None for _ in range ( len ( edims ) ) ] for i in range ... | Assume Y = T x_i V_i for i = 1 ... n can fit into memory |
59,020 | def transpose ( self , axes = None ) : if axes is None : raise NotImplementedError ( 'Sparse tensor transposition without axes argument is not supported' ) nsubs = tuple ( [ self . subs [ idx ] for idx in axes ] ) nshape = [ self . shape [ idx ] for idx in axes ] return sptensor ( nsubs , self . vals , nshape ) | Compute transpose of sparse tensors . |
59,021 | def concatenate ( self , tpl , axis = None ) : if axis is None : raise NotImplementedError ( 'Sparse tensor concatenation without axis argument is not supported' ) T = self for i in range ( 1 , len ( tpl ) ) : T = _single_concatenate ( T , tpl [ i ] , axis = axis ) return T | Concatenates sparse tensors . |
59,022 | def fold ( self ) : nsubs = zeros ( ( len ( self . data ) , len ( self . ten_shape ) ) , dtype = np . int ) if len ( self . rdims ) > 0 : nidx = unravel_index ( self . row , self . ten_shape [ self . rdims ] ) for i in range ( len ( self . rdims ) ) : nsubs [ : , self . rdims [ i ] ] = nidx [ i ] if len ( self . cdims ... | Recreate original tensor by folding unfolded_sptensor according toc ten_shape . |
59,023 | def _updateA ( X , A , R , P , Z , lmbdaA , orthogonalize ) : n , rank = A . shape F = zeros ( ( n , rank ) , dtype = A . dtype ) E = zeros ( ( rank , rank ) , dtype = A . dtype ) AtA = dot ( A . T , A ) for i in range ( len ( X ) ) : F += X [ i ] . dot ( dot ( A , R [ i ] . T ) ) + X [ i ] . T . dot ( dot ( A , R [ i ... | Update step for A |
59,024 | def _compute_fval ( X , A , R , P , Z , lmbdaA , lmbdaR , lmbdaZ , normX ) : f = lmbdaA * norm ( A ) ** 2 for i in range ( len ( X ) ) : ARAt = dot ( A , dot ( R [ i ] , A . T ) ) f += ( norm ( X [ i ] - ARAt ) ** 2 ) / normX [ i ] + lmbdaR * norm ( R [ i ] ) ** 2 return f | Compute fit for full slices |
59,025 | def als ( X , rank , ** kwargs ) : ainit = kwargs . pop ( 'init' , _DEF_INIT ) maxiter = kwargs . pop ( 'max_iter' , _DEF_MAXITER ) fit_method = kwargs . pop ( 'fit_method' , _DEF_FIT_METHOD ) conv = kwargs . pop ( 'conv' , _DEF_CONV ) dtype = kwargs . pop ( 'dtype' , _DEF_TYPE ) if not len ( kwargs ) == 0 : raise Valu... | Alternating least - sqaures algorithm to compute the CP decomposition . |
59,026 | def _init ( init , X , N , rank , dtype ) : Uinit = [ None for _ in range ( N ) ] if isinstance ( init , list ) : Uinit = init elif init == 'random' : for n in range ( 1 , N ) : Uinit [ n ] = array ( rand ( X . shape [ n ] , rank ) , dtype = dtype ) elif init == 'nvecs' : for n in range ( 1 , N ) : Uinit [ n ] = array ... | Initialization for CP models |
59,027 | def nvecs ( X , n , rank , do_flipsign = True , dtype = np . float ) : Xn = X . unfold ( n ) if issparse_mat ( Xn ) : Xn = csr_matrix ( Xn , dtype = dtype ) Y = Xn . dot ( Xn . T ) _ , U = eigsh ( Y , rank , which = 'LM' ) else : Y = Xn . dot ( Xn . T ) N = Y . shape [ 0 ] _ , U = eigh ( Y , eigvals = ( N - rank , N - ... | Eigendecomposition of mode - n unfolding of a tensor |
59,028 | def flipsign ( U ) : midx = abs ( U ) . argmax ( axis = 0 ) for i in range ( U . shape [ 1 ] ) : if U [ midx [ i ] , i ] < 0 : U [ : , i ] = - U [ : , i ] return U | Flip sign of factor matrices such that largest magnitude element will be positive |
59,029 | def khatrirao ( A , reverse = False ) : if not isinstance ( A , tuple ) : raise ValueError ( 'A must be a tuple of array likes' ) N = A [ 0 ] . shape [ 1 ] M = 1 for i in range ( len ( A ) ) : if A [ i ] . ndim != 2 : raise ValueError ( 'A must be a tuple of matrices (A[%d].ndim = %d)' % ( i , A [ i ] . ndim ) ) elif N... | Compute the columnwise Khatri - Rao product . |
59,030 | def teneye ( dim , order ) : I = zeros ( dim ** order ) for f in range ( dim ) : idd = f for i in range ( 1 , order ) : idd = idd + dim ** ( i - 1 ) * ( f - 1 ) I [ idd ] = 1 return I . reshape ( ones ( order ) * dim ) | Create tensor with superdiagonal all one rest zeros |
59,031 | def ttm ( self , V , mode = None , transp = False , without = False ) : if mode is None : mode = range ( self . ndim ) if isinstance ( V , np . ndarray ) : Y = self . _ttm_compute ( V , mode , transp ) elif is_sequence ( V ) : dims , vidx = check_multiplication_dims ( mode , self . ndim , len ( V ) , vidx = True , with... | Tensor times matrix product |
59,032 | def _process_registry ( registry , call_func ) : from django . core . exceptions import ImproperlyConfigured from django . apps import apps for key , value in list ( registry . items ( ) ) : model = apps . get_model ( * key . split ( '.' ) ) if model is None : raise ImproperlyConfigured ( _ ( '%(key)s is not a model' )... | Given a dictionary and a registration function process the registry |
59,033 | def field_exists ( app_name , model_name , field_name ) : model = apps . get_model ( app_name , model_name ) table_name = model . _meta . db_table cursor = connection . cursor ( ) field_info = connection . introspection . get_table_description ( cursor , table_name ) field_names = [ f . name for f in field_info ] retur... | Does the FK or M2M table exist in the database already? |
59,034 | def drop_field ( app_name , model_name , field_name ) : app_config = apps . get_app_config ( app_name ) model = app_config . get_model ( model_name ) field = model . _meta . get_field ( field_name ) with connection . schema_editor ( ) as schema_editor : schema_editor . remove_field ( model , field ) | Drop the given field from the app s model |
59,035 | def migrate_app ( sender , * args , ** kwargs ) : from . registration import registry if 'app_config' not in kwargs : return app_config = kwargs [ 'app_config' ] app_name = app_config . label fields = [ fld for fld in list ( registry . _field_registry . keys ( ) ) if fld . startswith ( app_name ) ] sid = transaction . ... | Migrate all models of this app registered |
59,036 | def get_absolute_url ( self ) : from django . urls import NoReverseMatch if self . alternate_url : return self . alternate_url try : prefix = reverse ( 'categories_tree_list' ) except NoReverseMatch : prefix = '/' ancestors = list ( self . get_ancestors ( ) ) + [ self , ] return prefix + '/' . join ( [ force_text ( i .... | Return a path |
59,037 | def get_content_type ( self , content_type ) : qs = self . get_queryset ( ) return qs . filter ( content_type__name = content_type ) | Get all the items of the given content type related to this item . |
59,038 | def get_relation_type ( self , relation_type ) : qs = self . get_queryset ( ) return qs . filter ( relation_type = relation_type ) | Get all the items of the given relationship type related to this item . |
59,039 | def handle_class_prepared ( sender , ** kwargs ) : from . settings import M2M_REGISTRY , FK_REGISTRY from . registration import registry sender_app = sender . _meta . app_label sender_name = sender . _meta . model_name for key , val in list ( FK_REGISTRY . items ( ) ) : app_name , model_name = key . split ( '.' ) if ap... | See if this class needs registering of fields |
59,040 | def get_queryset ( self , request ) : qs = self . model . _default_manager . get_queryset ( ) qs . __class__ = TreeEditorQuerySet return qs | Returns a QuerySet of all model instances that can be edited by the admin site . This is used by changelist_view . |
59,041 | def deactivate ( self , request , queryset ) : selected_cats = self . model . objects . filter ( pk__in = [ int ( x ) for x in request . POST . getlist ( '_selected_action' ) ] ) for item in selected_cats : if item . active : item . active = False item . save ( ) item . children . all ( ) . update ( active = False ) | Set active to False for selected items |
59,042 | def get_indent ( self , string ) : indent_amt = 0 if string [ 0 ] == '\t' : return '\t' for char in string : if char == ' ' : indent_amt += 1 else : return ' ' * indent_amt | Look through the string and count the spaces |
59,043 | def make_category ( self , string , parent = None , order = 1 ) : cat = Category ( name = string . strip ( ) , slug = slugify ( SLUG_TRANSLITERATOR ( string . strip ( ) ) ) [ : 49 ] , order = order ) cat . _tree_manager . insert_node ( cat , parent , 'last-child' , True ) cat . save ( ) if parent : parent . rght = cat ... | Make and save a category object from a string |
59,044 | def parse_lines ( self , lines ) : indent = '' level = 0 if lines [ 0 ] [ 0 ] == ' ' or lines [ 0 ] [ 0 ] == '\t' : raise CommandError ( "The first line in the file cannot start with a space or tab." ) current_parents = { 0 : None } for line in lines : if len ( line ) == 0 : continue if line [ 0 ] == ' ' or line [ 0 ] ... | Do the work of parsing each line |
59,045 | def handle ( self , * file_paths , ** options ) : import os for file_path in file_paths : if not os . path . isfile ( file_path ) : print ( "File %s not found." % file_path ) continue f = open ( file_path , 'r' ) data = f . readlines ( ) f . close ( ) self . parse_lines ( data ) | Handle the basic import |
59,046 | def get_cat_model ( model ) : try : if isinstance ( model , string_types ) : model_class = apps . get_model ( * model . split ( "." ) ) elif issubclass ( model , CategoryBase ) : model_class = model if model_class is None : raise TypeError except TypeError : raise TemplateSyntaxError ( "Unknown model submitted: %s" % m... | Return a class from a string or class |
59,047 | def get_category ( category_string , model = Category ) : model_class = get_cat_model ( model ) category = str ( category_string ) . strip ( "'\"" ) category = category . strip ( '/' ) cat_list = category . split ( '/' ) if len ( cat_list ) == 0 : return None try : categories = model_class . objects . filter ( name = c... | Convert a string including a path and return the Category object |
59,048 | def get_category_drilldown ( parser , token ) : bits = token . split_contents ( ) error_str = '%(tagname)s tag should be in the format {%% %(tagname)s ' '"category name" [using "app.Model"] as varname %%} or ' '{%% %(tagname)s category_obj as varname %%}.' if len ( bits ) == 4 : if bits [ 2 ] != 'as' : raise template .... | Retrieves the specified category its ancestors and its immediate children as an iterable . |
59,049 | def get_top_level_categories ( parser , token ) : bits = token . split_contents ( ) usage = 'Usage: {%% %s [using "app.Model"] as <variable> %%}' % bits [ 0 ] if len ( bits ) == 3 : if bits [ 1 ] != 'as' : raise template . TemplateSyntaxError ( usage ) varname = bits [ 2 ] model = "categories.category" elif len ( bits ... | Retrieves an alphabetical list of all the categories that have no parents . |
59,050 | def tree_queryset ( value ) : from django . db . models . query import QuerySet from copy import deepcopy if not isinstance ( value , QuerySet ) : return value qs = value qs2 = deepcopy ( qs ) is_filtered = bool ( qs . query . where . children ) if is_filtered : include_pages = set ( ) for p in qs2 . order_by ( 'rght' ... | Converts a normal queryset from an MPTT model to include all the ancestors so a filtered subset of items can be formatted correctly |
59,051 | def convolve ( data , h , res_g = None , sub_blocks = None ) : if not len ( data . shape ) in [ 1 , 2 , 3 ] : raise ValueError ( "dim = %s not supported" % ( len ( data . shape ) ) ) if len ( data . shape ) != len ( h . shape ) : raise ValueError ( "dimemnsion of data (%s) and h (%s) are different" % ( len ( data . sha... | convolves 1d - 3d data with kernel h |
59,052 | def _convolve3_old ( data , h , dev = None ) : if dev is None : dev = get_device ( ) if dev is None : raise ValueError ( "no OpenCLDevice found..." ) dtype = data . dtype . type dtypes_options = { np . float32 : "" , np . uint16 : "-D SHORTTYPE" } if not dtype in dtypes_options : raise TypeError ( "data type %s not sup... | convolves 3d data with kernel h on the GPU Device dev boundary conditions are clamping to edge . h is converted to float32 |
59,053 | def _scale_shape ( dshape , scale = ( 1 , 1 , 1 ) ) : nshape = np . round ( np . array ( dshape ) * np . array ( scale ) ) return tuple ( nshape . astype ( np . int ) ) | returns the shape after scaling ( should be the same as ndimage . zoom |
59,054 | def fftshift ( arr_obj , axes = None , res_g = None , return_buffer = False ) : if axes is None : axes = list ( range ( arr_obj . ndim ) ) if isinstance ( arr_obj , OCLArray ) : if not arr_obj . dtype . type in DTYPE_KERNEL_NAMES : raise NotImplementedError ( "only works for float32 or complex64" ) elif isinstance ( ar... | gpu version of fftshift for numpy arrays or OCLArrays |
59,055 | def _fftshift_single ( d_g , res_g , ax = 0 ) : dtype_kernel_name = { np . float32 : "fftshift_1_f" , np . complex64 : "fftshift_1_c" } N = d_g . shape [ ax ] N1 = 1 if ax == 0 else np . prod ( d_g . shape [ : ax ] ) N2 = 1 if ax == len ( d_g . shape ) - 1 else np . prod ( d_g . shape [ ax + 1 : ] ) dtype = d_g . dtype... | basic fftshift of an OCLArray |
59,056 | def fft_convolve ( data , h , res_g = None , plan = None , inplace = False , kernel_is_fft = False , kernel_is_fftshifted = False ) : if isinstance ( data , np . ndarray ) : return _fft_convolve_numpy ( data , h , plan = plan , kernel_is_fft = kernel_is_fft , kernel_is_fftshifted = kernel_is_fftshifted ) elif isinstanc... | convolves data with kernel h via FFTs |
59,057 | def _fft_convolve_numpy ( data , h , plan = None , kernel_is_fft = False , kernel_is_fftshifted = False ) : if data . shape != h . shape : raise ValueError ( "data and kernel must have same size! %s vs %s " % ( str ( data . shape ) , str ( h . shape ) ) ) data_g = OCLArray . from_array ( data . astype ( np . complex64 ... | convolving via opencl fft for numpy arrays |
59,058 | def _fft_convolve_gpu ( data_g , h_g , res_g = None , plan = None , inplace = False , kernel_is_fft = False ) : assert_bufs_type ( np . complex64 , data_g , h_g ) if data_g . shape != h_g . shape : raise ValueError ( "data and kernel must have same size! %s vs %s " % ( str ( data_g . shape ) , str ( h_g . shape ) ) ) i... | fft convolve for gpu buffer |
59,059 | def median_filter ( data , size = 3 , cval = 0 , res_g = None , sub_blocks = None ) : if data . ndim == 2 : _filt = make_filter ( _median_filter_gpu_2d ( ) ) elif data . ndim == 3 : _filt = make_filter ( _median_filter_gpu_3d ( ) ) else : raise ValueError ( "currently only 2 or 3 dimensional data is supported" ) return... | median filter of given size |
59,060 | def rotate ( data , axis = ( 1. , 0 , 0 ) , angle = 0. , center = None , mode = "constant" , interpolation = "linear" ) : if center is None : center = tuple ( [ s // 2 for s in data . shape ] ) cx , cy , cz = center m = np . dot ( mat4_translate ( cx , cy , cz ) , np . dot ( mat4_rotate ( angle , * axis ) , mat4_transl... | rotates data around axis by a given angle |
59,061 | def map_coordinates ( data , coordinates , interpolation = "linear" , mode = 'constant' ) : if not ( isinstance ( data , np . ndarray ) and data . ndim in ( 2 , 3 ) ) : raise ValueError ( "input data has to be a 2d or 3d array!" ) coordinates = np . asarray ( coordinates , np . int32 ) if not ( coordinates . shape [ 0 ... | Map data to new coordinates by interpolation . The array of coordinates is used to find for each point in the output the corresponding coordinates in the input . |
59,062 | def pad_to_shape ( d , dshape , mode = "constant" ) : if d . shape == dshape : return d diff = np . array ( dshape ) - np . array ( d . shape ) slices = tuple ( slice ( - x // 2 , x // 2 ) if x < 0 else slice ( None , None ) for x in diff ) res = d [ slices ] return np . pad ( res , [ ( int ( np . ceil ( d / 2. ) ) , d... | pad array d to shape dshape |
59,063 | def pad_to_power2 ( data , axis = None , mode = "constant" ) : if axis is None : axis = list ( range ( data . ndim ) ) if np . all ( [ _is_power2 ( n ) for i , n in enumerate ( data . shape ) if i in axis ] ) : return data else : return pad_to_shape ( data , [ ( _next_power_of_2 ( n ) if i in axis else n ) for i , n in... | pad data to a shape of power 2 if axis == None all axis are padded |
59,064 | def max_filter ( data , size = 7 , res_g = None , sub_blocks = ( 1 , 1 , 1 ) ) : if data . ndim == 2 : _filt = make_filter ( _generic_filter_gpu_2d ( FUNC = "(val>res?val:res)" , DEFAULT = "-INFINITY" ) ) elif data . ndim == 3 : _filt = make_filter ( _generic_filter_gpu_3d ( FUNC = "(val>res?val:res)" , DEFAULT = "-INF... | maximum filter of given size |
59,065 | def min_filter ( data , size = 7 , res_g = None , sub_blocks = ( 1 , 1 , 1 ) ) : if data . ndim == 2 : _filt = make_filter ( _generic_filter_gpu_2d ( FUNC = "(val<res?val:res)" , DEFAULT = "INFINITY" ) ) elif data . ndim == 3 : _filt = make_filter ( _generic_filter_gpu_3d ( FUNC = "(val<res?val:res)" , DEFAULT = "INFIN... | minimum filter of given size |
59,066 | def uniform_filter ( data , size = 7 , res_g = None , sub_blocks = ( 1 , 1 , 1 ) , normalized = True ) : if normalized : if np . isscalar ( size ) : norm = size else : norm = np . int32 ( np . prod ( size ) ) ** ( 1. / len ( size ) ) FUNC = "res+val/%s" % norm else : FUNC = "res+val" if data . ndim == 2 : _filt = make_... | mean filter of given size |
59,067 | def _gauss_filter ( data , sigma = 4 , res_g = None , sub_blocks = ( 1 , 1 , 1 ) ) : truncate = 4. radius = tuple ( int ( truncate * s + 0.5 ) for s in sigma ) size = tuple ( 2 * r + 1 for r in radius ) s = sigma [ 0 ] if data . ndim == 2 : _filt = make_filter ( _generic_filter_gpu_2d ( FUNC = "res+(val*native_exp((flo... | gaussian filter of given size |
59,068 | def _separable_series2 ( h , N = 1 ) : if min ( h . shape ) < N : raise ValueError ( "smallest dimension of h is smaller than approximation order! (%s < %s)" % ( min ( h . shape ) , N ) ) U , S , V = linalg . svd ( h ) hx = [ - U [ : , n ] * np . sqrt ( S [ n ] ) for n in range ( N ) ] hy = [ - V [ n , : ] * np . sqrt ... | finds separable approximations to the 2d function 2d h |
59,069 | def _separable_approx2 ( h , N = 1 ) : return np . cumsum ( [ np . outer ( fy , fx ) for fy , fx in _separable_series2 ( h , N ) ] , 0 ) | returns the N first approximations to the 2d function h whose sum should be h |
59,070 | def _separable_approx3 ( h , N = 1 ) : return np . cumsum ( [ np . einsum ( "i,j,k" , fz , fy , fx ) for fz , fy , fx in _separable_series3 ( h , N ) ] , 0 ) | returns the N first approximations to the 3d function h |
59,071 | def separable_approx ( h , N = 1 ) : if h . ndim == 2 : return _separable_approx2 ( h , N ) elif h . ndim == 3 : return _separable_approx3 ( h , N ) else : raise ValueError ( "unsupported array dimension: %s (only 2d or 3d) " % h . ndim ) | finds the k - th rank approximation to h where k = 1 .. N |
59,072 | def tables ( self ) : _tables = set ( ) for attr in six . itervalues ( self . __dict__ ) : if isinstance ( attr , list ) : for item in attr : if isinstance ( item , Node ) : _tables |= item . tables ( ) elif isinstance ( attr , Node ) : _tables |= attr . tables ( ) return _tables | Generic method that does a depth - first search on the node attributes . |
59,073 | def fix_identities ( self , uniq = None ) : if not hasattr ( self , 'children' ) : return self uniq = list ( set ( self . flat ( ) ) ) if uniq is None else uniq for i , child in enumerate ( self . children ) : if not hasattr ( child , 'children' ) : assert child in uniq self . children [ i ] = uniq [ uniq . index ( chi... | Make pattern - tree tips point to same object if they are equal . |
59,074 | def find_version ( fname ) : version = "" with open ( fname , "r" ) as fp : reg = re . compile ( r'__version__ = [\'"]([^\'"]*)[\'"]' ) for line in fp : m = reg . match ( line ) if m : version = m . group ( 1 ) break if not version : raise RuntimeError ( "Cannot find version information" ) return version | Attempts to find the version number in the file names fname . Raises RuntimeError if not found . |
59,075 | def format_context ( context : Context , formatter : typing . Union [ str , Formatter ] = "full" ) -> str : if not context : return "" if callable ( formatter ) : formatter_func = formatter else : if formatter in CONTEXT_FORMATTERS : formatter_func = CONTEXT_FORMATTERS [ formatter ] else : raise ValueError ( f'Invalid ... | Output the a context dictionary as a string . |
59,076 | def make_banner ( text : typing . Optional [ str ] = None , context : typing . Optional [ Context ] = None , banner_template : typing . Optional [ str ] = None , context_format : ContextFormat = "full" , ) -> str : banner_text = text or speak ( ) banner_template = banner_template or BANNER_TEMPLATE ctx = format_context... | Generates a full banner with version info the given text and a formatted list of context variables . |
59,077 | def config ( config_dict : typing . Mapping ) -> Config : logger . debug ( f"Updating with {config_dict}" ) _cfg . update ( config_dict ) return _cfg | Configures the konch shell . This function should be called in a . konchrc file . |
59,078 | def named_config ( name : str , config_dict : typing . Mapping ) -> None : names = ( name if isinstance ( name , Iterable ) and not isinstance ( name , ( str , bytes ) ) else [ name ] ) for each in names : _config_registry [ each ] = Config ( ** config_dict ) | Adds a named config to the config registry . The first argument may either be a string or a collection of strings . |
59,079 | def __ensure_directory_in_path ( filename : Path ) -> None : directory = Path ( filename ) . parent . resolve ( ) if directory not in sys . path : logger . debug ( f"Adding {directory} to sys.path" ) sys . path . insert ( 0 , str ( directory ) ) | Ensures that a file s directory is in the Python path . |
59,080 | def use_file ( filename : typing . Union [ Path , str , None ] , trust : bool = False ) -> typing . Union [ types . ModuleType , None ] : config_file = filename or resolve_path ( CONFIG_FILE ) def preview_unauthorized ( ) -> None : if not config_file : return None print ( SEPARATOR , file = sys . stderr ) with Path ( c... | Load filename as a python file . Import filename and return it as a module . |
59,081 | def resolve_path ( filename : Path ) -> typing . Union [ Path , None ] : current = Path . cwd ( ) sentinel_dir = Path . home ( ) . parent . resolve ( ) while current != sentinel_dir : target = Path ( current ) / Path ( filename ) if target . exists ( ) : return target . resolve ( ) else : current = current . parent . r... | Find a file by walking up parent directories until the file is found . Return the absolute path of the file . |
59,082 | def parse_args ( argv : typing . Optional [ typing . Sequence ] = None ) -> typing . Dict [ str , str ] : return docopt ( __doc__ , argv = argv , version = __version__ ) | Exposes the docopt command - line arguments parser . Return a dictionary of arguments . |
59,083 | def main ( argv : typing . Optional [ typing . Sequence ] = None ) -> typing . NoReturn : args = parse_args ( argv ) if args [ "--debug" ] : logging . basicConfig ( format = "%(levelname)s %(filename)s: %(message)s" , level = logging . DEBUG ) logger . debug ( args ) config_file : typing . Union [ Path , None ] if args... | Main entry point for the konch CLI . |
59,084 | def init_autoreload ( mode : int ) -> None : from IPython . extensions import autoreload ip = get_ipython ( ) autoreload . load_ipython_extension ( ip ) ip . magics_manager . magics [ "line" ] [ "autoreload" ] ( str ( mode ) ) | Load and initialize the IPython autoreload extension . |
59,085 | def read_tabular ( table_file , sheetname = 'Sheet1' ) : if isinstance ( table_file , str ) : extension = table_file . split ( '.' ) [ - 1 ] if extension in [ 'xls' , 'xlsx' ] : table = pd . read_excel ( table_file , sheetname = sheetname ) elif extension == 'csv' : table = pd . read_csv ( table_file , encoding = 'UTF-... | Reads a vensim syntax model which has been formatted as a table . |
59,086 | def read_xmile ( xmile_file ) : from . import py_backend from . py_backend . xmile . xmile2py import translate_xmile py_model_file = translate_xmile ( xmile_file ) model = load ( py_model_file ) model . xmile_file = xmile_file return model | Construct a model object from . xmile file . |
59,087 | def read_vensim ( mdl_file ) : from . py_backend . vensim . vensim2py import translate_vensim from . py_backend import functions py_model_file = translate_vensim ( mdl_file ) model = functions . Model ( py_model_file ) model . mdl_file = mdl_file return model | Construct a model from Vensim . mdl file . |
59,088 | def cache ( horizon ) : def cache_step ( func ) : @ wraps ( func ) def cached ( * args ) : try : data = func . __globals__ [ '__data' ] assert cached . cache_t == data [ 'time' ] ( ) assert hasattr ( cached , 'cache_val' ) assert cached . cache_val is not None except ( AssertionError , AttributeError ) : cached . cache... | Put a wrapper around a model function |
59,089 | def ramp ( time , slope , start , finish = 0 ) : t = time ( ) if t < start : return 0 else : if finish <= 0 : return slope * ( t - start ) elif t > finish : return slope * ( finish - start ) else : return slope * ( t - start ) | Implements vensim s and xmile s RAMP function |
59,090 | def pulse ( time , start , duration ) : t = time ( ) return 1 if start <= t < start + duration else 0 | Implements vensim s PULSE function |
59,091 | def pulse_train ( time , start , duration , repeat_time , end ) : t = time ( ) if start <= t < end : return 1 if ( t - start ) % repeat_time < duration else 0 else : return 0 | Implements vensim s PULSE TRAIN function |
59,092 | def lookup_extrapolation ( x , xs , ys ) : length = len ( xs ) if x < xs [ 0 ] : dx = xs [ 1 ] - xs [ 0 ] dy = ys [ 1 ] - ys [ 0 ] k = dy / dx return ys [ 0 ] + ( x - xs [ 0 ] ) * k if x > xs [ length - 1 ] : dx = xs [ length - 1 ] - xs [ length - 2 ] dy = ys [ length - 1 ] - ys [ length - 2 ] k = dy / dx return ys [ l... | Intermediate values are calculated with linear interpolation between the intermediate points . Out - of - range values are calculated with linear extrapolation from the last two values at either end . |
59,093 | def xidz ( numerator , denominator , value_if_denom_is_zero ) : small = 1e-6 if abs ( denominator ) < small : return value_if_denom_is_zero else : return numerator * 1.0 / denominator | Implements Vensim s XIDZ function . This function executes a division robust to denominator being zero . In the case of zero denominator the final argument is returned . |
59,094 | def initialize ( self , initialization_order = None ) : if self . time is None : if self . time_initialization is None : self . time = Time ( ) else : self . time = self . time_initialization ( ) self . components . _init_outer_references ( { 'scope' : self , 'time' : self . time } ) remaining = set ( self . _stateful_... | This function tries to initialize the stateful objects . |
59,095 | def set_components ( self , params ) : for key , value in params . items ( ) : if isinstance ( value , pd . Series ) : new_function = self . _timeseries_component ( value ) elif callable ( value ) : new_function = value else : new_function = self . _constant_component ( value ) func_name = utils . get_value_by_insensit... | Set the value of exogenous model elements . Element values can be passed as keyword = value pairs in the function call . Values can be numeric type or pandas Series . Series will be interpolated by integrator . |
59,096 | def _timeseries_component ( self , series ) : return lambda : np . interp ( self . time ( ) , series . index , series . values ) | Internal function for creating a timeseries model element |
59,097 | def set_state ( self , t , state ) : self . time . update ( t ) for key , value in state . items ( ) : component_name = utils . get_value_by_insensitive_key_or_value ( key , self . components . _namespace ) if component_name is not None : stateful_name = '_integ_%s' % component_name else : component_name = key stateful... | Set the system state . |
59,098 | def clear_caches ( self ) : for element_name in dir ( self . components ) : element = getattr ( self . components , element_name ) if hasattr ( element , 'cache_val' ) : delattr ( element , 'cache_val' ) | Clears the Caches for all model elements |
59,099 | def doc ( self ) : collector = [ ] for name , varname in self . components . _namespace . items ( ) : try : docstring = getattr ( self . components , varname ) . __doc__ lines = docstring . split ( '\n' ) collector . append ( { 'Real Name' : name , 'Py Name' : varname , 'Eqn' : lines [ 2 ] . replace ( "Original Eqn:" ,... | Formats a table of documentation strings to help users remember variable names and understand how they are translated into python safe names . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.