idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
49,500
def getConfigPath ( configFileName = None ) : paths = { } applicationPath = "./" if sys . platform == 'win32' : applicationPath = os . path . expanduser ( os . path . join ( '~\\' , 'OSRFramework' ) ) else : applicationPath = os . path . expanduser ( os . path . join ( '~/' , '.config' , 'OSRFramework' ) ) paths = { "a...
Auxiliar function to get the configuration paths depending on the system
49,501
def returnListOfConfigurationValues ( util ) : VALUES = { } configPath = os . path . join ( getConfigPath ( ) [ "appPath" ] , "general.cfg" ) if not os . path . exists ( configPath ) : defaultConfigPath = os . path . join ( getConfigPath ( ) [ "appPathDefaults" ] , "general.cfg" ) try : with open ( defaultConfigPath ) ...
Method that recovers the configuration information about each program
49,502
def performSearch ( platformNames = [ ] , queries = [ ] , process = False , excludePlatformNames = [ ] ) : platforms = platform_selection . getPlatformsByName ( platformNames , mode = "searchfy" , excludePlatformNames = excludePlatformNames ) results = [ ] for q in queries : for pla in platforms : entities = pla . getI...
Method to perform the search itself on the different platforms .
49,503
def getAllPlatformNames ( mode ) : platOptions = [ ] if mode in [ "phonefy" , "usufy" , "searchfy" , "mailfy" ] : allPlatforms = getAllPlatformObjects ( mode = mode ) for p in allPlatforms : try : parameter = p . parameterName except : parameter = p . platformName . lower ( ) if parameter not in platOptions : platOptio...
Method that defines the whole list of available parameters .
49,504
def from_json ( cls , json_str ) : d = json . loads ( json_str ) return cls . from_dict ( d )
Deserialize the object from a JSON string .
49,505
def createEmails ( nicks = None , nicksFile = None ) : candidate_emails = set ( ) if nicks != None : for n in nicks : for e in email_providers . domains : candidate_emails . add ( "{}@{}" . format ( n , e ) ) elif nicksFile != None : with open ( nicksFile , "r" ) as iF : nicks = iF . read ( ) . splitlines ( ) for n in ...
Method that globally permits to generate the emails to be checked .
49,506
def checkIPFromAlias ( alias = None ) : headers = { "Content-type" : "text/html" , "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" , "Accept-Encoding" : " gzip, deflate" , "Accept-Language" : " es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3" , "Connection" : "keep-alive" , "DNT" : "1" , "Host" : "www....
Method that checks if the given alias is currently connected to Skype and returns its IP address .
49,507
def get_form ( self , request , obj = None , ** kwargs ) : Form = type ( str ( 'ExtSharableForm' ) , ( SharableCascadeForm , kwargs . pop ( 'form' , self . form ) ) , { } ) Form . base_fields [ 'shared_glossary' ] . limit_choices_to = dict ( plugin_type = self . __class__ . __name__ ) kwargs . update ( form = Form ) re...
Extend the form for the given plugin with the form SharableCascadeForm
49,508
def get_min_max_bounds ( self ) : bound = Bound ( 999999.0 , 0.0 ) for bp in Breakpoint : bound . extend ( self . get_bound ( bp ) ) return { 'min' : bound . min , 'max' : bound . max }
Return a dict of min - and max - values for the given column . This is required to estimate the bounds of images .
49,509
def create_proxy_model ( name , model_mixins , base_model , attrs = None , module = None ) : from django . apps import apps class Meta : proxy = True app_label = 'cmsplugin_cascade' name = str ( name + 'Model' ) try : Model = apps . get_registered_model ( Meta . app_label , name ) except LookupError : bases = model_mix...
Create a Django Proxy Model on the fly to be used by any Cascade Plugin .
49,510
def _get_parent_classes_transparent ( cls , slot , page , instance = None ) : parent_classes = super ( CascadePluginBase , cls ) . get_parent_classes ( slot , page , instance ) if parent_classes is None : if cls . get_require_parent ( slot , page ) is False : return parent_classes = [ ] parent_classes = set ( parent_cl...
Return all parent classes including those marked as transparent .
49,511
def extend_children ( self , parent , wanted_children , child_class , child_glossary = None ) : from cms . api import add_plugin current_children = parent . get_num_children ( ) for _ in range ( current_children , wanted_children ) : child = add_plugin ( parent . placeholder , child_class , parent . language , target =...
Extend the number of children so that the parent object contains wanted children . No child will be removed if wanted_children is smaller than the current number of children .
49,512
def get_parent_instance ( self , request = None , obj = None ) : try : parent_id = obj . parent_id except AttributeError : try : parent_id = self . parent . id except AttributeError : if request : parent_id = request . GET . get ( 'plugin_parent' , None ) if parent_id is None : from cms . models import CMSPlugin try : ...
Get the parent model instance corresponding to this plugin . When adding a new plugin the parent might not be available . Therefore as fallback pass in the request object .
49,513
def in_edit_mode ( self , request , placeholder ) : toolbar = getattr ( request , 'toolbar' , None ) edit_mode = getattr ( toolbar , 'edit_mode' , False ) and getattr ( placeholder , 'is_editable' , True ) if edit_mode : edit_mode = placeholder . has_change_permission ( request . user ) return edit_mode
Returns True if the plugin is in edit mode .
49,514
def _get_previous_open_tag ( self , obj ) : prev_instance = self . get_previous_instance ( obj ) if prev_instance and prev_instance . plugin_type == self . __class__ . __name__ : return prev_instance . glossary . get ( 'open_tag' )
Return the open tag of the previous sibling
49,515
def check_unique_element_id ( cls , instance , element_id ) : try : element_ids = instance . placeholder . page . cascadepage . glossary . get ( 'element_ids' , { } ) except ( AttributeError , ObjectDoesNotExist ) : pass else : if element_id : for key , value in element_ids . items ( ) : if str ( key ) != str ( instanc...
Check for uniqueness of the given element_id for the current page . Return None if instance is not yet associated with a page .
49,516
def rectify_partial_form_field ( base_field , partial_form_fields ) : base_field . label = '' base_field . help_text = '' for fieldset in partial_form_fields : if not isinstance ( fieldset , ( list , tuple ) ) : fieldset = [ fieldset ] for field in fieldset : base_field . validators . append ( field . run_validators )
In base_field reset the attributes label and help_text since they are overriden by the partial field . Additionally from the list or list of lists of partial_form_fields append the bound validator methods to the given base field .
49,517
def validate_link ( link_data ) : from django . apps import apps try : Model = apps . get_model ( * link_data [ 'model' ] . split ( '.' ) ) Model . objects . get ( pk = link_data [ 'pk' ] ) except Model . DoesNotExist : raise ValidationError ( _ ( "Unable to link onto '{0}'." ) . format ( Model . __name__ ) )
Check if the given model exists otherwise raise a Validation error
49,518
def parse_responsive_length ( responsive_length ) : responsive_length = responsive_length . strip ( ) if responsive_length . endswith ( 'px' ) : return ( int ( responsive_length . rstrip ( 'px' ) ) , None ) elif responsive_length . endswith ( '%' ) : return ( None , float ( responsive_length . rstrip ( '%' ) ) / 100 ) ...
Takes a string containing a length definition in pixels or percent and parses it to obtain a computational length . It returns a tuple where the first element is the length in pixels and the second element is its length in percent divided by 100 . Note that one of both returned elements is None .
49,519
def get_css_classes ( cls , instance ) : css_classes = [ ] if hasattr ( cls , 'default_css_class' ) : css_classes . append ( cls . default_css_class ) for attr in getattr ( cls , 'default_css_attributes' , [ ] ) : css_class = instance . glossary . get ( attr ) if isinstance ( css_class , six . string_types ) : css_clas...
Returns a list of CSS classes to be added as class = ... to the current HTML tag .
49,520
def get_inline_styles ( cls , instance ) : inline_styles = getattr ( cls , 'default_inline_styles' , { } ) css_style = instance . glossary . get ( 'inline_styles' ) if css_style : inline_styles . update ( css_style ) return inline_styles
Returns a dictionary of CSS attributes to be added as style = ... to the current HTML tag .
49,521
def get_html_tag_attributes ( cls , instance ) : attributes = getattr ( cls , 'html_tag_attributes' , { } ) return dict ( ( attr , instance . glossary . get ( key , '' ) ) for key , attr in attributes . items ( ) )
Returns a dictionary of attributes which shall be added to the current HTML tag . This method normally is called by the models s property method html_tag_ attributes which enriches the HTML tag with those attributes converted to a list as attr1 = val1 attr2 = val2 ... .
49,522
def compile_validation_pattern ( self , units = None ) : if units is None : units = list ( self . POSSIBLE_UNITS ) else : for u in units : if u not in self . POSSIBLE_UNITS : raise ValidationError ( '{} is not a valid unit for a size field' . format ( u ) ) regex = re . compile ( r'^(-?\d+)({})$' . format ( '|' . join ...
Assure that passed in units are valid size units or if missing use all possible units . Return a tuple with a regular expression to be used for validating and an error message in case this validation failed .
49,523
def unset_required_for ( cls , sharable_fields ) : if 'link_content' in cls . base_fields and 'link_content' not in sharable_fields : cls . base_fields [ 'link_content' ] . required = False if 'link_type' in cls . base_fields and 'link' not in sharable_fields : cls . base_fields [ 'link_type' ] . required = False
Fields borrowed by SharedGlossaryAdmin to build its temporary change form only are required if they are declared in sharable_fields . Otherwise just deactivate them .
49,524
def assure_relation ( cls , cms_page ) : try : cms_page . cascadepage except cls . DoesNotExist : cls . objects . create ( extended_object = cms_page )
Assure that we have a foreign key relation pointing from CascadePage onto CMSPage .
49,525
def compute_media_queries ( element ) : parent_glossary = element . get_parent_glossary ( ) element . glossary [ 'container_max_widths' ] = max_widths = { } element . glossary [ 'media_queries' ] = media_queries = { } breakpoints = element . glossary . get ( 'breakpoints' , parent_glossary . get ( 'breakpoints' , [ ] )...
For e given Cascade element compute the current media queries for each breakpoint even for nested containers rows and columns .
49,526
def get_element_ids ( self , prefix_id ) : if isinstance ( self . widget , widgets . MultiWidget ) : ids = [ '{0}_{1}_{2}' . format ( prefix_id , self . name , field_name ) for field_name in self . widget ] elif isinstance ( self . widget , ( widgets . SelectMultiple , widgets . RadioSelect ) ) : ids = [ '{0}_{1}_{2}' ...
Returns a single or a list of element ids one for each input widget of this field
49,527
def get_context_override ( self , request ) : context_override = super ( EmulateUserModelMixin , self ) . get_context_override ( request ) try : if request . user . is_staff : user = self . UserModel . objects . get ( pk = request . session [ 'emulate_user_id' ] ) context_override . update ( user = user ) except ( self...
Override the request object with an emulated user .
49,528
def emulate_users ( self , request ) : def display_as_link ( self , obj ) : try : identifier = getattr ( user_model_admin , list_display_link ) ( obj ) except AttributeError : identifier = admin . utils . lookup_field ( list_display_link , obj , model_admin = self ) [ 2 ] emulate_user_id = request . session . get ( 'em...
The list view
49,529
def pre_migrate ( cls , sender = None , ** kwargs ) : ContentType = apps . get_model ( 'contenttypes' , 'ContentType' ) try : queryset = ContentType . objects . filter ( app_label = sender . label ) for ctype in queryset . exclude ( model__in = sender . get_proxy_models ( ) . keys ( ) ) : model = ctype . model_class ( ...
Iterate over contenttypes and remove those not in proxy models
49,530
def post_migrate ( cls , sender = None , ** kwargs ) : ContentType = apps . get_model ( 'contenttypes' , 'ContentType' ) for model_name , proxy_model in sender . get_proxy_models ( ) . items ( ) : ctype , created = ContentType . objects . get_or_create ( app_label = sender . label , model = model_name ) if created : se...
Iterate over fake_proxy_models and add contenttypes and permissions for missing proxy models if this has not been done by Django yet
49,531
def grant_permissions ( self , proxy_model ) : ContentType = apps . get_model ( 'contenttypes' , 'ContentType' ) try : Permission = apps . get_model ( 'auth' , 'Permission' ) except LookupError : return searched_perms = [ ] ctype = ContentType . objects . get_for_model ( proxy_model ) for perm in self . default_permiss...
Create the default permissions for the just added proxy model
49,532
def revoke_permissions ( self , ctype ) : ContentType = apps . get_model ( 'contenttypes' , 'ContentType' ) try : Permission = apps . get_model ( 'auth' , 'Permission' ) except LookupError : return codenames = [ '{0}_{1}' . format ( perm , ctype ) for perm in self . default_permissions ] cascade_element = apps . get_mo...
Remove all permissions for the content type to be removed
49,533
def to_file ( file , array ) : try : array . tofile ( file ) except ( TypeError , IOError , UnsupportedOperation ) : file . write ( array . tostring ( ) )
Wrapper around ndarray . tofile to support any file - like object
49,534
def write_segment ( self , objects ) : segment = TdmsSegment ( objects ) segment . write ( self . _file )
Write a segment of data to a TDMS file
49,535
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
49,536
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
49,537
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
49,538
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
49,539
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
49,540
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
49,541
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
49,542
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
49,543
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
49,544
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
49,545
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 .
49,546
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
49,547
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
49,548
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
49,549
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
49,550
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
49,551
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
49,552
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
49,553
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 .
49,554
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 .
49,555
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
49,556
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
49,557
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
49,558
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
49,559
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 .
49,560
def get_chromosomes ( snps ) : if isinstance ( snps , pd . DataFrame ) : return list ( pd . unique ( snps [ "chrom" ] ) ) else : return [ ]
Get the chromosomes of SNPs .
49,561
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 .
49,562
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 .
49,563
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 .
49,564
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 .
49,565
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 .
49,566
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 .
49,567
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 .
49,568
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 .
49,569
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 .
49,570
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 .
49,571
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 .
49,572
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 .
49,573
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 .
49,574
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 .
49,575
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 .
49,576
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 .
49,577
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 .
49,578
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 .
49,579
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 .
49,580
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 .
49,581
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 .
49,582
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 .
49,583
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 .
49,584
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 .
49,585
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 .
49,586
def _set_snps ( self , snps , build = 37 ) : self . _snps = snps self . _build = build
Set _snps and _build properties of this Individual .
49,587
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 .
49,588
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 .
49,589
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 .
49,590
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 .
49,591
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 .
49,592
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 .
49,593
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 .
49,594
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 .
49,595
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 .
49,596
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 .
49,597
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 .
49,598
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 .
49,599
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 .