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 . emptyDoubleVector ( 6 ) libspice . xfmsta_c ( input_state , input_coord_sys , output_coord_sys , body , output_state ) return stypes . cVectorToPython ( output_state ) | 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 ( ) return - 2 * g | 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 . ADt ) for j in range ( i , len ( x ) ) : Aj = self . A [ : , j ] tj = outer ( Ai , Aj ) H [ i , j ] = ( self . E * ( self . R [ i , j ] * tj + self . R [ j , i ] * tj . T ) - ti * ( dot ( self . AD , outer ( self . R [ : , j ] , Aj ) ) + dot ( outer ( Aj , self . R [ j , : ] ) , self . ADt ) ) ) . sum ( ) H [ j , i ] = H [ i , j ] H *= - 2 e = eigvals ( H ) . min ( ) H = H + ( eye ( H . shape [ 0 ] ) * e ) return H | 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 ) return unfolded_dtensor ( arr , mode , self . shape ) | 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 ] . shape [ 0 ] ] ) ) nvals = np . zeros ( len ( idx ) - 1 ) for i in range ( len ( idx ) - 1 ) : nvals [ i ] = func ( vals [ idx [ i ] : idx [ i + 1 ] ] ) if with_subs : return nvals , tuple ( sub [ idx [ : - 1 ] ] for sub in subs ) else : return nvals | 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 ( ) ) ) ndims = X . ndim if is_number ( rank ) : rank = rank * ones ( ndims ) normX = norm ( X ) U = __init ( ainit , X , ndims , rank , dtype ) fit = 0 exectimes = [ ] for itr in range ( maxIter ) : tic = time . clock ( ) fitold = fit for n in range ( ndims ) : Utilde = ttm ( X , U , n , transp = True , without = True ) U [ n ] = nvecs ( Utilde , n , rank [ n ] ) core = ttm ( Utilde , U , n , transp = True ) normresidual = sqrt ( normX ** 2 - norm ( core ) ** 2 ) fit = 1 - ( normresidual / normX ) fitchange = abs ( fitold - fit ) exectimes . append ( time . clock ( ) - tic ) _log . debug ( '[%3d] fit: %.5f | delta: %7.1e | secs: %.5f' % ( itr , fit , fitchange , exectimes [ - 1 ] ) ) if itr > 1 and fitchange < conv : break return core , U | 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 ( np . prod ( shapeY [ edims ] ) ) : rsubs = unravel_index ( shapeY [ edims ] , i ) | 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 ) > 0 : nidx = unravel_index ( self . col , self . ten_shape [ self . cdims ] ) for i in range ( len ( self . cdims ) ) : nsubs [ : , self . cdims [ i ] ] = nidx [ i ] nsubs = [ z . flatten ( ) for z in hsplit ( nsubs , len ( self . ten_shape ) ) ] return sptensor ( tuple ( nsubs ) , self . data , self . ten_shape ) | 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 ] ) ) E += dot ( R [ i ] , dot ( AtA , R [ i ] . T ) ) + dot ( R [ i ] . T , dot ( AtA , R [ i ] ) ) I = lmbdaA * eye ( rank , dtype = A . dtype ) for i in range ( len ( Z ) ) : F += P [ i ] . dot ( Z [ i ] . T ) E += dot ( Z [ i ] , Z [ i ] . T ) A = solve ( I + E . T , F . T ) . T return orth ( A ) if orthogonalize else A | 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 ValueError ( 'Unknown keywords (%s)' % ( kwargs . keys ( ) ) ) N = X . ndim normX = norm ( X ) U = _init ( ainit , X , N , rank , dtype ) fit = 0 exectimes = [ ] for itr in range ( maxiter ) : tic = time . clock ( ) fitold = fit for n in range ( N ) : Unew = X . uttkrp ( U , n ) Y = ones ( ( rank , rank ) , dtype = dtype ) for i in ( list ( range ( n ) ) + list ( range ( n + 1 , N ) ) ) : Y = Y * dot ( U [ i ] . T , U [ i ] ) Unew = Unew . dot ( pinv ( Y ) ) if itr == 0 : lmbda = sqrt ( ( Unew ** 2 ) . sum ( axis = 0 ) ) else : lmbda = Unew . max ( axis = 0 ) lmbda [ lmbda < 1 ] = 1 U [ n ] = Unew / lmbda P = ktensor ( U , lmbda ) if fit_method == 'full' : normresidual = normX ** 2 + P . norm ( ) ** 2 - 2 * P . innerprod ( X ) fit = 1 - ( normresidual / normX ** 2 ) else : fit = itr fitchange = abs ( fitold - fit ) exectimes . append ( time . clock ( ) - tic ) _log . debug ( '[%3d] fit: %.5f | delta: %7.1e | secs: %.5f' % ( itr , fit , fitchange , exectimes [ - 1 ] ) ) if itr > 0 and fitchange < conv : break return P , fit , itr , array ( exectimes ) | 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 ( nvecs ( X , n , rank ) , dtype = dtype ) else : raise 'Unknown option (init=%s)' % str ( init ) return Uinit | 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 - 1 ) ) U = array ( U [ : , : : - 1 ] ) if do_flipsign : U = flipsign ( U ) return U | 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 != A [ i ] . shape [ 1 ] : raise ValueError ( 'All matrices must have same number of columns' ) M *= A [ i ] . shape [ 0 ] matorder = arange ( len ( A ) ) if reverse : matorder = matorder [ : : - 1 ] P = np . zeros ( ( M , N ) , dtype = A [ 0 ] . dtype ) for n in range ( N ) : ab = A [ matorder [ 0 ] ] [ : , n ] for j in range ( 1 , len ( matorder ) ) : ab = np . kron ( ab , A [ matorder [ j ] ] [ : , n ] ) P [ : , n ] = ab return P | 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 , without = without ) Y = self . _ttm_compute ( V [ vidx [ 0 ] ] , dims [ 0 ] , transp ) for i in xrange ( 1 , len ( dims ) ) : Y = Y . _ttm_compute ( V [ vidx [ i ] ] , dims [ i ] , transp ) return Y | 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' ) % { 'key' : key } ) if isinstance ( value , ( tuple , list ) ) : for item in value : if isinstance ( item , str ) : call_func ( model , item ) elif isinstance ( item , dict ) : field_name = item . pop ( 'name' ) call_func ( model , field_name , extra_params = item ) else : raise ImproperlyConfigured ( _ ( "%(settings)s doesn't recognize the value of %(key)s" ) % { 'settings' : 'CATEGORY_SETTINGS' , 'key' : key } ) elif isinstance ( value , str ) : call_func ( model , value ) elif isinstance ( value , dict ) : field_name = value . pop ( 'name' ) call_func ( model , field_name , extra_params = value ) else : raise ImproperlyConfigured ( _ ( "%(settings)s doesn't recognize the value of %(key)s" ) % { 'settings' : 'CATEGORY_SETTINGS' , 'key' : key } ) | 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 ] return field_name in field_names | 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 . savepoint ( ) for fld in fields : model_name , field_name = fld . split ( '.' ) [ 1 : ] if field_exists ( app_name , model_name , field_name ) : continue model = app_config . get_model ( model_name ) try : with connection . schema_editor ( ) as schema_editor : schema_editor . add_field ( model , registry . _field_registry [ fld ] ) if sid : transaction . savepoint_commit ( sid ) except ProgrammingError : if sid : transaction . savepoint_rollback ( sid ) continue | 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 . slug ) for i in ancestors ] ) + '/' | 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 app_name == sender_app and sender_name == model_name : registry . register_model ( app_name , sender , 'ForeignKey' , val ) for key , val in list ( M2M_REGISTRY . items ( ) ) : app_name , model_name = key . split ( '.' ) if app_name == sender_app and sender_name == model_name : registry . register_model ( app_name , sender , 'ManyToManyField' , val ) | 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 . rght + 1 parent . save ( ) return 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 ] == '\t' : if indent == '' : indent = self . get_indent ( line ) elif not line [ 0 ] in indent : raise CommandError ( "You can't mix spaces and tabs for indents" ) level = line . count ( indent ) current_parents [ level ] = self . make_category ( line , parent = current_parents [ level - 1 ] ) else : current_parents = { 0 : self . make_category ( line ) } current_parents [ 0 ] . _tree_manager . rebuild ( ) | 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" % model ) return model_class | 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 = cat_list [ - 1 ] , level = len ( cat_list ) - 1 ) if len ( cat_list ) == 1 and len ( categories ) > 1 : return None if len ( categories ) == 1 : return categories [ 0 ] else : for item in categories : if item . parent . name == cat_list [ - 2 ] : return item except model_class . DoesNotExist : return None | 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 . TemplateSyntaxError ( error_str % { 'tagname' : bits [ 0 ] } ) if bits [ 2 ] == 'as' : varname = bits [ 3 ] . strip ( "'\"" ) model = "categories.category" if len ( bits ) == 6 : if bits [ 2 ] not in ( 'using' , 'as' ) or bits [ 4 ] not in ( 'using' , 'as' ) : raise template . TemplateSyntaxError ( error_str % { 'tagname' : bits [ 0 ] } ) if bits [ 2 ] == 'as' : varname = bits [ 3 ] . strip ( "'\"" ) model = bits [ 5 ] . strip ( "'\"" ) if bits [ 2 ] == 'using' : varname = bits [ 5 ] . strip ( "'\"" ) model = bits [ 3 ] . strip ( "'\"" ) category = FilterExpression ( bits [ 1 ] , parser ) return CategoryDrillDownNode ( category , varname , model ) | 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 ) == 5 : if bits [ 1 ] not in ( 'as' , 'using' ) and bits [ 3 ] not in ( 'as' , 'using' ) : raise template . TemplateSyntaxError ( usage ) if bits [ 1 ] == 'using' : model = bits [ 2 ] . strip ( "'\"" ) varname = bits [ 4 ] . strip ( "'\"" ) else : model = bits [ 4 ] . strip ( "'\"" ) varname = bits [ 2 ] . strip ( "'\"" ) return TopLevelCategoriesNode ( varname , model ) | 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' ) . iterator ( ) : if p . parent_id and p . parent_id not in include_pages and p . id not in include_pages : ancestor_id_list = p . get_ancestors ( ) . values_list ( 'id' , flat = True ) include_pages . update ( ancestor_id_list ) if include_pages : qs = qs | qs . model . _default_manager . filter ( id__in = include_pages ) qs = qs . distinct ( ) return qs | 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 . shape ) , len ( h . shape ) ) ) if isinstance ( data , OCLArray ) and isinstance ( h , OCLArray ) : return _convolve_buf ( data , h , res_g ) elif isinstance ( data , np . ndarray ) and isinstance ( h , np . ndarray ) : if sub_blocks == ( 1 , ) * len ( data . shape ) or sub_blocks is None : return _convolve_np ( data , h ) else : N_sub = [ int ( np . ceil ( 1. * n / s ) ) for n , s in zip ( data . shape , sub_blocks ) ] Npads = [ int ( s / 2 ) for s in h . shape ] res = np . empty ( data . shape , np . float32 ) for data_tile , data_s_src , data_s_dest in tile_iterator ( data , blocksize = N_sub , padsize = Npads , mode = "constant" ) : res_tile = _convolve_np ( data_tile . copy ( ) , h ) res [ data_s_src ] = res_tile [ data_s_dest ] return res else : raise TypeError ( "unknown types (%s, %s)" % ( type ( data ) , type ( h ) ) ) | 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 supported yet, please convert to:" % dtype , list ( dtypes_options . keys ( ) ) ) prog = OCLProgram ( abspath ( "kernels/convolve3.cl" ) , build_options = dtypes_options [ dtype ] ) hbuf = OCLArray . from_array ( h . astype ( np . float32 ) ) img = OCLImage . from_array ( data ) res = OCLArray . empty ( data . shape , dtype = np . float32 ) Ns = [ np . int32 ( n ) for n in data . shape + h . shape ] prog . run_kernel ( "convolve3d" , img . shape , None , img , hbuf . data , res . data , * Ns ) return res . get ( ) | 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 ( arr_obj , np . ndarray ) : if np . iscomplexobj ( arr_obj ) : arr_obj = OCLArray . from_array ( arr_obj . astype ( np . complex64 , copy = False ) ) else : arr_obj = OCLArray . from_array ( arr_obj . astype ( np . float32 , copy = False ) ) else : raise ValueError ( "unknown type (%s)" % ( type ( arr_obj ) ) ) if not np . all ( [ arr_obj . shape [ a ] % 2 == 0 for a in axes ] ) : raise NotImplementedError ( "only works on axes of even dimensions" ) if res_g is None : res_g = OCLArray . empty_like ( arr_obj ) in_g = arr_obj for ax in axes : _fftshift_single ( in_g , res_g , ax ) in_g = res_g if return_buffer : return res_g else : return res_g . get ( ) | 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 . type prog = OCLProgram ( abspath ( "kernels/fftshift.cl" ) ) prog . run_kernel ( dtype_kernel_name [ dtype ] , ( N2 , N // 2 , N1 ) , None , d_g . data , res_g . data , np . int32 ( N ) , np . int32 ( N2 ) ) return res_g | 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 isinstance ( data , OCLArray ) : return _fft_convolve_gpu ( data , h , res_g = res_g , plan = plan , inplace = inplace , kernel_is_fft = kernel_is_fft ) else : raise TypeError ( "array argument (1) has bad type: %s" % type ( data ) ) | 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 ) ) if not kernel_is_fftshifted : h = np . fft . fftshift ( h ) h_g = OCLArray . from_array ( h . astype ( np . complex64 ) ) res_g = OCLArray . empty_like ( data_g ) _fft_convolve_gpu ( data_g , h_g , res_g = res_g , plan = plan , kernel_is_fft = kernel_is_fft ) res = abs ( res_g . get ( ) ) del data_g del h_g del res_g return res | 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 ) ) ) if plan is None : plan = fft_plan ( data_g . shape ) if inplace : res_g = data_g else : if res_g is None : res_g = OCLArray . empty ( data_g . shape , data_g . dtype ) res_g . copy_buffer ( data_g ) if not kernel_is_fft : kern_g = OCLArray . empty ( h_g . shape , h_g . dtype ) kern_g . copy_buffer ( h_g ) fft ( kern_g , inplace = True , plan = plan ) else : kern_g = h_g fft ( res_g , inplace = True , plan = plan ) _complex_multiply_kernel ( res_g , kern_g ) fft ( res_g , inplace = True , inverse = True , plan = plan ) return res_g | 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 _filt ( data = data , size = size , cval = cval , res_g = res_g , sub_blocks = sub_blocks ) | 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_translate ( - cx , - cy , - cz ) ) ) m = np . linalg . inv ( m ) return affine ( data , m , mode = mode , interpolation = interpolation ) | 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 ] == data . ndim ) : raise ValueError ( "coordinate has to be of shape (data.ndim,m) " ) interpolation_defines = { "linear" : [ "-D" , "SAMPLER_FILTER=CLK_FILTER_LINEAR" ] , "nearest" : [ "-D" , "SAMPLER_FILTER=CLK_FILTER_NEAREST" ] } mode_defines = { "constant" : [ "-D" , "SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP" ] , "wrap" : [ "-D" , "SAMPLER_ADDRESS=CLK_ADDRESS_REPEAT" ] , "edge" : [ "-D" , "SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP_TO_EDGE" ] } if not interpolation in interpolation_defines : raise KeyError ( "interpolation = '%s' not defined ,valid: %s" % ( interpolation , list ( interpolation_defines . keys ( ) ) ) ) if not mode in mode_defines : raise KeyError ( "mode = '%s' not defined ,valid: %s" % ( mode , list ( mode_defines . keys ( ) ) ) ) if not data . dtype . type in cl_buffer_datatype_dict : raise KeyError ( "dtype %s not supported yet (%s)" % ( data . dtype . type , tuple ( cl_buffer_datatype_dict . keys ( ) ) ) ) dtype_defines = [ "-D" , "DTYPE=%s" % cl_buffer_datatype_dict [ data . dtype . type ] ] d_im = OCLImage . from_array ( data ) coordinates_g = OCLArray . from_array ( coordinates . astype ( np . float32 , copy = False ) ) res_g = OCLArray . empty ( coordinates . shape [ 1 ] , data . dtype ) prog = OCLProgram ( abspath ( "kernels/map_coordinates.cl" ) , build_options = interpolation_defines [ interpolation ] + mode_defines [ mode ] + dtype_defines ) kernel = "map_coordinates{ndim}" . format ( ndim = data . ndim ) prog . run_kernel ( kernel , ( coordinates . shape [ - 1 ] , ) , None , d_im , res_g . data , coordinates_g . data ) return res_g . get ( ) | 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 - int ( np . ceil ( d / 2. ) ) ) if d > 0 else ( 0 , 0 ) for d in diff ] , mode = mode ) | 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 enumerate ( data . shape ) ] , mode ) | 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 = "-INFINITY" ) ) return _filt ( data = data , size = size , res_g = res_g , sub_blocks = sub_blocks ) | 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 = "INFINITY" ) ) else : raise ValueError ( "currently only 2 or 3 dimensional data is supported" ) return _filt ( data = data , size = size , res_g = res_g , sub_blocks = sub_blocks ) | 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_filter ( _generic_filter_gpu_2d ( FUNC = FUNC , DEFAULT = "0" ) ) elif data . ndim == 3 : _filt = make_filter ( _generic_filter_gpu_3d ( FUNC = FUNC , DEFAULT = "0" ) ) res = _filt ( data = data , size = size , res_g = res_g , sub_blocks = sub_blocks ) return res | 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((float)(-(ht-%s)*(ht-%s)/2/%s/%s)))" % ( size [ 0 ] // 2 , size [ 0 ] // 2 , s , s ) , DEFAULT = "0.f" ) ) elif data . ndim == 3 : _filt = make_filter ( _generic_filter_gpu_3d ( FUNC = "res+(val*native_exp((float)(-(ht-%s)*(ht-%s)/2/%s/%s)))" % ( size [ 0 ] // 2 , size [ 0 ] // 2 , s , s ) , DEFAULT = "0.f" ) ) else : raise ValueError ( "currently only 2 or 3 dimensional data is supported" ) return _filt ( data = data , size = size , res_g = res_g , sub_blocks = sub_blocks ) | 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 ( S [ n ] ) for n in range ( N ) ] return np . array ( list ( zip ( hx , hy ) ) ) | 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 ( child ) ] else : child . fix_identities ( uniq ) | 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 context format: "{formatter}"' ) return formatter_func ( context ) | 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 ( context or { } , formatter = context_format ) out = banner_template . format ( version = sys . version , text = banner_text , context = ctx ) return out | 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 ( config_file ) . open ( "r" , encoding = "utf-8" ) as fp : for line in fp : print ( line , end = "" , file = sys . stderr ) print ( SEPARATOR , file = sys . stderr ) if config_file and not Path ( config_file ) . exists ( ) : print_error ( f'"{filename}" not found.' ) sys . exit ( 1 ) if config_file and Path ( config_file ) . exists ( ) : if not trust : with AuthFile . load ( ) as authfile : try : authfile . check ( Path ( config_file ) ) except KonchrcChangedError : print_error ( f'"{config_file}" has changed since you last used it.' ) preview_unauthorized ( ) if confirm ( "Would you like to authorize it?" ) : authfile . allow ( Path ( config_file ) ) print ( ) else : sys . exit ( 1 ) except KonchrcNotAuthorizedError : print_error ( f'"{config_file}" is blocked.' ) preview_unauthorized ( ) if confirm ( "Would you like to authorize it?" ) : authfile . allow ( Path ( config_file ) ) print ( ) else : sys . exit ( 1 ) logger . info ( f"Using {config_file}" ) __ensure_directory_in_path ( Path ( config_file ) ) mod = None try : mod = imp . load_source ( "konchrc" , str ( config_file ) ) except UnboundLocalError : pass else : return mod if not config_file : print_warning ( "No konch config file found." ) else : print_warning ( f'"{config_file}" not found.' ) return None | 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 . resolve ( ) return None | 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 [ "init" ] : config_file = Path ( args [ "<config_file>" ] or CONFIG_FILE ) init_config ( config_file ) else : config_file = Path ( args [ "<config_file>" ] ) if args [ "<config_file>" ] else None if args [ "edit" ] : edit_config ( config_file ) elif args [ "allow" ] : allow_config ( config_file ) elif args [ "deny" ] : deny_config ( config_file ) mod = use_file ( Path ( args [ "--file" ] ) if args [ "--file" ] else None ) if hasattr ( mod , "setup" ) : mod . setup ( ) if args [ "--name" ] : if args [ "--name" ] not in _config_registry : print_error ( f'Invalid --name: "{args["--name"]}"' ) sys . exit ( 1 ) config_dict = _config_registry [ args [ "--name" ] ] logger . debug ( f'Using named config: "{args["--name"]}"' ) logger . debug ( config_dict ) else : config_dict = _cfg shell_name = args [ "--shell" ] if shell_name : config_dict [ "shell" ] = SHELL_MAP . get ( shell_name . lower ( ) , AutoShell ) logger . debug ( f"Starting with config {config_dict}" ) start ( ** config_dict ) if hasattr ( mod , "teardown" ) : mod . teardown ( ) sys . exit ( 0 ) | 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-8' ) elif extension == 'tab' : table = pd . read_csv ( table_file , sep = '\t' , encoding = 'UTF-8' ) else : raise ValueError ( 'Unknown file or table type' ) else : raise ValueError ( 'Unknown file or table type' ) if not set ( table . columns ) . issuperset ( { 'Variable' , 'Equation' } ) : raise ValueError ( 'Table must contain at least columns "Variable" and "Equation"' ) if "Units" not in set ( table . columns ) : warnings . warn ( 'Column for "Units" not found' , RuntimeWarning , stacklevel = 2 ) table [ 'Units' ] = '' if "Min" not in set ( table . columns ) : warnings . warn ( 'Column for "Min" not found' , RuntimeWarning , stacklevel = 2 ) table [ 'Min' ] = '' if "Max" not in set ( table . columns ) : warnings . warn ( 'Column for "Max" not found' , RuntimeWarning , stacklevel = 2 ) table [ 'Max' ] = '' mdl_file = table_file . replace ( extension , 'mdl' ) with open ( mdl_file , 'w' , encoding = 'UTF-8' ) as outfile : for element in table . to_dict ( orient = 'records' ) : outfile . write ( "%(Variable)s = \n" "\t %(Equation)s \n" "\t~\t %(Units)s [%(Min)s, %(Max)s] \n" "\t~\t %(Comment)s \n\t|\n\n" % element ) outfile . write ( u'\\\---/// Sketch information - this is where sketch stuff would go.' ) return read_vensim ( mdl_file ) | 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_val = func ( * args ) data = func . __globals__ [ '__data' ] cached . cache_t = data [ 'time' ] ( ) return cached . cache_val return cached def cache_run ( func ) : @ wraps ( func ) def cached ( * args ) : try : return cached . cache_val except AttributeError : cached . cache_val = func ( * args ) return cached . cache_val return cached if horizon == 'step' : return cache_step elif horizon == 'run' : return cache_run else : raise ( AttributeError ( 'Bad horizon for cache decorator' ) ) | 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 [ length - 1 ] + ( x - xs [ length - 1 ] ) * k return np . interp ( x , xs , ys ) | 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_elements ) while remaining : progress = set ( ) for element in remaining : try : element . initialize ( ) progress . add ( element ) except ( KeyError , TypeError , AttributeError ) : pass if progress : remaining . difference_update ( progress ) else : raise KeyError ( 'Unresolvable Reference: Probable circular initialization' + '\n' . join ( [ repr ( e ) for e in remaining ] ) ) | 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_insensitive_key_or_value ( key , self . components . _namespace ) if func_name is None : raise NameError ( '%s is not recognized as a model component' % key ) if '_integ_' + func_name in dir ( self . components ) : warnings . warn ( "Replacing the equation of stock {} with params" . format ( key ) , stacklevel = 2 ) setattr ( self . components , func_name , new_function ) | 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_name = key if hasattr ( self . components , stateful_name ) : try : element = getattr ( self . components , stateful_name ) element . update ( value ) except AttributeError : print ( "'%s' has no state elements, assignment failed" ) raise else : try : setattr ( self . components , component_name , self . _constant_component ( value ) ) except AttributeError : print ( "'%s' has no component, assignment failed" ) raise | 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:" , "" ) . strip ( ) , 'Unit' : lines [ 3 ] . replace ( "Units:" , "" ) . strip ( ) , 'Lims' : lines [ 4 ] . replace ( "Limits:" , "" ) . strip ( ) , 'Type' : lines [ 5 ] . replace ( "Type:" , "" ) . strip ( ) , 'Comment' : '\n' . join ( lines [ 7 : ] ) . strip ( ) } ) except : pass docs_df = _pd . DataFrame ( collector ) docs_df . fillna ( 'None' , inplace = True ) order = [ 'Real Name' , 'Py Name' , 'Unit' , 'Lims' , 'Type' , 'Eqn' , 'Comment' ] return docs_df [ order ] . sort_values ( by = 'Real Name' ) . reset_index ( drop = True ) | 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.