idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
238,400 | def fromfile ( file , dtype , count , * args , ** kwargs ) : try : return np . fromfile ( file , dtype = dtype , count = count , * args , ** kwargs ) except ( TypeError , IOError , UnsupportedOperation ) : return np . frombuffer ( file . read ( count * np . dtype ( dtype ) . itemsize ) , dtype = dtype , count = count ,... | Wrapper around np . fromfile to support any file - like object |
238,401 | def read_property ( f , endianness = "<" ) : prop_name = types . String . read ( f , endianness ) prop_data_type = types . tds_data_types [ types . Uint32 . read ( f , endianness ) ] value = prop_data_type . read ( f , endianness ) log . debug ( "Property %s: %r" , prop_name , value ) return prop_name , value | Read a property from a segment s metadata |
238,402 | def read_string_data ( file , number_values , endianness ) : offsets = [ 0 ] for i in range ( number_values ) : offsets . append ( types . Uint32 . read ( file , endianness ) ) strings = [ ] for i in range ( number_values ) : s = file . read ( offsets [ i + 1 ] - offsets [ i ] ) strings . append ( s . decode ( 'utf-8' ... | Read string raw data |
238,403 | def path_components ( path ) : def yield_components ( path ) : chars = zip_longest ( path , path [ 1 : ] ) try : while True : c , n = next ( chars ) if c != '/' : raise ValueError ( "Invalid path, expected \"/\"" ) elif ( n is not None and n != "'" ) : raise ValueError ( "Invalid path, expected \"'\"" ) else : next ( c... | Convert a path into group and channel name components |
238,404 | def object ( self , * path ) : object_path = self . _path ( * path ) try : return self . objects [ object_path ] except KeyError : raise KeyError ( "Invalid object path: %s" % object_path ) | Get a TDMS object from the file |
238,405 | def groups ( self ) : object_paths = ( path_components ( path ) for path in self . objects ) group_names = ( path [ 0 ] for path in object_paths if len ( path ) > 0 ) groups_set = OrderedDict ( ) for group in group_names : groups_set [ group ] = None return list ( groups_set ) | Return the names of groups in the file |
238,406 | def group_channels ( self , group ) : path = self . _path ( group ) return [ self . objects [ p ] for p in self . objects if p . startswith ( path + '/' ) ] | Returns a list of channel objects for the given group |
238,407 | def as_dataframe ( self , time_index = False , absolute_time = False ) : import pandas as pd dataframe_dict = OrderedDict ( ) for key , value in self . objects . items ( ) : if value . has_data : index = value . time_track ( absolute_time ) if time_index else None dataframe_dict [ key ] = pd . Series ( data = value . d... | Converts the TDMS file to a DataFrame |
238,408 | def as_hdf ( self , filepath , mode = 'w' , group = '/' ) : import h5py h5file = h5py . File ( filepath , mode ) container_group = None if group in h5file : container_group = h5file [ group ] else : container_group = h5file . create_group ( group ) try : root = self . object ( ) for property_name , property_value in ro... | Converts the TDMS file into an HDF5 file |
238,409 | def read_metadata ( self , f , objects , previous_segment = None ) : if not self . toc [ "kTocMetaData" ] : try : self . ordered_objects = previous_segment . ordered_objects except AttributeError : raise ValueError ( "kTocMetaData is not set for segment but " "there is no previous segment" ) self . calculate_chunks ( )... | Read segment metadata section and update object information |
238,410 | def calculate_chunks ( self ) : if self . toc [ 'kTocDAQmxRawData' ] : try : data_size = next ( o . number_values * o . raw_data_width for o in self . ordered_objects if o . has_data and o . number_values * o . raw_data_width > 0 ) except StopIteration : data_size = 0 else : data_size = sum ( [ o . data_size for o in s... | Work out the number of chunks the data is in for cases where the meta data doesn t change at all so there is no lead in . |
238,411 | def read_raw_data ( self , f ) : if not self . toc [ "kTocRawData" ] : return f . seek ( self . data_position ) total_data_size = self . next_segment_offset - self . raw_data_offset log . debug ( "Reading %d bytes of data at %d in %d chunks" % ( total_data_size , f . tell ( ) , self . num_chunks ) ) for chunk in range ... | Read signal data from file |
238,412 | def _read_interleaved_numpy ( self , f , data_objects ) : log . debug ( "Reading interleaved data all at once" ) all_channel_bytes = data_objects [ 0 ] . raw_data_width if all_channel_bytes == 0 : all_channel_bytes = sum ( ( o . data_type . size for o in data_objects ) ) log . debug ( "all_channel_bytes: %d" , all_chan... | Read interleaved data where all channels have a numpy type |
238,413 | def _read_interleaved ( self , f , data_objects ) : log . debug ( "Reading interleaved data point by point" ) object_data = { } points_added = { } for obj in data_objects : object_data [ obj . path ] = obj . _new_segment_data ( ) points_added [ obj . path ] = 0 while any ( [ points_added [ o . path ] < o . number_value... | Read interleaved data that doesn t have a numpy type |
238,414 | def time_track ( self , absolute_time = False , accuracy = 'ns' ) : try : increment = self . property ( 'wf_increment' ) offset = self . property ( 'wf_start_offset' ) except KeyError : raise KeyError ( "Object does not have time properties available." ) periods = len ( self . _data ) relative_time = np . linspace ( of... | Return an array of time or the independent variable for this channel |
238,415 | def _initialise_data ( self , memmap_dir = None ) : if self . number_values == 0 : pass elif self . data_type . nptype is None : self . _data = [ ] else : if memmap_dir : memmap_file = tempfile . NamedTemporaryFile ( mode = 'w+b' , prefix = "nptdms_" , dir = memmap_dir ) self . _data = np . memmap ( memmap_file . file ... | Initialise data array to zeros |
238,416 | def _update_data ( self , new_data ) : log . debug ( "Adding %d data points to data for %s" % ( len ( new_data ) , self . path ) ) if self . _data is None : self . _data = new_data else : if self . data_type . nptype is not None : data_pos = ( self . _data_insert_position , self . _data_insert_position + len ( new_data... | Update the object data with a new array of data |
238,417 | def as_dataframe ( self , absolute_time = False ) : import pandas as pd try : time = self . time_track ( absolute_time ) except KeyError : time = None if self . channel is None : return pd . DataFrame . from_items ( [ ( ch . channel , pd . Series ( ch . data ) ) for ch in self . tdms_file . group_channels ( self . grou... | Converts the TDMS object to a DataFrame |
238,418 | def data ( self ) : if self . _data is None : return np . empty ( ( 0 , 1 ) ) if self . _data_scaled is None : scale = scaling . get_scaling ( self ) if scale is None : self . _data_scaled = self . _data else : self . _data_scaled = scale . scale ( self . _data ) return self . _data_scaled | NumPy array containing data if there is data for this object otherwise None . |
238,419 | def _read_metadata ( self , f , endianness ) : self . data_type = types . tds_data_types [ 0xFFFFFFFF ] self . dimension = types . Uint32 . read ( f , endianness ) if self . dimension != 1 : log . warning ( "Data dimension is not 1" ) self . chunk_size = types . Uint64 . read ( f , endianness ) self . scaler_vector_len... | Read the metadata for a DAQmx raw segment . This is the raw DAQmx - specific portion of the raw data index . |
238,420 | def _read_metadata ( self , f ) : raw_data_index = types . Uint32 . read ( f , self . endianness ) log . debug ( "Reading metadata for object %s" , self . tdms_object . path ) if raw_data_index == 0xFFFFFFFF : log . debug ( "Object has no data in this segment" ) self . has_data = False elif raw_data_index == 0x00000000... | Read object metadata and update object information |
238,421 | def _read_value ( self , file ) : if self . data_type . nptype is not None : dtype = ( np . dtype ( self . data_type . nptype ) . newbyteorder ( self . endianness ) ) return fromfile ( file , dtype = dtype , count = 1 ) return self . data_type . read ( file , self . endianness ) | Read a single value from the given file |
238,422 | def _read_values ( self , file , number_values ) : if self . data_type . nptype is not None : dtype = ( np . dtype ( self . data_type . nptype ) . newbyteorder ( self . endianness ) ) return fromfile ( file , dtype = dtype , count = number_values ) elif self . data_type == types . String : return read_string_data ( fil... | Read all values for this object from a contiguous segment |
238,423 | def _new_segment_data ( self ) : if self . data_type . nptype is not None : return np . zeros ( self . number_values , dtype = self . data_type . nptype ) else : return [ None ] * self . number_values | Return a new array to read the data of the current section into |
238,424 | def detect_build ( snps ) : def lookup_build_with_snp_pos ( pos , s ) : try : return s . loc [ s == pos ] . index [ 0 ] except : return None build = None rsids = [ "rs3094315" , "rs11928389" , "rs2500347" , "rs964481" , "rs2341354" ] df = pd . DataFrame ( { 36 : [ 742429 , 50908372 , 143649677 , 27566744 , 908436 ] , 3... | Detect build of SNPs . |
238,425 | def get_chromosomes ( snps ) : if isinstance ( snps , pd . DataFrame ) : return list ( pd . unique ( snps [ "chrom" ] ) ) else : return [ ] | Get the chromosomes of SNPs . |
238,426 | def get_chromosomes_summary ( snps ) : if isinstance ( snps , pd . DataFrame ) : chroms = list ( pd . unique ( snps [ "chrom" ] ) ) int_chroms = [ int ( chrom ) for chrom in chroms if chrom . isdigit ( ) ] str_chroms = [ chrom for chrom in chroms if not chrom . isdigit ( ) ] def as_range ( iterable ) : l = list ( itera... | Summary of the chromosomes of SNPs . |
238,427 | def determine_sex ( snps , y_snps_not_null_threshold = 0.1 , heterozygous_x_snps_threshold = 0.01 ) : if isinstance ( snps , pd . DataFrame ) : y_snps = len ( snps . loc [ ( snps [ "chrom" ] == "Y" ) ] ) if y_snps > 0 : y_snps_not_null = len ( snps . loc [ ( snps [ "chrom" ] == "Y" ) & ( snps [ "genotype" ] . notnull (... | Determine sex from SNPs using thresholds . |
238,428 | def sort_snps ( snps ) : sorted_list = sorted ( snps [ "chrom" ] . unique ( ) , key = _natural_sort_key ) if "PAR" in sorted_list : sorted_list . remove ( "PAR" ) sorted_list . append ( "PAR" ) if "MT" in sorted_list : sorted_list . remove ( "MT" ) sorted_list . append ( "MT" ) snps [ "chrom" ] = snps [ "chrom" ] . ast... | Sort SNPs based on ordered chromosome list and position . |
238,429 | def get_summary ( self ) : if not self . is_valid ( ) : return None else : return { "source" : self . source , "assembly" : self . assembly , "build" : self . build , "build_detected" : self . build_detected , "snp_count" : self . snp_count , "chromosomes" : self . chromosomes_summary , "sex" : self . sex , } | Get summary of SNPs . |
238,430 | def _read_23andme ( file ) : df = pd . read_csv ( file , comment = "#" , sep = "\t" , na_values = "--" , names = [ "rsid" , "chrom" , "pos" , "genotype" ] , index_col = 0 , dtype = { "chrom" : object } , ) return sort_snps ( df ) , "23andMe" | Read and parse 23andMe file . |
238,431 | def _read_lineage_csv ( file , comments ) : source = "" for comment in comments . split ( "\n" ) : if "Source(s):" in comment : source = comment . split ( "Source(s):" ) [ 1 ] . strip ( ) break df = pd . read_csv ( file , comment = "#" , header = 0 , na_values = "--" , names = [ "rsid" , "chrom" , "pos" , "genotype" ] ... | Read and parse CSV file generated by lineage . |
238,432 | def _read_generic_csv ( file ) : df = pd . read_csv ( file , skiprows = 1 , na_values = "--" , names = [ "rsid" , "chrom" , "pos" , "genotype" ] , index_col = 0 , dtype = { "chrom" : object , "pos" : np . int64 } , ) return sort_snps ( df ) , "generic" | Read and parse generic CSV file . |
238,433 | def _assign_par_snps ( self ) : rest_client = EnsemblRestClient ( server = "https://api.ncbi.nlm.nih.gov" ) for rsid in self . snps . loc [ self . snps [ "chrom" ] == "PAR" ] . index . values : if "rs" in rsid : try : id = rsid . split ( "rs" ) [ 1 ] response = rest_client . perform_rest_action ( "/variation/v0/beta/re... | Assign PAR SNPs to the X or Y chromosome using SNP position . |
238,434 | def plot_chromosomes ( one_chrom_match , two_chrom_match , cytobands , path , title , build ) : chrom_height = 1.25 chrom_spacing = 1 chromosome_list = [ "chr%s" % i for i in range ( 1 , 23 ) ] chromosome_list . append ( "chrY" ) chromosome_list . append ( "chrX" ) ybase = 0 chrom_ybase = { } chrom_centers = { } for ch... | Plots chromosomes with designated markers . |
238,435 | def create_dir ( path ) : try : os . makedirs ( path , exist_ok = True ) except Exception as err : print ( err ) return False if os . path . exists ( path ) : return True else : return False | Create directory specified by path if it doesn t already exist . |
238,436 | def save_df_as_csv ( df , path , filename , comment = None , ** kwargs ) : if isinstance ( df , pd . DataFrame ) and len ( df ) > 0 : try : if not create_dir ( path ) : return "" destination = os . path . join ( path , filename ) print ( "Saving " + os . path . relpath ( destination ) ) s = ( "# Generated by lineage v{... | Save dataframe to a CSV file . |
238,437 | def get_genetic_map_HapMapII_GRCh37 ( self ) : if self . _genetic_map_HapMapII_GRCh37 is None : self . _genetic_map_HapMapII_GRCh37 = self . _load_genetic_map ( self . _get_path_genetic_map_HapMapII_GRCh37 ( ) ) return self . _genetic_map_HapMapII_GRCh37 | Get International HapMap Consortium HapMap Phase II genetic map for Build 37 . |
238,438 | def get_cytoBand_hg19 ( self ) : if self . _cytoBand_hg19 is None : self . _cytoBand_hg19 = self . _load_cytoBand ( self . _get_path_cytoBand_hg19 ( ) ) return self . _cytoBand_hg19 | Get UCSC cytoBand table for Build 37 . |
238,439 | def get_knownGene_hg19 ( self ) : if self . _knownGene_hg19 is None : self . _knownGene_hg19 = self . _load_knownGene ( self . _get_path_knownGene_hg19 ( ) ) return self . _knownGene_hg19 | Get UCSC knownGene table for Build 37 . |
238,440 | def get_kgXref_hg19 ( self ) : if self . _kgXref_hg19 is None : self . _kgXref_hg19 = self . _load_kgXref ( self . _get_path_kgXref_hg19 ( ) ) return self . _kgXref_hg19 | Get UCSC kgXref table for Build 37 . |
238,441 | def get_assembly_mapping_data ( self , source_assembly , target_assembly ) : return self . _load_assembly_mapping_data ( self . _get_path_assembly_mapping_data ( source_assembly , target_assembly ) ) | Get assembly mapping data . |
238,442 | def _load_assembly_mapping_data ( filename ) : try : assembly_mapping_data = { } with tarfile . open ( filename , "r" ) as tar : for member in tar . getmembers ( ) : if ".json" in member . name : with tar . extractfile ( member ) as tar_file : tar_bytes = tar_file . read ( ) assembly_mapping_data [ member . name . spli... | Load assembly mapping data . |
238,443 | def _load_cytoBand ( filename ) : try : df = pd . read_table ( filename , names = [ "chrom" , "start" , "end" , "name" , "gie_stain" ] ) df [ "chrom" ] = df [ "chrom" ] . str [ 3 : ] return df except Exception as err : print ( err ) return None | Load UCSC cytoBand table . |
238,444 | def _load_knownGene ( filename ) : try : df = pd . read_table ( filename , names = [ "name" , "chrom" , "strand" , "txStart" , "txEnd" , "cdsStart" , "cdsEnd" , "exonCount" , "exonStarts" , "exonEnds" , "proteinID" , "alignID" , ] , index_col = 0 , ) df [ "chrom" ] = df [ "chrom" ] . str [ 3 : ] return df except Except... | Load UCSC knownGene table . |
238,445 | def _load_kgXref ( filename ) : try : df = pd . read_table ( filename , names = [ "kgID" , "mRNA" , "spID" , "spDisplayID" , "geneSymbol" , "refseq" , "protAcc" , "description" , "rfamAcc" , "tRnaName" , ] , index_col = 0 , dtype = object , ) return df except Exception as err : print ( err ) return None | Load UCSC kgXref table . |
238,446 | def _get_path_assembly_mapping_data ( self , source_assembly , target_assembly , retries = 10 ) : if not lineage . create_dir ( self . _resources_dir ) : return None chroms = [ "1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" , "11" , "12" , "13" , "14" , "15" , "16" , "17" , "18" , "19" , "20" , "21" , "22" ... | Get local path to assembly mapping data downloading if necessary . |
238,447 | def _download_file ( self , url , filename , compress = False , timeout = 30 ) : if not lineage . create_dir ( self . _resources_dir ) : return None if compress and filename [ - 3 : ] != ".gz" : filename += ".gz" destination = os . path . join ( self . _resources_dir , filename ) if not os . path . exists ( destination... | Download a file to the resources folder . |
238,448 | def load_snps ( self , raw_data , discrepant_snp_positions_threshold = 100 , discrepant_genotypes_threshold = 500 , save_output = False , ) : if type ( raw_data ) is list : for file in raw_data : self . _load_snps_helper ( file , discrepant_snp_positions_threshold , discrepant_genotypes_threshold , save_output , ) elif... | Load raw genotype data . |
238,449 | def save_snps ( self , filename = None ) : comment = ( "# Source(s): {}\n" "# Assembly: {}\n" "# SNPs: {}\n" "# Chromosomes: {}\n" . format ( self . source , self . assembly , self . snp_count , self . chromosomes_summary ) ) if filename is None : filename = self . get_var_name ( ) + "_lineage_" + self . assembly + ".c... | Save SNPs to file . |
238,450 | def remap_snps ( self , target_assembly , complement_bases = True ) : from lineage import Lineage l = Lineage ( ) return l . remap_snps ( self , target_assembly , complement_bases ) | Remap the SNP coordinates of this Individual from one assembly to another . |
238,451 | def _set_snps ( self , snps , build = 37 ) : self . _snps = snps self . _build = build | Set _snps and _build properties of this Individual . |
238,452 | def _double_single_alleles ( df , chrom ) : single_alleles = np . where ( ( df [ "chrom" ] == chrom ) & ( df [ "genotype" ] . str . len ( ) == 1 ) ) [ 0 ] df . ix [ single_alleles , "genotype" ] = df . ix [ single_alleles , "genotype" ] * 2 return df | Double any single alleles in the specified chromosome . |
238,453 | def seperate_symbols ( func ) : params = [ ] vars = [ ] for symbol in func . free_symbols : if not isidentifier ( str ( symbol ) ) : continue if isinstance ( symbol , Parameter ) : params . append ( symbol ) elif isinstance ( symbol , Idx ) : pass elif isinstance ( symbol , ( MatrixExpr , Expr ) ) : vars . append ( sym... | Seperate the symbols in symbolic function func . Return them in alphabetical order . |
238,454 | def sympy_to_py ( func , args ) : derivatives = { var : Variable ( var . name ) for var in args if isinstance ( var , sympy . Derivative ) } func = func . xreplace ( derivatives ) args = [ derivatives [ var ] if isinstance ( var , sympy . Derivative ) else var for var in args ] lambdafunc = lambdify ( args , func , pri... | Turn a symbolic expression into a Python lambda function which has the names of the variables and parameters as it s argument names . |
238,455 | def sympy_to_scipy ( func , vars , params ) : lambda_func = sympy_to_py ( func , vars , params ) def f ( x , p ) : x = np . atleast_2d ( x ) y = [ x [ i ] for i in range ( len ( x ) ) ] if len ( x [ 0 ] ) else [ ] try : ans = lambda_func ( * ( y + list ( p ) ) ) except TypeError : ans = lambda_func ( * list ( p ) ) ret... | Convert a symbolic expression to one scipy digs . Not used by symfit any more . |
238,456 | def jacobian ( expr , symbols ) : jac = [ ] for symbol in symbols : f = sympy . diff ( expr , symbol ) jac . append ( f ) return jac | Derive a symbolic expr w . r . t . each symbol in symbols . This returns a symbolic jacobian vector . |
238,457 | def name ( self ) : base_str = 'd{}{}_' . format ( self . derivative_count if self . derivative_count > 1 else '' , self . expr ) for var , count in self . variable_count : base_str += 'd{}{}' . format ( var , count if count > 1 else '' ) return base_str | Save name which can be used for alphabetic sorting and can be turned into a kwarg . |
238,458 | def _baseobjective_from_callable ( self , func , objective_type = MinimizeModel ) : if isinstance ( func , BaseObjective ) or ( hasattr ( func , '__self__' ) and isinstance ( func . __self__ , BaseObjective ) ) : return func else : from . fit import CallableNumericalModel , BaseModel if isinstance ( func , BaseModel ) ... | symfit works with BaseObjective subclasses internally . If a custom objective is provided we wrap it into a BaseObjective MinimizeModel by default . |
238,459 | def resize_jac ( self , func ) : if func is None : return None @ wraps ( func ) def resized ( * args , ** kwargs ) : out = func ( * args , ** kwargs ) out = np . atleast_1d ( np . squeeze ( out ) ) mask = [ p not in self . _fixed_params for p in self . parameters ] return out [ mask ] return resized | Removes values with identical indices to fixed parameters from the output of func . func has to return the jacobian of a scalar function . |
238,460 | def resize_hess ( self , func ) : if func is None : return None @ wraps ( func ) def resized ( * args , ** kwargs ) : out = func ( * args , ** kwargs ) out = np . atleast_2d ( np . squeeze ( out ) ) mask = [ p not in self . _fixed_params for p in self . parameters ] return np . atleast_2d ( out [ mask , mask ] ) return... | Removes values with identical indices to fixed parameters from the output of func . func has to return the Hessian of a scalar function . |
238,461 | def execute ( self , bounds = None , jacobian = None , hessian = None , constraints = None , ** minimize_options ) : ans = minimize ( self . objective , self . initial_guesses , method = self . method_name ( ) , bounds = bounds , constraints = constraints , jac = jacobian , hess = hessian , ** minimize_options ) return... | Calls the wrapped algorithm . |
238,462 | def scipy_constraints ( self , constraints ) : cons = [ ] types = { sympy . Eq : 'eq' , sympy . Ge : 'ineq' , } for constraint in constraints : if isinstance ( constraint , MinimizeModel ) : constraint_type = constraint . model . constraint_type elif hasattr ( constraint , 'constraint_type' ) : if self . parameters != ... | Returns all constraints in a scipy compatible format . |
238,463 | def _get_jacobian_hessian_strategy ( self ) : if self . jacobian is not None and self . hessian is None : jacobian = None hessian = 'cs' elif self . jacobian is None and self . hessian is None : jacobian = 'cs' hessian = soBFGS ( exception_strategy = 'damp_update' ) else : jacobian = None hessian = None return jacobian... | Figure out how to calculate the jacobian and hessian . Will return a tuple describing how best to calculate the jacobian and hessian repectively . If None it should be calculated using the available analytical method . |
238,464 | def execute ( self , ** minimize_options ) : if 'minimizer_kwargs' not in minimize_options : minimize_options [ 'minimizer_kwargs' ] = { } if 'method' not in minimize_options [ 'minimizer_kwargs' ] : minimize_options [ 'minimizer_kwargs' ] [ 'method' ] = self . local_minimizer . method_name ( ) if 'jac' not in minimize... | Execute the basin - hopping minimization . |
238,465 | def _print_MatMul ( self , expr ) : from sympy import MatrixExpr links = [ ] for i , j in zip ( expr . args [ 1 : ] , expr . args [ : - 1 ] ) : if isinstance ( i , MatrixExpr ) and isinstance ( j , MatrixExpr ) : links . append ( ').dot(' ) else : links . append ( '*' ) printouts = [ self . _print ( i ) for i in expr .... | Matrix multiplication printer . The sympy one turns everything into a dot product without type - checking . |
238,466 | def execute ( self , ** kwargs ) : show = kwargs . pop ( 'show' ) if show : plt . show ( ** kwargs ) | Execute the interactive guessing procedure . |
238,467 | def _set_up_sliders ( self ) : i = 0.05 self . _sliders = { } for param in self . model . params : if not param . fixed : axbg = 'lightgoldenrodyellow' else : axbg = 'red' ax = self . fig . add_axes ( ( 0.162 , i , 0.68 , 0.03 ) , facecolor = axbg , label = param ) val = param . value if not hasattr ( param , 'min' ) o... | Creates an slider for every parameter . |
238,468 | def _update_plot ( self , _ ) : for param in self . model . params : param . value = self . _sliders [ param ] . val for indep_var , dep_var in self . _projections : self . _update_specific_plot ( indep_var , dep_var ) | Callback to redraw the plot to reflect the new parameter values . |
238,469 | def _eval_model ( self ) : arguments = self . _x_grid . copy ( ) arguments . update ( { param : param . value for param in self . model . params } ) return self . model ( ** key2str ( arguments ) ) | Convenience method for evaluating the model with the current parameters |
238,470 | def plot_data ( self , proj , ax ) : x , y = proj ax . scatter ( self . ig . independent_data [ x ] , self . ig . dependent_data [ y ] , c = 'b' ) | Creates and plots a scatter plot of the original data . |
238,471 | def plot_data ( self , proj , ax ) : x , y = proj x_data = self . ig . independent_data [ x ] y_data = self . ig . dependent_data [ y ] projected_data = np . column_stack ( ( x_data , y_data ) ) . T kde = gaussian_kde ( projected_data ) xx , yy = np . meshgrid ( self . ig . _x_points [ x ] , self . ig . _y_points [ y ]... | Creates and plots the contourplot of the original data . This is done by evaluating the density of projected datapoints on a grid . |
238,472 | def BivariateGaussian ( x , y , mu_x , mu_y , sig_x , sig_y , rho ) : exponent = - 1 / ( 2 * ( 1 - rho ** 2 ) ) exponent *= ( x - mu_x ) ** 2 / sig_x ** 2 + ( y - mu_y ) ** 2 / sig_y ** 2 - 2 * rho * ( x - mu_x ) * ( y - mu_y ) / ( sig_x * sig_y ) return sympy . exp ( exponent ) / ( 2 * sympy . pi * sig_x * sig_y * sym... | Bivariate Gaussian pdf . |
238,473 | def r_squared ( model , fit_result , data ) : y_is = [ data [ var ] for var in model if var in data ] x_is = [ value for var , value in data . items ( ) if var . name in model . __signature__ . parameters ] y_bars = [ np . mean ( y_i ) if y_i is not None else None for y_i in y_is ] f_is = model ( * x_is , ** fit_result... | Calculates the coefficient of determination R^2 for the fit . |
238,474 | def _partial_subs ( func , func2vars ) : if isinstance ( func , sympy . Derivative ) : new_func = func . expr . xreplace ( func2vars ) new_variables = tuple ( var . xreplace ( func2vars ) for var in func . variables ) return _partial_diff ( new_func , * new_variables ) else : return func . xreplace ( func2vars ) | Partial - bug proof substitution . Works by making the substitutions on the expression inside the derivative first and then rebuilding the derivative safely without evaluating it using _partial_diff . |
238,475 | def _init_from_dict ( self , model_dict ) : sort_func = lambda symbol : symbol . name self . model_dict = OrderedDict ( sorted ( model_dict . items ( ) , key = lambda i : sort_func ( i [ 0 ] ) ) ) ordered = list ( toposort ( self . connectivity_mapping ) ) independent = sorted ( ordered . pop ( 0 ) , key = sort_func ) ... | Initiate self from a model_dict to make sure attributes such as vars params are available . |
238,476 | def function_dict ( self ) : func_dict = OrderedDict ( ) for var , func in self . vars_as_functions . items ( ) : expr = self . model_dict [ var ] . xreplace ( self . vars_as_functions ) func_dict [ func ] = expr return func_dict | Equivalent to self . model_dict but with all variables replaced by functions if applicable . Sorted by the evaluation order according to self . ordered_symbols not alphabetical like self . model_dict ! |
238,477 | def _model_sanity ( model ) : if not isinstance ( model , ODEModel ) and not isinstance ( model , BaseNumericalModel ) : for var , expr in model . items ( ) : if isinstance ( var , sympy . Derivative ) or expr . has ( sympy . Derivative ) : warnings . warn ( RuntimeWarning ( 'The model contains derivatives in its defin... | Perform some basic sanity checking on the model to warn users when they might be trying something ill advised . |
238,478 | def data_shapes ( self ) : independent_shapes = [ ] for var , data in self . independent_data . items ( ) : if data is not None : independent_shapes . append ( data . shape ) dependent_shapes = [ ] for var , data in self . dependent_data . items ( ) : if data is not None : dependent_shapes . append ( data . shape ) ret... | Returns the shape of the data . In most cases this will be the same for all variables of the same type if not this raises an Exception . |
238,479 | def execute ( self , ** minimize_options ) : minimizer_ans = self . minimizer . execute ( ** minimize_options ) try : cov_matrix = minimizer_ans . covariance_matrix except AttributeError : cov_matrix = self . covariance_matrix ( dict ( zip ( self . model . params , minimizer_ans . _popt ) ) ) else : if cov_matrix is No... | Execute the fit . |
238,480 | def eval_components ( self , * args , ** kwargs ) : bound_arguments = self . __signature__ . bind ( * args , ** kwargs ) t_like = bound_arguments . arguments [ self . independent_vars [ 0 ] . name ] f = lambda ys , t , * a : [ c ( t , * ( list ( ys ) + list ( a ) ) ) for c in self . _ncomponents ] Dfun = lambda ys , t ... | Numerically integrate the system of ODEs . |
238,481 | def call ( self , * values , ** named_values ) : independent_vars , params = seperate_symbols ( self ) func = sympy_to_py ( self , independent_vars + params ) parameters = [ inspect_sig . Parameter ( arg . name , inspect_sig . Parameter . POSITIONAL_OR_KEYWORD ) for arg in independent_vars + params ] arg_names = [ arg ... | Call an expression to evaluate it at the given point . |
238,482 | def variance ( self , param ) : param_number = self . model . params . index ( param ) try : return self . covariance_matrix [ param_number , param_number ] except TypeError : return None | Return the variance in a given parameter as found by the fit . |
238,483 | def covariance ( self , param_1 , param_2 ) : param_1_number = self . model . params . index ( param_1 ) param_2_number = self . model . params . index ( param_2 ) return self . covariance_matrix [ param_1_number , param_2_number ] | Return the covariance between param_1 and param_2 . |
238,484 | def _array_safe_dict_eq ( one_dict , other_dict ) : for key in one_dict : try : assert one_dict [ key ] == other_dict [ key ] except ValueError as err : if isinstance ( one_dict [ key ] , dict ) : assert FitResults . _array_safe_dict_eq ( one_dict [ key ] , other_dict [ key ] ) else : assert np . allclose ( one_dict [ ... | Dicts containing arrays are hard to compare . This function uses numpy . allclose to compare arrays and does normal comparison for all other types . |
238,485 | def nonanalytical_func ( x , a , b ) : y = np . zeros_like ( x ) y [ x > b ] = ( a * ( x - b ) + b ) [ x > b ] y [ x <= b ] = b return y | This can be any pythonic function which should be fitted typically one which is not easily written or supported as an analytical expression . |
238,486 | def get_form ( self , request , obj = None , ** kwargs ) : if obj : if obj . alternatives : choices = [ ( alternative , alternative ) for alternative in obj . alternatives . keys ( ) ] else : choices = [ ( conf . CONTROL_GROUP , conf . CONTROL_GROUP ) ] class ExperimentModelForm ( forms . ModelForm ) : default_alternat... | Add the default alternative dropdown with appropriate choices |
238,487 | def set_alternative_view ( self , request ) : if not request . user . has_perm ( 'experiments.change_experiment' ) : return HttpResponseForbidden ( ) experiment_name = request . POST . get ( "experiment" ) alternative_name = request . POST . get ( "alternative" ) if not ( experiment_name and alternative_name ) : return... | Allows the admin user to change their assigned alternative |
238,488 | def set_state_view ( self , request ) : if not request . user . has_perm ( 'experiments.change_experiment' ) : return HttpResponseForbidden ( ) try : state = int ( request . POST . get ( "state" , "" ) ) except ValueError : return HttpResponseBadRequest ( ) try : experiment = Experiment . objects . get ( name = request... | Changes the experiment state |
238,489 | def get_alternative ( self , experiment_name ) : experiment = None try : experiment = experiment_manager [ experiment_name ] except KeyError : pass if experiment : if experiment . is_displaying_alternatives ( ) : alternative = self . _get_enrollment ( experiment ) if alternative is not None : return alternative else : ... | Get the alternative this user is enrolled in . |
238,490 | def set_alternative ( self , experiment_name , alternative ) : experiment = experiment_manager . get_experiment ( experiment_name ) if experiment : self . _set_enrollment ( experiment , alternative ) | Explicitly set the alternative the user is enrolled in for the specified experiment . |
238,491 | def goal ( self , goal_name , count = 1 ) : for enrollment in self . _get_all_enrollments ( ) : if enrollment . experiment . is_displaying_alternatives ( ) : self . _experiment_goal ( enrollment . experiment , enrollment . alternative , goal_name , count ) | Record that this user has performed a particular goal |
238,492 | def incorporate ( self , other_user ) : for enrollment in other_user . _get_all_enrollments ( ) : if not self . _get_enrollment ( enrollment . experiment ) : self . _set_enrollment ( enrollment . experiment , enrollment . alternative , enrollment . enrollment_date , enrollment . last_seen ) goals = self . experiment_co... | Incorporate all enrollments and goals performed by the other user |
238,493 | def visit ( self ) : for enrollment in self . _get_all_enrollments ( ) : if enrollment . experiment . is_displaying_alternatives ( ) : if not enrollment . last_seen : self . _experiment_goal ( enrollment . experiment , enrollment . alternative , conf . VISIT_NOT_PRESENT_COUNT_GOAL , 1 ) self . _set_last_seen ( enrollme... | Record that the user has visited the site for the purposes of retention tracking |
238,494 | def flatten_pages ( self , pages , level = 1 ) : flattened = [ ] for page in pages : if type ( page ) is list : flattened . append ( { 'file' : page [ 0 ] , 'title' : page [ 1 ] , 'level' : level , } ) if type ( page ) is dict : if type ( list ( page . values ( ) ) [ 0 ] ) is str : flattened . append ( { 'file' : list ... | Recursively flattens pages data structure into a one - dimensional data structure |
238,495 | def convert ( self ) : lines = [ ] pages = self . flatten_pages ( self . config [ 'pages' ] ) f_exclude = mkdocs_pandoc . filters . exclude . ExcludeFilter ( exclude = self . exclude ) f_include = mkdocs_pandoc . filters . include . IncludeFilter ( base_path = self . config [ 'docs_dir' ] , encoding = self . encoding )... | User - facing conversion method . Returns pandoc document as a list of lines . |
238,496 | def blocks ( self , lines ) : state = markdown . blockparser . State ( ) blocks = [ ] state . set ( 'start' ) currblock = 0 for line in lines : line += '\n' if state . isstate ( 'start' ) : if line [ : 3 ] == '```' : state . set ( '```' ) else : state . set ( '\n' ) blocks . append ( '' ) currblock = len ( blocks ) - 1... | Groups lines into markdown blocks |
238,497 | def ruler_line ( self , widths , linetype = '-' ) : cells = [ ] for w in widths : cells . append ( linetype * ( w + 2 ) ) return '+' + '+' . join ( cells ) + '+' | Generates a ruler line for separating rows from each other |
238,498 | def wrap_row ( self , widths , row , width_default = None ) : lines = [ ] longest = 0 if not width_default : width_default = self . width_default for i in range ( 0 , len ( row ) ) : w = width_default if i < len ( widths ) : w = widths [ i ] tw = textwrap . TextWrapper ( width = w , break_on_hyphens = False ) row [ i ]... | Wraps a single line table row into a fixed width multi - line table . |
238,499 | def render_export_form ( self , request , context , form_url = '' ) : context . update ( { 'has_change_permission' : self . has_change_permission ( request ) , 'form_url' : mark_safe ( form_url ) , 'opts' : self . opts , 'add' : True , 'save_on_top' : self . save_on_top , } ) return TemplateResponse ( request , self . ... | Render the from submission export form . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.