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 = { "appPath" : applicationPath , "appPathData" : os . path . join ( applicationPath , "data" ) , "appPathDefaults" : os . path . join ( applicationPath , "default" ) , "appPathPlugins" : os . path . join ( applicationPath , "plugins" ) , "appPathWrappers" : os . path . join ( applicationPath , "plugins" , "wrappers" ) , "appPathPatterns" : os . path . join ( applicationPath , "plugins" , "patterns" ) , } for path in paths . keys ( ) : if not os . path . exists ( paths [ path ] ) : os . makedirs ( paths [ path ] ) return paths | 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 ) as iF : cont = iF . read ( ) with open ( configPath , "w" ) as oF : oF . write ( cont ) except Exception as e : raise errors . DefaultConfigurationFileNotFoundError ( configPath , defaultConfigPath ) config = ConfigParser . ConfigParser ( ) config . read ( configPath ) LISTS = [ "tlds" , "domains" , "platforms" , "extension" , "exclude_platforms" , "exclude_domains" ] for section in config . sections ( ) : incomplete = False if section . lower ( ) == util . lower ( ) : for ( param , value ) in config . items ( section ) : if value == '' : if param in LISTS : value = [ ] else : value = "" elif param in LISTS : value = value . split ( ' ' ) elif param == "threads" : try : value = int ( value ) except Exception as err : raise errors . ConfigurationParameterNotValidError ( configPath , section , param , value ) elif param == "debug" : try : if int ( value ) == 0 : value = False else : value = True except Exception as err : print ( "Something happened when processing this debug option. Resetting to default." ) defaultConfigPath = os . path . join ( getConfigPath ( ) [ "appPathDefaults" ] , "general.cfg" ) try : with open ( defaultConfigPath ) as iF : cont = iF . read ( ) with open ( configPath , "w" ) as oF : oF . write ( cont ) except Exception as e : raise errors . DefaultConfigurationFileNotFoundError ( configPath , defaultConfigPath ) VALUES [ param ] = value break return VALUES | 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 . getInfo ( query = q , process = process , mode = "searchfy" ) if entities != "[]" : results += json . loads ( entities ) return results | 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 : platOptions . append ( parameter ) elif mode == "domainfy" : platOptions = osrframework . domainfy . TLD . keys ( ) platOptions = sorted ( set ( platOptions ) ) platOptions . insert ( 0 , 'all' ) return platOptions | 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 nicks : for e in email_providers . domains : candidate_emails . add ( "{}@{}" . format ( n , e ) ) return candidate_emails | 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.resolvethem.com" , "Referer" : "http://www.resolvethem.com/index.php" , "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0" , "Content-Length" : "26" , "Content-Type" : "application/x-www-form-urlencoded" , } req = requests . post ( "http://www.resolvethem.com/index.php" , headers = headers , data = { 'skypeUsername' : alias , 'submit' : '' } ) data = req . content p = re . compile ( "class='alert alert-success'>([0-9\.]*)<" ) allMatches = p . findall ( data ) if len ( allMatches ) > 0 : jsonData = { } jsonData [ "type" ] = "i3visio.ip" jsonData [ "value" ] = allMatches [ 0 ] jsonData [ "attributes" ] = [ ] return jsonData return { } | 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 ) return super ( SharableGlossaryMixin , self ) . get_form ( request , obj , ** kwargs ) | 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_mixins + ( base_model , ) attrs = dict ( attrs or { } , Meta = Meta , __module__ = module ) Model = type ( name , bases , attrs ) fake_proxy_models [ name ] = bases return Model | 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_classes ) parent_classes . update ( TransparentContainer . get_plugins ( ) ) return list ( parent_classes ) | 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 = parent ) if isinstance ( child_glossary , dict ) : child . glossary . update ( child_glossary ) child . save ( ) | 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 : parent_id = CMSPlugin . objects . filter ( id = request . resolver_match . args [ 0 ] ) . only ( "parent_id" ) . order_by ( '?' ) . first ( ) . parent_id except ( AttributeError , IndexError ) : parent_id = None else : parent_id = None for model in CascadeModelBase . _get_cascade_elements ( ) : try : return model . objects . get ( id = parent_id ) except model . DoesNotExist : continue | 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 ( instance . pk ) and element_id == value : msg = _ ( "The element ID '{}' is not unique for this page." ) raise ValidationError ( msg . format ( element_id ) ) | 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 ) return ( None , None ) | 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_classes . append ( css_class ) elif isinstance ( css_class , list ) : css_classes . extend ( css_class ) return css_classes | 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 ( units ) ) ) endings = ( ' %s ' % ugettext ( "or" ) ) . join ( "'%s'" % u . replace ( '%' , '%%' ) for u in units ) params = { 'label' : '%(label)s' , 'value' : '%(value)s' , 'field' : '%(field)s' , 'endings' : endings } return regex , self . invalid_message % params | 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' , [ ] ) ) last_index = len ( breakpoints ) - 1 fluid = element . glossary . get ( 'fluid' ) for index , bp in enumerate ( breakpoints ) : try : key = 'container_fluid_max_widths' if fluid else 'container_max_widths' max_widths [ bp ] = parent_glossary [ key ] [ bp ] except KeyError : max_widths [ bp ] = BS3_BREAKPOINTS [ bp ] [ 4 if fluid else 3 ] if last_index > 0 : if index == 0 : next_bp = breakpoints [ 1 ] media_queries [ bp ] = [ '(max-width: {0}px)' . format ( BS3_BREAKPOINTS [ next_bp ] [ 0 ] ) ] elif index == last_index : media_queries [ bp ] = [ '(min-width: {0}px)' . format ( BS3_BREAKPOINTS [ bp ] [ 0 ] ) ] else : next_bp = breakpoints [ index + 1 ] media_queries [ bp ] = [ '(min-width: {0}px)' . format ( BS3_BREAKPOINTS [ bp ] [ 0 ] ) , '(max-width: {0}px)' . format ( BS3_BREAKPOINTS [ next_bp ] [ 0 ] ) ] | 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}' . format ( prefix_id , self . name , k ) for k in range ( len ( self . widget . choices ) ) ] else : ids = [ '{0}_{1}' . format ( prefix_id , self . name ) ] return ids | 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 . UserModel . DoesNotExist , KeyError ) : pass return context_override | 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 ( 'emulate_user_id' ) if emulate_user_id == obj . id : return format_html ( '<strong>{}</strong>' , identifier ) fmtargs = { 'href' : reverse ( 'admin:emulate-user' , kwargs = { 'user_id' : obj . id } ) , 'identifier' : identifier , } return format_html ( '<a href="{href}" class="emulate-user">{identifier}</a>' , ** fmtargs ) opts = self . UserModel . _meta app_label = opts . app_label user_model_admin = self . admin_site . _registry [ self . UserModel ] request . _lookup_model = self . UserModel list_display_links = user_model_admin . get_list_display_links ( request , user_model_admin . list_display ) list_display_link = list_display_links [ 0 ] try : list_display = list ( user_model_admin . segmentation_list_display ) except AttributeError : list_display = list ( user_model_admin . list_display ) list_display . remove ( list_display_link ) list_display . insert ( 0 , 'display_as_link' ) display_as_link . allow_tags = True try : display_as_link . short_description = user_model_admin . identifier . short_description except AttributeError : display_as_link . short_description = admin . utils . label_for_field ( list_display_link , self . UserModel ) self . display_as_link = six . create_bound_method ( display_as_link , self ) ChangeList = self . get_changelist ( request ) cl = ChangeList ( request , self . UserModel , list_display , ( None , ) , user_model_admin . list_filter , user_model_admin . date_hierarchy , user_model_admin . search_fields , user_model_admin . list_select_related , user_model_admin . list_per_page , user_model_admin . list_max_show_all , ( ) , self ) cl . formset = None selection_note_all = ungettext ( '%(total_count)s selected' , 'All %(total_count)s selected' , cl . result_count ) context = { 'module_name' : force_text ( opts . verbose_name_plural ) , 'selection_note' : _ ( '0 of %(cnt)s selected' ) % { 'cnt' : len ( cl . result_list ) } , 'selection_note_all' : selection_note_all % { 'total_count' : cl . result_count } , 'title' : _ ( "Select %(user_model)s to emulate" ) % { 'user_model' : opts . verbose_name } , 'is_popup' : cl . is_popup , 'cl' : cl , 'media' : self . media , 'has_add_permission' : False , 'opts' : cl . opts , 'app_label' : app_label , 'actions_on_top' : self . actions_on_top , 'actions_on_bottom' : self . actions_on_bottom , 'actions_selection_counter' : self . actions_selection_counter , 'preserved_filters' : self . get_preserved_filters ( request ) , } return TemplateResponse ( request , self . change_list_template or [ 'admin/%s/%s/change_list.html' % ( app_label , opts . model_name ) , 'admin/%s/change_list.html' % app_label , 'admin/change_list.html' ] , context ) | 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 ( ) if model is None : sender . revoke_permissions ( ctype ) ContentType . objects . get ( app_label = sender . label , model = ctype ) . delete ( ) except DatabaseError : return | 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 : sender . grant_permissions ( proxy_model ) | 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_permissions : searched_perms . append ( ( '{0}_{1}' . format ( perm , proxy_model . _meta . model_name ) , "Can {0} {1}" . format ( perm , proxy_model . _meta . verbose_name_raw ) ) ) all_perms = set ( Permission . objects . filter ( content_type = ctype , ) . values_list ( 'content_type' , 'codename' ) ) permissions = [ Permission ( codename = codename , name = name , content_type = ctype ) for codename , name in searched_perms if ( ctype . pk , codename ) not in all_perms ] Permission . objects . bulk_create ( permissions ) | 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_model ( self . label , 'cascadeelement' ) element_ctype = ContentType . objects . get_for_model ( cascade_element ) Permission . objects . filter ( content_type = element_ctype , codename__in = codenames ) . delete ( ) | 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 , * args , ** kwargs ) | 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' ) ) return strings | 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 ( chars ) component = [ ] while True : c , n = next ( chars ) if c == "'" and n == "'" : component += "'" next ( chars ) elif c == "'" : yield "" . join ( component ) break else : component += c except StopIteration : return return list ( yield_components ( path ) ) | 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 . data , index = index ) return pd . DataFrame . from_dict ( dataframe_dict ) | 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 root . properties . items ( ) : container_group . attrs [ property_name ] = property_value except KeyError : pass for group_name in self . groups ( ) : try : group = self . object ( group_name ) for prop_name , prop_value in group . properties . items ( ) : container_group [ group_name ] . attrs [ prop_name ] = prop_value except KeyError : pass for channel in self . group_channels ( group_name ) : for prop_name , prop_value in channel . properties . items ( ) : container_group . attrs [ prop_name ] = prop_value container_group [ group_name + '/' + channel . channel ] = channel . data return h5file | 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 ( ) return if not self . toc [ "kTocNewObjList" ] : self . ordered_objects = [ copy ( o ) for o in previous_segment . ordered_objects ] log . debug ( "Reading metadata at %d" , f . tell ( ) ) num_objects = types . Int32 . read ( f , self . endianness ) for obj in range ( num_objects ) : object_path = types . String . read ( f , self . endianness ) if object_path in objects : obj = objects [ object_path ] else : obj = TdmsObject ( object_path , self . tdms_file ) objects [ object_path ] = obj updating_existing = False if not self . toc [ "kTocNewObjList" ] : obj_index = [ i for i , o in enumerate ( self . ordered_objects ) if o . tdms_object is obj ] if len ( obj_index ) > 0 : updating_existing = True log . debug ( "Updating object in segment list" ) obj_index = obj_index [ 0 ] segment_obj = self . ordered_objects [ obj_index ] if not updating_existing : if obj . _previous_segment_object is not None : log . debug ( "Copying previous segment object" ) segment_obj = copy ( obj . _previous_segment_object ) else : log . debug ( "Creating a new segment object" ) segment_obj = _TdmsSegmentObject ( obj , self . endianness ) self . ordered_objects . append ( segment_obj ) segment_obj . _read_metadata ( f ) obj . _previous_segment_object = segment_obj 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 self . ordered_objects if o . has_data ] ) total_data_size = self . next_segment_offset - self . raw_data_offset if data_size < 0 or total_data_size < 0 : raise ValueError ( "Negative data size" ) elif data_size == 0 : if total_data_size != data_size : raise ValueError ( "Zero channel data size but data length based on " "segment offset is %d." % total_data_size ) self . num_chunks = 0 return chunk_remainder = total_data_size % data_size if chunk_remainder == 0 : self . num_chunks = int ( total_data_size // data_size ) for obj in self . ordered_objects : if obj . has_data : obj . tdms_object . number_values += ( obj . number_values * self . num_chunks ) else : log . warning ( "Data size %d is not a multiple of the " "chunk size %d. Will attempt to read last chunk" % ( total_data_size , data_size ) ) self . num_chunks = 1 + int ( total_data_size // data_size ) self . final_chunk_proportion = ( float ( chunk_remainder ) / float ( data_size ) ) for obj in self . ordered_objects : if obj . has_data : obj . tdms_object . number_values += ( obj . number_values * ( self . num_chunks - 1 ) + int ( obj . number_values * self . final_chunk_proportion ) ) | 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 ( self . num_chunks ) : if self . toc [ "kTocInterleavedData" ] : log . debug ( "Data is interleaved" ) data_objects = [ o for o in self . ordered_objects if o . has_data ] all_numpy = all ( ( o . data_type . nptype is not None for o in data_objects ) ) same_length = ( len ( set ( ( o . number_values for o in data_objects ) ) ) == 1 ) if ( all_numpy and same_length ) : self . _read_interleaved_numpy ( f , data_objects ) else : self . _read_interleaved ( f , data_objects ) else : object_data = { } log . debug ( "Data is contiguous" ) for obj in self . ordered_objects : if obj . has_data : if ( chunk == ( self . num_chunks - 1 ) and self . final_chunk_proportion != 1.0 ) : number_values = int ( obj . number_values * self . final_chunk_proportion ) else : number_values = obj . number_values object_data [ obj . path ] = ( obj . _read_values ( f , number_values ) ) for obj in self . ordered_objects : if obj . has_data : obj . tdms_object . _update_data ( object_data [ obj . path ] ) | 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_channel_bytes ) number_bytes = int ( all_channel_bytes * data_objects [ 0 ] . number_values ) combined_data = fromfile ( f , dtype = np . uint8 , count = number_bytes ) combined_data = combined_data . reshape ( - 1 , all_channel_bytes ) data_pos = 0 for ( i , obj ) in enumerate ( data_objects ) : byte_columns = tuple ( range ( data_pos , obj . data_type . size + data_pos ) ) log . debug ( "Byte columns for channel %d: %s" , i , byte_columns ) object_data = combined_data [ : , byte_columns ] . ravel ( ) object_data . dtype = ( np . dtype ( obj . data_type . nptype ) . newbyteorder ( self . endianness ) ) obj . tdms_object . _update_data ( object_data ) data_pos += obj . data_type . size | 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_values for o in data_objects ] ) : for obj in data_objects : if points_added [ obj . path ] < obj . number_values : object_data [ obj . path ] [ points_added [ obj . path ] ] = ( obj . _read_value ( f ) ) points_added [ obj . path ] += 1 for obj in data_objects : obj . tdms_object . _update_data ( object_data [ obj . path ] ) | 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 ( offset , offset + ( periods - 1 ) * increment , periods ) if not absolute_time : return relative_time try : start_time = self . property ( 'wf_start_time' ) except KeyError : raise KeyError ( "Object does not have start time property available." ) try : unit_correction = { 's' : 1e0 , 'ms' : 1e3 , 'us' : 1e6 , 'ns' : 1e9 , } [ accuracy ] except KeyError : raise KeyError ( "Invalid accuracy: {0}" . format ( accuracy ) ) time_type = "timedelta64[{0}]" . format ( accuracy ) return ( np . datetime64 ( start_time ) + ( relative_time * unit_correction ) . astype ( time_type ) ) | 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 , mode = 'w+' , shape = ( self . number_values , ) , dtype = self . data_type . nptype ) else : self . _data = np . zeros ( self . number_values , dtype = self . data_type . nptype ) self . _data_insert_position = 0 if self . _data is not None : log . debug ( "Allocated %d sample slots for %s" , len ( self . _data ) , self . path ) else : log . debug ( "Allocated no space for %s" , self . path ) | 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 ) ) self . _data_insert_position += len ( new_data ) self . _data [ data_pos [ 0 ] : data_pos [ 1 ] ] = new_data else : self . _data . extend ( 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 . group ) ] ) else : return pd . DataFrame ( self . _data , index = time , columns = [ self . path ] ) | 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_length = types . Uint32 . read ( f , endianness ) log . debug ( "mxDAQ format scaler vector size '%d'" % ( self . scaler_vector_length , ) ) if self . scaler_vector_length > 1 : log . error ( "mxDAQ multiple format changing scalers not implemented" ) for idx in range ( self . scaler_vector_length ) : self . scaler_data_type_code = types . Uint32 . read ( f , endianness ) self . scaler_data_type = ( types . tds_data_types [ self . scaler_data_type_code ] ) self . scaler_raw_buffer_index = types . Uint32 . read ( f , endianness ) self . scaler_raw_byte_offset = types . Uint32 . read ( f , endianness ) self . scaler_sample_format_bitmap = types . Uint32 . read ( f , endianness ) self . scale_id = types . Uint32 . read ( f , endianness ) raw_data_widths_length = types . Uint32 . read ( f , endianness ) self . raw_data_widths = np . zeros ( raw_data_widths_length , dtype = np . int32 ) for cnt in range ( raw_data_widths_length ) : self . raw_data_widths [ cnt ] = types . Uint32 . read ( f , endianness ) | 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 : log . debug ( "Object has same data structure as in the previous segment" ) self . has_data = True elif raw_data_index == 0x00001269 or raw_data_index == 0x00001369 : if raw_data_index == 0x00001369 : log . warning ( "DAQmx with Digital Line scaler has not tested" ) self . has_data = True self . tdms_object . has_data = True info = self . _read_metadata_mx ( f ) self . dimension = info . dimension self . data_type = info . data_type self . data_size = info . chunk_size self . number_values = info . chunk_size assert ( len ( info . raw_data_widths ) == 1 ) self . raw_data_width = info . raw_data_widths [ 0 ] else : self . has_data = True self . tdms_object . has_data = True try : self . data_type = types . tds_data_types [ types . Uint32 . read ( f , self . endianness ) ] except KeyError : raise KeyError ( "Unrecognised data type" ) if ( self . tdms_object . data_type is not None and self . data_type != self . tdms_object . data_type ) : raise ValueError ( "Segment object doesn't have the same data " "type as previous segments." ) else : self . tdms_object . data_type = self . data_type log . debug ( "Object data type: %r" , self . tdms_object . data_type ) if ( self . tdms_object . data_type . size is None and self . tdms_object . data_type != types . String ) : raise ValueError ( "Unsupported data type: %r" % self . tdms_object . data_type ) self . dimension = types . Uint32 . read ( f , self . endianness ) if self . dimension != 1 : log . warning ( "Data dimension is not 1" ) self . number_values = types . Uint64 . read ( f , self . endianness ) if self . data_type in ( types . String , ) : self . data_size = types . Uint64 . read ( f , self . endianness ) else : self . data_size = ( self . number_values * self . data_type . size * self . dimension ) log . debug ( "Object number of values in segment: %d" , self . number_values ) num_properties = types . Uint32 . read ( f , self . endianness ) log . debug ( "Reading %d properties" , num_properties ) for i in range ( num_properties ) : prop_name , value = read_property ( f , self . endianness ) self . tdms_object . properties [ prop_name ] = value | 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 ( file , number_values , self . endianness ) data = self . _new_segment_data ( ) for i in range ( number_values ) : data [ i ] = self . data_type . read ( file , self . endianness ) return data | 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 ] , 37 : [ 752566 , 50927009 , 144938320 , 27656823 , 918573 ] , 38 : [ 817186 , 50889578 , 148946169 , 27638706 , 983193 ] , } , index = rsids , ) for rsid in rsids : if rsid in snps . index : build = lookup_build_with_snp_pos ( snps . loc [ rsid ] . pos , df . loc [ rsid ] ) if build is not None : break return build | 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 ( iterable ) if len ( l ) > 1 : return "{0}-{1}" . format ( l [ 0 ] , l [ - 1 ] ) else : return "{0}" . format ( l [ 0 ] ) int_chroms = ", " . join ( as_range ( g ) for _ , g in groupby ( int_chroms , key = lambda n , c = count ( ) : n - next ( c ) ) ) str_chroms = ", " . join ( str_chroms ) if int_chroms != "" and str_chroms != "" : int_chroms += ", " return int_chroms + str_chroms else : return "" | 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 ( ) ) ] ) if y_snps_not_null / y_snps > y_snps_not_null_threshold : return "Male" else : return "Female" x_snps = len ( snps . loc [ snps [ "chrom" ] == "X" ] ) if x_snps == 0 : return "" heterozygous_x_snps = len ( snps . loc [ ( snps [ "chrom" ] == "X" ) & ( snps [ "genotype" ] . notnull ( ) ) & ( snps [ "genotype" ] . str [ 0 ] != snps [ "genotype" ] . str [ 1 ] ) ] ) if heterozygous_x_snps / x_snps > heterozygous_x_snps_threshold : return "Female" else : return "Male" else : return "" | 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" ] . astype ( CategoricalDtype ( categories = sorted_list , ordered = True ) ) snps = snps . sort_values ( [ "chrom" , "pos" ] ) snps [ "chrom" ] = snps [ "chrom" ] . astype ( object ) return snps | 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" ] , index_col = 0 , dtype = { "chrom" : object , "pos" : np . int64 } , ) return sort_snps ( df ) , source | 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/refsnp/" + id ) if response is not None : for item in response [ "primary_snapshot_data" ] [ "placements_with_allele" ] : if "NC_000023" in item [ "seq_id" ] : assigned = self . _assign_snp ( rsid , item [ "alleles" ] , "X" ) elif "NC_000024" in item [ "seq_id" ] : assigned = self . _assign_snp ( rsid , item [ "alleles" ] , "Y" ) else : assigned = False if assigned : if not self . build_detected : self . build = self . _extract_build ( item ) self . build_detected = True continue except Exception as err : print ( err ) | 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 chrom in chromosome_list [ : : - 1 ] : chrom_ybase [ chrom ] = ybase chrom_centers [ chrom ] = ybase + chrom_height / 2.0 ybase += chrom_height + chrom_spacing color_lookup = { "gneg" : ( 202 / 255 , 202 / 255 , 202 / 255 ) , "one_chrom" : ( 0 / 255 , 176 / 255 , 240 / 255 ) , "two_chrom" : ( 66 / 255 , 69 / 255 , 121 / 255 ) , "centromere" : ( 1 , 1 , 1 , 0.6 ) , } df = _patch_chromosomal_features ( cytobands , one_chrom_match , two_chrom_match ) df [ "colors" ] = df [ "gie_stain" ] . apply ( lambda x : color_lookup [ x ] ) figsize = ( 6.5 , 9 ) fig = plt . figure ( figsize = figsize ) ax = fig . add_subplot ( 111 ) for collection in _chromosome_collections ( df , chrom_ybase , chrom_height ) : ax . add_collection ( collection ) ax . set_yticks ( [ chrom_centers [ i ] for i in chromosome_list ] ) ax . set_yticklabels ( chromosome_list ) ax . margins ( 0.01 ) ax . axis ( "tight" ) handles = [ ] if len ( one_chrom_match ) > 0 : one_chrom_patch = patches . Patch ( color = color_lookup [ "one_chrom" ] , label = "One chromosome shared" ) handles . append ( one_chrom_patch ) if len ( two_chrom_match ) > 0 : two_chrom_patch = patches . Patch ( color = color_lookup [ "two_chrom" ] , label = "Two chromosomes shared" ) handles . append ( two_chrom_patch ) no_match_patch = patches . Patch ( color = color_lookup [ "gneg" ] , label = "No shared DNA" ) handles . append ( no_match_patch ) centromere_patch = patches . Patch ( color = ( 234 / 255 , 234 / 255 , 234 / 255 ) , label = "Centromere" ) handles . append ( centromere_patch ) plt . legend ( handles = handles , loc = "lower right" , bbox_to_anchor = ( 0.95 , 0.05 ) ) ax . set_title ( title , fontsize = 14 , fontweight = "bold" ) plt . xlabel ( "Build " + str ( build ) + " Chromosome Position" , fontsize = 10 ) print ( "Saving " + os . path . relpath ( path ) ) plt . tight_layout ( ) plt . savefig ( path ) | 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{}, https://github.com/apriha/lineage\n" "# Generated at {} UTC\n" ) s = s . format ( __version__ , datetime . datetime . utcnow ( ) . strftime ( "%Y-%m-%d %H:%M:%S" ) ) if isinstance ( comment , str ) : s += comment with open ( destination , "w" ) as f : f . write ( s ) with open ( destination , "a" ) as f : df . to_csv ( f , na_rep = "--" , ** kwargs ) return destination except Exception as err : print ( err ) return "" else : print ( "no data to save..." ) return "" | 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 . split ( "." ) [ 0 ] ] = json . loads ( tar_bytes . decode ( "utf-8" ) ) return assembly_mapping_data except Exception as err : print ( err ) return None | 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 Exception as err : print ( err ) return None | 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" , "X" , "Y" , "MT" , ] assembly_mapping_data = source_assembly + "_" + target_assembly destination = os . path . join ( self . _resources_dir , assembly_mapping_data + ".tar.gz" ) if not os . path . exists ( destination ) or not self . _all_chroms_in_tar ( chroms , destination ) : print ( "Downloading {}" . format ( os . path . relpath ( destination ) ) ) try : with tarfile . open ( destination , "w:gz" ) as out_tar : for chrom in chroms : file = chrom + ".json" map_endpoint = ( "/map/human/" + source_assembly + "/" + chrom + "/" + target_assembly + "?" ) response = None retry = 0 while response is None and retry < retries : response = self . _ensembl_rest_client . perform_rest_action ( map_endpoint ) retry += 1 if response is not None : with tempfile . NamedTemporaryFile ( delete = False , mode = "w" ) as f : json . dump ( response , f ) out_tar . add ( f . name , arcname = file ) os . remove ( f . name ) except Exception as err : print ( err ) return None return destination | 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 ) : try : if compress : open_func = gzip . open else : open_func = open with urllib . request . urlopen ( url , timeout = timeout ) as response , open_func ( destination , "wb" ) as f : self . _print_download_msg ( destination ) data = response . read ( ) f . write ( data ) except urllib . error . URLError as err : print ( err ) destination = None if "ftp://" in url : destination = self . _download_file ( url . replace ( "ftp://" , "http://" ) , filename , compress = compress , timeout = timeout , ) except Exception as err : print ( err ) return None return 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 type ( raw_data ) is str : self . _load_snps_helper ( raw_data , discrepant_snp_positions_threshold , discrepant_genotypes_threshold , save_output , ) else : raise TypeError ( "invalid filetype" ) | 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 + ".csv" return lineage . save_df_as_csv ( self . _snps , self . _output_dir , filename , comment = comment , header = [ "chromosome" , "position" , "genotype" ] , ) | 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 ( symbol ) else : raise TypeError ( 'model contains an unknown symbol type, {}' . format ( type ( symbol ) ) ) for der in func . atoms ( sympy . Derivative ) : if der . expr in vars and all ( isinstance ( s , Parameter ) for s in der . variables ) : vars . append ( der ) params . sort ( key = lambda symbol : symbol . name ) vars . sort ( key = lambda symbol : symbol . name ) return vars , params | 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 , printer = SymfitNumPyPrinter , dummify = False ) signature = inspect_sig . signature ( lambdafunc ) sig_parameters = OrderedDict ( signature . parameters ) for arg , lambda_arg in zip ( args , sig_parameters ) : if arg . name != lambda_arg : break else : return lambdafunc lambda_names = sig_parameters . keys ( ) arg_names = [ arg . name for arg in args ] conversion = dict ( zip ( arg_names , lambda_names ) ) @ wraps ( lambdafunc ) def wrapped_lambdafunc ( * ordered_args , ** kwargs ) : converted_kwargs = { conversion [ k ] : v for k , v in kwargs . items ( ) } return lambdafunc ( * ordered_args , ** converted_kwargs ) new_sig_parameters = OrderedDict ( ) for arg_name , dummy_name in conversion . items ( ) : if arg_name == dummy_name : new_sig_parameters [ arg_name ] = sig_parameters [ arg_name ] else : param = sig_parameters [ dummy_name ] param = param . replace ( name = arg_name ) new_sig_parameters [ arg_name ] = param wrapped_lambdafunc . __signature__ = signature . replace ( parameters = new_sig_parameters . values ( ) ) return wrapped_lambdafunc | 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 ) ) return ans return f | 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 ) : model = func else : y = sympy . Dummy ( ) model = CallableNumericalModel ( { y : func } , connectivity_mapping = { y : set ( self . parameters ) } ) return objective_type ( model , data = { y : None for y in model . dependent_vars } ) | 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 resized | 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 self . _pack_output ( ans ) | 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 != constraint . params : raise AssertionError ( 'The constraint should accept the same' ' parameters as used for the fit.' ) constraint_type = constraint . constraint_type constraint = MinimizeModel ( constraint , data = self . objective . data ) elif isinstance ( constraint , sympy . Rel ) : constraint_type = constraint . __class__ constraint = self . objective . model . __class__ . as_constraint ( constraint , self . objective . model ) constraint = MinimizeModel ( constraint , data = self . objective . data ) else : raise TypeError ( 'Unknown type for a constraint.' ) con = { 'type' : types [ constraint_type ] , 'fun' : constraint , } cons . append ( con ) cons = tuple ( cons ) return cons | 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 , hessian | 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_options [ 'minimizer_kwargs' ] and isinstance ( self . local_minimizer , GradientMinimizer ) : minimize_options [ 'minimizer_kwargs' ] [ 'jac' ] = self . local_minimizer . wrapped_jacobian if 'constraints' not in minimize_options [ 'minimizer_kwargs' ] and isinstance ( self . local_minimizer , ConstrainedMinimizer ) : minimize_options [ 'minimizer_kwargs' ] [ 'constraints' ] = self . local_minimizer . wrapped_constraints if 'bounds' not in minimize_options [ 'minimizer_kwargs' ] and isinstance ( self . local_minimizer , BoundedMinimizer ) : minimize_options [ 'minimizer_kwargs' ] [ 'bounds' ] = self . local_minimizer . bounds ans = basinhopping ( self . objective , self . initial_guesses , ** minimize_options ) return self . _pack_output ( ans ) | Execute the basin - hopping minimization . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.