idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
22,900
def define_both_methods ( class_name , class_dict , old_name , new_name ) : assert old_name not in class_dict or new_name not in class_dict , ( 'Class "{}" cannot define both "{}" and "{}" methods.' . format ( class_name , old_name , new_name ) ) if old_name in class_dict : class_dict [ new_name ] = class_dict [ old_na...
Function to help CamelCase to PEP8 style class methods migration .
22,901
def _IsUnparsedFlagAccessAllowed ( self , name ) : if _UNPARSED_FLAG_ACCESS_ENV_NAME in os . environ : allow_unparsed_flag_access = ( os . getenv ( _UNPARSED_FLAG_ACCESS_ENV_NAME ) == '1' ) elif self . __dict__ [ '__reset_called' ] : allow_unparsed_flag_access = False elif _helpers . IsRunningTest ( ) : name_bytes = na...
Determine whether to allow unparsed flag access or not .
22,902
def _AssertValidators ( self , validators ) : for validator in sorted ( validators , key = lambda validator : validator . insertion_index ) : try : validator . verify ( self ) except exceptions . ValidationError as e : message = validator . print_flags_with_values ( self ) raise exceptions . IllegalFlagValueError ( '%s...
Assert if all validators in the list are satisfied .
22,903
def _RemoveAllFlagAppearances ( self , name ) : flag_dict = self . FlagDict ( ) if name not in flag_dict : raise exceptions . UnrecognizedFlagError ( name ) flag = flag_dict [ name ] names_to_remove = { name } names_to_remove . add ( flag . name ) if flag . short_name : names_to_remove . add ( flag . short_name ) for n...
Removes flag with name for all appearances .
22,904
def GetHelp ( self , prefix = '' , include_special_flags = True ) : helplist = [ ] flags_by_module = self . FlagsByModuleDict ( ) if flags_by_module : modules = sorted ( flags_by_module ) main_module = sys . argv [ 0 ] if main_module in modules : modules . remove ( main_module ) modules = [ main_module ] + modules for ...
Generates a help string for all known flags .
22,905
def __RenderOurModuleKeyFlags ( self , module , output_lines , prefix = '' ) : key_flags = self . _GetKeyFlagsForModule ( module ) if key_flags : self . __RenderModuleFlags ( module , key_flags , output_lines , prefix )
Generates a help string for the key flags of a given module .
22,906
def ModuleHelp ( self , module ) : helplist = [ ] self . __RenderOurModuleKeyFlags ( module , helplist ) return '\n' . join ( helplist )
Describe the key flags of a module .
22,907
def register_multi_flags_validator ( flag_names , multi_flags_checker , message = 'Flags validation failed' , flag_values = FLAGS ) : v = gflags_validators . MultiFlagsValidator ( flag_names , multi_flags_checker , message ) _add_validator ( flag_values , v )
Adds a constraint to multiple flags .
22,908
def multi_flags_validator ( flag_names , message = 'Flag validation failed' , flag_values = FLAGS ) : def decorate ( function ) : register_multi_flags_validator ( flag_names , function , message = message , flag_values = flag_values ) return function return decorate
A function decorator for defining a multi - flag validator .
22,909
def mark_flag_as_required ( flag_name , flag_values = FLAGS ) : if flag_values [ flag_name ] . default is not None : warnings . warn ( 'Flag %s has a non-None default value; therefore, ' 'mark_flag_as_required will pass even if flag is not specified in the ' 'command line!' % flag_name ) register_validator ( flag_name ...
Ensures that flag is not None during program execution .
22,910
def mark_flags_as_mutual_exclusive ( flag_names , required = False , flag_values = FLAGS ) : def validate_mutual_exclusion ( flags_dict ) : flag_count = sum ( 1 for val in flags_dict . values ( ) if val is not None ) if flag_count == 1 or ( not required and flag_count == 0 ) : return True message = ( '%s one of (%s) mu...
Ensures that only one flag among flag_names is set .
22,911
def DEFINE_enum ( name , default , enum_values , help , flag_values = FLAGS , module_name = None , ** args ) : DEFINE_flag ( EnumFlag ( name , default , help , enum_values , ** args ) , flag_values , module_name )
Registers a flag whose value can be any string from enum_values .
22,912
def DEFINE_list ( name , default , help , flag_values = FLAGS , ** args ) : parser = ListParser ( ) serializer = CsvListSerializer ( ',' ) DEFINE ( parser , name , default , help , flag_values , serializer , ** args )
Registers a flag whose value is a comma - separated list of strings .
22,913
def DEFINE_multi ( parser , serializer , name , default , help , flag_values = FLAGS , module_name = None , ** args ) : DEFINE_flag ( MultiFlag ( parser , serializer , name , default , help , ** args ) , flag_values , module_name )
Registers a generic MultiFlag that parses its args with a given parser .
22,914
def DEFINE_multi_float ( name , default , help , lower_bound = None , upper_bound = None , flag_values = FLAGS , ** args ) : parser = FloatParser ( lower_bound , upper_bound ) serializer = ArgumentSerializer ( ) DEFINE_multi ( parser , serializer , name , default , help , flag_values , ** args )
Registers a flag whose value can be a list of arbitrary floats .
22,915
def DEFINE_alias ( name , original_name , flag_values = FLAGS , module_name = None ) : if original_name not in flag_values : raise UnrecognizedFlagError ( original_name ) flag = flag_values [ original_name ] class _Parser ( ArgumentParser ) : def parse ( self , argument ) : flag . parse ( argument ) return flag . value...
Defines an alias flag for an existing one .
22,916
def from_flag ( cls , flagname , flag_values , other_flag_values = None ) : first_module = flag_values . FindModuleDefiningFlag ( flagname , default = '<unknown>' ) if other_flag_values is None : second_module = _helpers . GetCallingModule ( ) else : second_module = other_flag_values . FindModuleDefiningFlag ( flagname...
Create a DuplicateFlagError by providing flag name and values .
22,917
def convert ( self , argument ) : if isinstance ( argument , str ) : if argument . lower ( ) in [ 'true' , 't' , '1' ] : return True elif argument . lower ( ) in [ 'false' , 'f' , '0' ] : return False bool_argument = bool ( argument ) if argument == bool_argument : return bool_argument raise ValueError ( 'Non-boolean a...
Converts the argument to a boolean ; raise ValueError on errors .
22,918
def parse ( self , argument ) : if not self . enum_values : return argument elif self . case_sensitive : if argument not in self . enum_values : raise ValueError ( 'value should be one of <%s>' % '|' . join ( self . enum_values ) ) else : return argument else : if argument . upper ( ) not in [ value . upper ( ) for val...
Determine validity of argument and return the correct element of enum .
22,919
def serialize ( self , value ) : if six . PY2 : output = io . BytesIO ( ) csv . writer ( output ) . writerow ( [ unicode ( x ) . encode ( 'utf-8' ) for x in value ] ) serialized_value = output . getvalue ( ) . decode ( 'utf-8' ) . strip ( ) else : output = io . StringIO ( ) csv . writer ( output ) . writerow ( [ str ( ...
Serialize a list as a string if possible or as a unicode string .
22,920
def record ( self ) : while True : frames = [ ] self . stream . start_stream ( ) for i in range ( self . num_frames ) : data = self . stream . read ( self . config . FRAMES_PER_BUFFER ) frames . append ( data ) self . output . seek ( 0 ) w = wave . open ( self . output , 'wb' ) w . setnchannels ( self . config . CHANNE...
Record PyAudio stream into StringIO output
22,921
def stop ( self ) : self . prestop ( ) if not self . _graceful : self . _graceful = True self . stream . stop_stream ( ) self . audio . terminate ( ) msg = 'Stopped' self . verbose_info ( msg , log = False ) if self . log : self . logging . info ( msg ) if self . collect : if self . _data : print ( 'Collected result:' ...
Stop the stream and terminate PyAudio
22,922
def get_threshold ( self ) : if self . threshold . startswith ( '+' ) : if self . threshold [ 1 : ] . isdigit ( ) : self . _threshold = int ( self . threshold [ 1 : ] ) self . _upper = True elif self . threshold . startswith ( '-' ) : if self . threshold [ 1 : ] . isdigit ( ) : self . _threshold = int ( self . threshol...
Get and validate raw RMS value from threshold
22,923
def collect_rms ( self , rms ) : if self . _data : self . _data [ 'min' ] = min ( rms , self . _data [ 'min' ] ) self . _data [ 'max' ] = max ( rms , self . _data [ 'max' ] ) self . _data [ 'avg' ] = float ( rms + self . _data [ 'avg' ] ) / 2 else : self . _data [ 'min' ] = rms self . _data [ 'max' ] = rms self . _data...
Collect and calculate min max and average RMS values
22,924
def from_timedelta ( cls , timedelta ) : from math import ceil units = ceil ( timedelta . total_seconds ( ) / cls . time_unit ) return cls . create ( units )
expects a datetime . timedelta object
22,925
def b58decode_check ( v : str ) -> bytes : result = b58decode ( v ) result , check = result [ : - 4 ] , result [ - 4 : ] digest = sha256 ( sha256 ( result ) . digest ( ) ) . digest ( ) if check != digest [ : 4 ] : raise ValueError ( "Invalid checksum" ) return result
Decode and verify the checksum of a Base58 encoded string
22,926
def bech32_decode ( bech ) : if ( ( any ( ord ( x ) < 33 or ord ( x ) > 126 for x in bech ) ) or ( bech . lower ( ) != bech and bech . upper ( ) != bech ) ) : return None , None bech = bech . lower ( ) pos = bech . rfind ( '1' ) if pos < 1 or pos + 7 > len ( bech ) or len ( bech ) > 90 : return None , None if not all (...
Validate a Bech32 string and determine HRP and data .
22,927
def process_request ( self , request ) : if django . VERSION < ( 1 , 10 ) : is_authenticated = request . user . is_authenticated ( ) else : is_authenticated = request . user . is_authenticated if not is_authenticated : return now = datetime . now ( ) if '_session_security' not in request . session : set_last_activity (...
Update last activity time or logout .
22,928
def get_last_activity ( session ) : try : return datetime . strptime ( session [ '_session_security' ] , '%Y-%m-%dT%H:%M:%S.%f' ) except AttributeError : return datetime . now ( ) except TypeError : return datetime . now ( )
Get the last activity datetime string from the session and return the python datetime object .
22,929
def name ( self ) : return self . inquire ( name = True , lifetime = False , usage = False , mechs = False ) . name
Get the name associated with these credentials
22,930
def acquire ( cls , name = None , lifetime = None , mechs = None , usage = 'both' , store = None ) : if store is None : res = rcreds . acquire_cred ( name , lifetime , mechs , usage ) else : if rcred_cred_store is None : raise NotImplementedError ( "Your GSSAPI implementation does " "not have support for manipulating "...
Acquire GSSAPI credentials
22,931
def store ( self , store = None , usage = 'both' , mech = None , overwrite = False , set_default = False ) : if store is None : if rcred_rfc5588 is None : raise NotImplementedError ( "Your GSSAPI implementation does " "not have support for RFC 5588" ) return rcred_rfc5588 . store_cred ( self , usage , mech , overwrite ...
Store these credentials into the given store
22,932
def impersonate ( self , name = None , lifetime = None , mechs = None , usage = 'initiate' ) : if rcred_s4u is None : raise NotImplementedError ( "Your GSSAPI implementation does not " "have support for S4U" ) res = rcred_s4u . acquire_cred_impersonate_name ( self , name , lifetime , mechs , usage ) return type ( self ...
Impersonate a name using the current credentials
22,933
def inquire ( self , name = True , lifetime = True , usage = True , mechs = True ) : res = rcreds . inquire_cred ( self , name , lifetime , usage , mechs ) if res . name is not None : res_name = names . Name ( res . name ) else : res_name = None return tuples . InquireCredResult ( res_name , res . lifetime , res . usag...
Inspect these credentials for information
22,934
def inquire_by_mech ( self , mech , name = True , init_lifetime = True , accept_lifetime = True , usage = True ) : res = rcreds . inquire_cred_by_mech ( self , mech , name , init_lifetime , accept_lifetime , usage ) if res . name is not None : res_name = names . Name ( res . name ) else : res_name = None return tuples ...
Inspect these credentials for per - mechanism information
22,935
def add ( self , name , mech , usage = 'both' , init_lifetime = None , accept_lifetime = None , impersonator = None , store = None ) : if store is not None and impersonator is not None : raise ValueError ( 'You cannot use both the `impersonator` and ' '`store` arguments at the same time' ) if store is not None : if rcr...
Acquire more credentials to add to the current set
22,936
def display_as ( self , name_type ) : if rname_rfc6680 is None : raise NotImplementedError ( "Your GSSAPI implementation does not " "support RFC 6680 (the GSSAPI naming " "extensions)" ) return rname_rfc6680 . display_name_ext ( self , name_type ) . decode ( _utils . _get_encoding ( ) )
Display this name as the given name type .
22,937
def export ( self , composite = False ) : if composite : if rname_rfc6680 is None : raise NotImplementedError ( "Your GSSAPI implementation does " "not support RFC 6680 (the GSSAPI " "naming extensions)" ) return rname_rfc6680 . export_name_composite ( self ) else : return rname . export_name ( self )
Export this name as a token .
22,938
def _inquire ( self , ** kwargs ) : if rname_rfc6680 is None : raise NotImplementedError ( "Your GSSAPI implementation does not " "support RFC 6680 (the GSSAPI naming " "extensions)" ) if not kwargs : default_val = True else : default_val = False attrs = kwargs . get ( 'attrs' , default_val ) mech_name = kwargs . get (...
Inspect this name for information .
22,939
def from_sasl_name ( cls , name = None ) : if rfc5801 is None : raise NotImplementedError ( "Your GSSAPI implementation does not " "have support for RFC 5801" ) if isinstance ( name , six . text_type ) : name = name . encode ( _utils . _get_encoding ( ) ) m = rfc5801 . inquire_mech_for_saslname ( name ) return cls ( m ...
Create a Mechanism from its SASL name
22,940
def import_gssapi_extension ( name ) : try : path = 'gssapi.raw.ext_{0}' . format ( name ) __import__ ( path ) return sys . modules [ path ] except ImportError : return None
Import a GSSAPI extension module
22,941
def inquire_property ( name , doc = None ) : def inquire_property ( self ) : if not self . _started : msg = ( "Cannot read {0} from a security context whose " "establishment has not yet been started." ) raise AttributeError ( msg ) return getattr ( self . _inquire ( ** { name : True } ) , name ) return property ( inqui...
Creates a property based on an inquire result
22,942
def _encode_dict ( d ) : def enc ( x ) : if isinstance ( x , six . text_type ) : return x . encode ( _ENCODING ) else : return x return dict ( ( enc ( k ) , enc ( v ) ) for k , v in six . iteritems ( d ) )
Encodes any relevant strings in a dict
22,943
def catch_and_return_token ( func , self , * args , ** kwargs ) : try : return func ( self , * args , ** kwargs ) except GSSError as e : if e . token is not None and self . __DEFER_STEP_ERRORS__ : self . _last_err = e if six . PY2 : self . _last_tb = sys . exc_info ( ) [ 2 ] . tb_next . tb_next else : self . _last_err ...
Optionally defer exceptions and return a token instead
22,944
def check_last_err ( func , self , * args , ** kwargs ) : if self . _last_err is not None : try : if six . PY2 : six . reraise ( type ( self . _last_err ) , self . _last_err , self . _last_tb ) else : raise self . _last_err finally : if six . PY2 : del self . _last_tb self . _last_err = None else : return func ( self ,...
Check and raise deferred errors before running the function
22,945
def velocity_graph ( adata , basis = None , vkey = 'velocity' , which_graph = 'velocity' , n_neighbors = 10 , alpha = .8 , perc = 90 , edge_width = .2 , edge_color = 'grey' , color = None , use_raw = None , layer = None , color_map = None , colorbar = True , palette = None , size = None , sort_order = True , groups = N...
\ Plot of the velocity graph .
22,946
def cleanup ( data , clean = 'layers' , keep = None , copy = False ) : adata = data . copy ( ) if copy else data keep = list ( [ keep ] ) if isinstance ( keep , str ) else list ( ) if keep is None else list ( keep ) keep . extend ( [ 'spliced' , 'unspliced' , 'Ms' , 'Mu' , 'clusters' , 'neighbors' ] ) ann_dict = { 'obs...
Deletes attributes not needed .
22,947
def filter_genes ( data , min_counts = None , min_cells = None , max_counts = None , max_cells = None , min_counts_u = None , min_cells_u = None , max_counts_u = None , max_cells_u = None , min_shared_counts = None , min_shared_cells = None , copy = False ) : adata = data . copy ( ) if copy else data set_initial_size (...
Filter genes based on number of cells or counts . Keep genes that have at least min_counts counts or are expressed in at least min_cells cells or have at most max_counts counts or are expressed in at most max_cells cells . Only provide one of the optional parameters min_counts min_cells max_counts max_cells per call .
22,948
def filter_genes_dispersion ( data , flavor = 'seurat' , min_disp = None , max_disp = None , min_mean = None , max_mean = None , n_bins = 20 , n_top_genes = None , log = True , copy = False ) : adata = data . copy ( ) if copy else data set_initial_size ( adata ) if n_top_genes is not None and adata . n_vars < n_top_gen...
Extract highly variable genes . The normalized dispersion is obtained by scaling with the mean and standard deviation of the dispersions for genes falling into a given bin for mean expression of genes . This means that for each bin of mean expression highly variable genes are selected .
22,949
def normalize_per_cell ( data , counts_per_cell_after = None , counts_per_cell = None , key_n_counts = None , max_proportion_per_cell = None , use_initial_size = True , layers = [ 'spliced' , 'unspliced' ] , enforce = False , copy = False ) : adata = data . copy ( ) if copy else data layers = adata . layers . keys ( ) ...
Normalize each cell by total counts over all genes .
22,950
def filter_and_normalize ( data , min_counts = None , min_counts_u = None , min_cells = None , min_cells_u = None , min_shared_counts = None , min_shared_cells = None , n_top_genes = None , flavor = 'seurat' , log = True , copy = False ) : adata = data . copy ( ) if copy else data if 'spliced' not in adata . layers . k...
Filtering normalization and log transform
22,951
def toy_data ( n_obs ) : adata = dentategyrus ( ) indices = np . random . choice ( adata . n_obs , n_obs ) adata = adata [ indices ] adata . obs_names = np . array ( range ( adata . n_obs ) , dtype = 'str' ) adata . var_names_make_unique ( ) return adata
Randomly samples from the Dentate Gyrus dataset .
22,952
def forebrain ( ) : filename = 'data/ForebrainGlut/hgForebrainGlut.loom' url = 'http://pklab.med.harvard.edu/velocyto/hgForebrainGlut/hgForebrainGlut.loom' adata = read ( filename , backup_url = url , cleanup = True , sparse = True , cache = True ) adata . var_names_make_unique ( ) return adata
Developing human forebrain . Forebrain tissue of a week 10 embryo focusing on the glutamatergic neuronal lineage .
22,953
def set_rcParams_scvelo ( fontsize = 8 , color_map = None , frameon = None ) : rcParams [ 'figure.dpi' ] = 100 rcParams [ 'savefig.dpi' ] = 150 rcParams [ 'figure.figsize' ] = ( 7 , 5 ) rcParams [ 'figure.subplot.left' ] = 0.18 rcParams [ 'figure.subplot.right' ] = 0.96 rcParams [ 'figure.subplot.bottom' ] = 0.15 rcPar...
Set matplotlib . rcParams to scvelo defaults .
22,954
def merge ( adata , ldata , copy = True ) : if 'spliced' in ldata . layers . keys ( ) and 'initial_size_spliced' not in ldata . obs . keys ( ) : set_initial_size ( ldata ) elif 'spliced' in adata . layers . keys ( ) and 'initial_size_spliced' not in adata . obs . keys ( ) : set_initial_size ( adata ) common_obs = adata...
Merges two annotated data matrices .
22,955
def velocity_graph ( data , vkey = 'velocity' , xkey = 'Ms' , tkey = None , basis = None , n_neighbors = None , n_recurse_neighbors = None , random_neighbors_at_max = None , sqrt_transform = False , approx = False , copy = False ) : adata = data . copy ( ) if copy else data if vkey not in adata . layers . keys ( ) : ve...
Computes velocity graph based on cosine similarities .
22,956
def optimize_NxN ( x , y , fit_offset = False , perc = None ) : if perc is not None : if not fit_offset and isinstance ( perc , ( list , tuple ) ) : perc = perc [ 1 ] weights = get_weight ( x , y , perc ) . astype ( bool ) if issparse ( weights ) : weights = weights . A else : weights = None x , y = x . astype ( np . f...
Just to compare with closed - form solution
22,957
def velocity_confidence ( data , vkey = 'velocity' , copy = False ) : adata = data . copy ( ) if copy else data if vkey not in adata . layers . keys ( ) : raise ValueError ( 'You need to run `tl.velocity` first.' ) idx = np . array ( adata . var [ vkey + '_genes' ] . values , dtype = bool ) X , V = adata . layers [ 'Ms...
Computes confidences of velocities .
22,958
def velocity_confidence_transition ( data , vkey = 'velocity' , scale = 10 , copy = False ) : adata = data . copy ( ) if copy else data if vkey not in adata . layers . keys ( ) : raise ValueError ( 'You need to run `tl.velocity` first.' ) idx = np . array ( adata . var [ vkey + '_genes' ] . values , dtype = bool ) T = ...
Computes confidences of velocity transitions .
22,959
def cell_fate ( data , groupby = 'clusters' , disconnected_groups = None , self_transitions = False , n_neighbors = None , copy = False ) : adata = data . copy ( ) if copy else data logg . info ( 'computing cell fates' , r = True ) n_neighbors = 10 if n_neighbors is None else n_neighbors _adata = adata . copy ( ) vgrap...
Computes individual cell endpoints
22,960
def moments ( data , n_neighbors = 30 , n_pcs = 30 , mode = 'connectivities' , method = 'umap' , metric = 'euclidean' , use_rep = None , recurse_neighbors = False , renormalize = False , copy = False ) : adata = data . copy ( ) if copy else data if 'spliced' not in adata . layers . keys ( ) or 'unspliced' not in adata ...
Computes moments for velocity estimation .
22,961
def transition_matrix ( adata , vkey = 'velocity' , basis = None , backward = False , self_transitions = True , scale = 10 , perc = None , use_negative_cosines = False , weight_diffusion = 0 , scale_diffusion = 1 , weight_indirect_neighbors = None , n_neighbors = None , vgraph = None ) : if vkey + '_graph' not in adata...
Computes transition probabilities from velocity graph
22,962
def apply ( self ) : raw_operations = copy . deepcopy ( self . occurrences ) for task in self . tasks : task ( self ) self . occurrences = raw_operations
Apply the rules of the context to its occurrences .
22,963
def average_price ( quantity_1 , price_1 , quantity_2 , price_2 ) : return ( quantity_1 * price_1 + quantity_2 * price_2 ) / ( quantity_1 + quantity_2 )
Calculates the average price between two asset states .
22,964
def update_holder ( self , holder ) : subject_symbol = self . subject . symbol if subject_symbol in holder . state : if not holder . state [ subject_symbol ] [ 'quantity' ] : holder . state [ subject_symbol ] [ 'value' ] = self . details [ 'value' ] elif same_sign ( holder . state [ subject_symbol ] [ 'quantity' ] , se...
Udpate the Holder state according to the occurrence .
22,965
def fitter ( self , n = 0 , ftype = "real" , colfac = 1.0e-8 , lmfac = 1.0e-3 ) : fid = self . _fitproxy . getid ( ) ftype = self . _gettype ( ftype ) n = len ( self . _fitids ) if 0 <= fid < n : self . _fitids [ fid ] = { } elif fid == n : self . _fitids . append ( { } ) else : raise RangeError ( "fit id out of range"...
Create a sub - fitter .
22,966
def done ( self , fid = 0 ) : self . _checkid ( fid ) self . _fitids [ fid ] = { } self . _fitproxy . done ( fid )
Terminates the fitserver .
22,967
def reset ( self , fid = 0 ) : self . _checkid ( fid ) self . _fitids [ fid ] [ "solved" ] = False self . _fitids [ fid ] [ "haserr" ] = False if not self . _fitids [ fid ] [ "looped" ] : return self . _fitproxy . reset ( fid ) else : self . _fitids [ fid ] [ "looped" ] = False return True
Reset the object s resources to its initialized state .
22,968
def addconstraint ( self , x , y = 0 , fnct = None , fid = 0 ) : self . _checkid ( fid ) i = 0 if "constraint" in self . _fitids [ fid ] : i = len ( self . _fitids [ fid ] [ "constraint" ] ) else : self . _fitids [ fid ] [ "constraint" ] = { } i = str ( i ) self . _fitids [ fid ] [ "constraint" ] [ i ] = { } if isinsta...
Add constraint .
22,969
def fitspoly ( self , n , x , y , sd = None , wt = 1.0 , fid = 0 ) : a = max ( abs ( max ( x ) ) , abs ( min ( x ) ) ) if a == 0 : a = 1 a = 1.0 / a b = NUM . power ( a , range ( n + 1 ) ) if self . set ( n = n + 1 , fid = fid ) : self . linear ( poly ( n ) , x * a , y , sd , wt , fid ) self . _fitids [ fid ] [ "sol" ]...
Create normal equations from the specified condition equations and solve the resulting normal equations . It is in essence a combination .
22,970
def functional ( self , fnct , x , y , sd = None , wt = 1.0 , mxit = 50 , fid = 0 ) : self . _fit ( fitfunc = "functional" , fnct = fnct , x = x , y = y , sd = sd , wt = wt , mxit = mxit , fid = fid )
Make a non - linear least squares solution .
22,971
def linear ( self , fnct , x , y , sd = None , wt = 1.0 , fid = 0 ) : self . _fit ( fitfunc = "linear" , fnct = fnct , x = x , y = y , sd = sd , wt = wt , fid = fid )
Make a linear least squares solution .
22,972
def constraint ( self , n = - 1 , fid = 0 ) : c = self . _getval ( "constr" , fid ) if n < 0 or n > self . deficiency ( fid ) : return c else : raise RuntimeError ( "Not yet implemented" )
Obtain the set of orthogonal equations that make the solution of the rank deficient normal equations possible .
22,973
def fitted ( self , fid = 0 ) : self . _checkid ( fid ) return not ( self . _fitids [ fid ] [ "fit" ] > 0 or self . _fitids [ fid ] [ "fit" ] < - 0.001 )
Test if enough Levenberg - Marquardt loops have been done .
22,974
def set_data_path ( self , pth ) : if os . path . exists ( pth ) : if not os . path . exists ( os . path . join ( pth , 'data' , 'geodetic' ) ) : raise IOError ( "The given path doesn't contain a 'data' " "subdirectory" ) os . environ [ "AIPSPATH" ] = "%s dummy dummy" % pth
Set the location of the measures data directory .
22,975
def asbaseline ( self , pos ) : if not is_measure ( pos ) or pos [ 'type' ] not in [ 'position' , 'baseline' ] : raise TypeError ( 'Argument is not a position/baseline measure' ) if pos [ 'type' ] == 'position' : loc = self . measure ( pos , 'itrf' ) loc [ 'type' ] = 'baseline' return self . measure ( loc , 'j2000' ) r...
Convert a position measure into a baseline measure . No actual baseline is calculated since operations can be done on positions with subtractions to obtain baselines at a later stage .
22,976
def getvalue ( self , v ) : if not is_measure ( v ) : raise TypeError ( 'Incorrect input type for getvalue()' ) import re rx = re . compile ( "m\d+" ) out = [ ] keys = v . keys ( ) [ : ] keys . sort ( ) for key in keys : if re . match ( rx , key ) : out . append ( dq . quantity ( v . get ( key ) ) ) return out
Return a list of quantities making up the measures value .
22,977
def doframe ( self , v ) : if not is_measure ( v ) : raise TypeError ( 'Argument is not a measure' ) if ( v [ "type" ] == "frequency" and v [ "refer" ] . lower ( ) == "rest" ) or _measures . doframe ( self , v ) : self . _framestack [ v [ "type" ] ] = v return True return False
This method will set the measure specified as part of a frame .
22,978
def addImagingColumns ( msname , ack = True ) : import numpy as np t = table ( msname , readonly = False , ack = False ) cnames = t . colnames ( ) try : cdesc = t . getcoldesc ( 'DATA' ) except : raise ValueError ( 'Column DATA does not exist' ) hasTiled = False try : dminfo = t . getdminfo ( "DATA" ) if dminfo [ 'TYPE...
Add the columns to an MS needed for the casa imager .
22,979
def addDerivedMSCal ( msname ) : t = table ( msname , readonly = False , ack = False ) colnames = t . colnames ( ) for col in [ "TIME" , "ANTENNA1" , "FIELD_ID" , "FEED1" ] : if col not in colnames : raise ValueError ( "Columns " + colnames + " should be present in table " + msname ) scols1 = [ 'HA' , 'HA1' , 'HA2' , '...
Add the derived columns like HA to an MS or CalTable .
22,980
def removeDerivedMSCal ( msname ) : t = table ( msname , readonly = False , ack = False ) dmi = t . getdminfo ( ) for x in dmi . values ( ) : if x [ 'TYPE' ] == 'DerivedMSCal' : t . removecols ( x [ 'COLUMNS' ] ) t . flush ( )
Remove the derived columns like HA from an MS or CalTable .
22,981
def msregularize ( msname , newname ) : t = table ( msname ) t1 = t . sort ( 'unique ANTENNA1,ANTENNA2' ) nadded = 0 for tsub in t . iter ( [ 'TIME' , 'DATA_DESC_ID' ] ) : nmissing = t1 . nrows ( ) - tsub . nrows ( ) if nmissing < 0 : raise ValueError ( "A time/band chunk has too many rows" ) if nmissing > 0 : ant1 = s...
Regularize an MS
22,982
def _repr_html_ ( self ) : out = "<table class='taqltable'>\n" if not ( self . name ( ) [ : 4 ] == "Col_" ) : out += "<tr>" out += "<th><b>" + self . name ( ) + "</b></th>" out += "</tr>" cropped = False rowcount = 0 colkeywords = self . getkeywords ( ) for row in self : out += "\n<tr>" out += "<td>" + _format_cell ( r...
Give a nice representation of columns in notebooks .
22,983
def _get_coordinatenames ( self ) : validnames = ( "direction" , "spectral" , "linear" , "stokes" , "tabular" ) self . _names = [ "" ] * len ( validnames ) n = 0 for key in self . _csys . keys ( ) : for name in validnames : if key . startswith ( name ) : idx = int ( key [ len ( name ) : ] ) self . _names [ idx ] = name...
Create ordered list of coordinate names
22,984
def set_projection ( self , val ) : knownproj = [ "SIN" , "ZEA" , "TAN" , "NCP" , "AIT" , "ZEA" ] assert val . upper ( ) in knownproj self . _coord [ "projection" ] = val . upper ( )
Set the projection of the given axis in this coordinate .
22,985
def tablefromascii ( tablename , asciifile , headerfile = '' , autoheader = False , autoshape = [ ] , columnnames = [ ] , datatypes = [ ] , sep = ' ' , commentmarker = '' , firstline = 1 , lastline = - 1 , readonly = True , lockoptions = 'default' , ack = True ) : import os . path filename = os . path . expandvars ( as...
Create a table from an ASCII file .
22,986
def makescacoldesc ( columnname , value , datamanagertype = '' , datamanagergroup = '' , options = 0 , maxlen = 0 , comment = '' , valuetype = '' , keywords = { } ) : vtype = valuetype if vtype == '' : vtype = _value_type_name ( value ) rec2 = { 'valueType' : vtype , 'dataManagerType' : datamanagertype , 'dataManagerGr...
Create description of a scalar column .
22,987
def makearrcoldesc ( columnname , value , ndim = 0 , shape = [ ] , datamanagertype = '' , datamanagergroup = '' , options = 0 , maxlen = 0 , comment = '' , valuetype = '' , keywords = { } ) : vtype = valuetype if vtype == '' : vtype = _value_type_name ( value ) if len ( shape ) > 0 : if ndim <= 0 : ndim = len ( shape )...
Create description of an array column .
22,988
def maketabdesc ( descs = [ ] ) : rec = { } if isinstance ( descs , dict ) : descs = [ descs ] for desc in descs : colname = desc [ 'name' ] if colname in rec : raise ValueError ( 'Column name ' + colname + ' multiply used in table description' ) rec [ colname ] = desc [ 'desc' ] return rec
Create a table description .
22,989
def makedminfo ( tabdesc , group_spec = None ) : if group_spec is None : group_spec = { } class DMGroup ( object ) : def __init__ ( self ) : self . columns = [ ] self . type = None self . spec = None dm_groups = defaultdict ( DMGroup ) for c , d in six . iteritems ( tabdesc ) : if c in ( '_define_hypercolumn_' , '_keyw...
Creates a data manager information object .
22,990
def tabledefinehypercolumn ( tabdesc , name , ndim , datacolumns , coordcolumns = False , idcolumns = False ) : rec = { 'HCndim' : ndim , 'HCdatanames' : datacolumns } if not isinstance ( coordcolumns , bool ) : rec [ 'HCcoordnames' ] = coordcolumns if not isinstance ( idcolumns , bool ) : rec [ 'HCidnames' ] = idcolum...
Add a hypercolumn to a table description .
22,991
def tabledelete ( tablename , checksubtables = False , ack = True ) : tabname = _remove_prefix ( tablename ) t = table ( tabname , ack = False ) if t . ismultiused ( checksubtables ) : six . print_ ( 'Table' , tabname , 'cannot be deleted; it is still in use' ) else : t = 0 table ( tabname , readonly = False , _delete ...
Delete a table on disk .
22,992
def tableexists ( tablename ) : result = True try : t = table ( tablename , ack = False ) except : result = False return result
Test if a table exists .
22,993
def tableiswritable ( tablename ) : result = True try : t = table ( tablename , readonly = False , ack = False ) result = t . iswritable ( ) except : result = False return result
Test if a table is writable .
22,994
def tablestructure ( tablename , dataman = True , column = True , subtable = False , sort = False ) : t = table ( tablename , ack = False ) six . print_ ( t . showstructure ( dataman , column , subtable , sort ) )
Print the structure of a table .
22,995
def attrget ( self , groupname , attrname , rownr ) : return self . _attrget ( groupname , attrname , rownr )
Get the value of an attribute in the given row in a group .
22,996
def attrgetcol ( self , groupname , attrname ) : values = [ ] for rownr in range ( self . attrnrows ( groupname ) ) : values . append ( self . attrget ( groupname , attrname , rownr ) ) return values
Get the value of an attribute for all rows in a group .
22,997
def attrfindrows ( self , groupname , attrname , value ) : values = self . attrgetcol ( groupname , attrname ) return [ i for i in range ( len ( values ) ) if values [ i ] == value ]
Get the row numbers of all rows where the attribute matches the given value .
22,998
def attrgetrow ( self , groupname , key , value = None ) : if not isinstance ( key , str ) : return self . _attrgetrow ( groupname , key ) rownrs = self . attrfindrows ( groupname , key , value ) if len ( rownrs ) == 0 : raise IndexError ( "Image attribute " + key + " in group " + groupname + " has no matches for value...
Get the values of all attributes of a row in a group .
22,999
def attrput ( self , groupname , attrname , rownr , value , unit = [ ] , meas = [ ] ) : return self . _attrput ( groupname , attrname , rownr , value , unit , meas )
Put the value and optionally unit and measinfo of an attribute in a row in a group .