idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
17,700 | def send_invitation ( self , invitation , ** kwargs ) : return self . email_message ( invitation . invitee_identifier , self . invitation_subject , self . invitation_body , invitation . invited_by , ** kwargs ) . send ( ) | Sends an invitation message for a specific invitation . |
17,701 | def email_message ( self , recipient , subject_template , body_template , sender = None , message_class = EmailMessage , ** kwargs ) : from_email = "%s %s <%s>" % ( sender . first_name , sender . last_name , email . utils . parseaddr ( settings . DEFAULT_FROM_EMAIL ) [ 1 ] , ) reply_to = "%s %s <%s>" % ( sender . first_name , sender . last_name , sender . email ) headers = { "Reply-To" : reply_to } kwargs . update ( { "sender" : sender , "recipient" : recipient } ) subject_template = loader . get_template ( subject_template ) body_template = loader . get_template ( body_template ) subject = subject_template . render ( kwargs ) . strip ( ) body = body_template . render ( kwargs ) return message_class ( subject , body , from_email , [ recipient ] , headers = headers ) | Returns an invitation email message . This can be easily overridden . For instance to send an HTML message use the EmailMultiAlternatives message_class and attach the additional conent . |
17,702 | def update_org ( cls , module ) : try : cls . module_registry [ module ] [ "OrgModel" ] . _meta . get_field ( "users" ) except FieldDoesNotExist : cls . module_registry [ module ] [ "OrgModel" ] . add_to_class ( "users" , models . ManyToManyField ( USER_MODEL , through = cls . module_registry [ module ] [ "OrgUserModel" ] . __name__ , related_name = "%(app_label)s_%(class)s" , ) , ) cls . module_registry [ module ] [ "OrgModel" ] . invitation_model = cls . module_registry [ module ] [ "OrgInviteModel" ] | Adds the users field to the organization model |
17,703 | def update_org_users ( cls , module ) : try : cls . module_registry [ module ] [ "OrgUserModel" ] . _meta . get_field ( "user" ) except FieldDoesNotExist : cls . module_registry [ module ] [ "OrgUserModel" ] . add_to_class ( "user" , models . ForeignKey ( USER_MODEL , related_name = "%(app_label)s_%(class)s" , on_delete = models . CASCADE , ) , ) try : cls . module_registry [ module ] [ "OrgUserModel" ] . _meta . get_field ( "organization" ) except FieldDoesNotExist : cls . module_registry [ module ] [ "OrgUserModel" ] . add_to_class ( "organization" , models . ForeignKey ( cls . module_registry [ module ] [ "OrgModel" ] , related_name = "organization_users" , on_delete = models . CASCADE , ) , ) | Adds the user field to the organization user model and the link to the specific organization model . |
17,704 | def update_org_owner ( cls , module ) : try : cls . module_registry [ module ] [ "OrgOwnerModel" ] . _meta . get_field ( "organization_user" ) except FieldDoesNotExist : cls . module_registry [ module ] [ "OrgOwnerModel" ] . add_to_class ( "organization_user" , models . OneToOneField ( cls . module_registry [ module ] [ "OrgUserModel" ] , on_delete = models . CASCADE , ) , ) try : cls . module_registry [ module ] [ "OrgOwnerModel" ] . _meta . get_field ( "organization" ) except FieldDoesNotExist : cls . module_registry [ module ] [ "OrgOwnerModel" ] . add_to_class ( "organization" , models . OneToOneField ( cls . module_registry [ module ] [ "OrgModel" ] , related_name = "owner" , on_delete = models . CASCADE , ) , ) | Creates the links to the organization and organization user for the owner . |
17,705 | def update_org_invite ( cls , module ) : try : cls . module_registry [ module ] [ "OrgInviteModel" ] . _meta . get_field ( "invited_by" ) except FieldDoesNotExist : cls . module_registry [ module ] [ "OrgInviteModel" ] . add_to_class ( "invited_by" , models . ForeignKey ( USER_MODEL , related_name = "%(app_label)s_%(class)s_sent_invitations" , on_delete = models . CASCADE , ) , ) try : cls . module_registry [ module ] [ "OrgInviteModel" ] . _meta . get_field ( "invitee" ) except FieldDoesNotExist : cls . module_registry [ module ] [ "OrgInviteModel" ] . add_to_class ( "invitee" , models . ForeignKey ( USER_MODEL , null = True , blank = True , related_name = "%(app_label)s_%(class)s_invitations" , on_delete = models . CASCADE , ) , ) try : cls . module_registry [ module ] [ "OrgInviteModel" ] . _meta . get_field ( "organization" ) except FieldDoesNotExist : cls . module_registry [ module ] [ "OrgInviteModel" ] . add_to_class ( "organization" , models . ForeignKey ( cls . module_registry [ module ] [ "OrgModel" ] , related_name = "organization_invites" , on_delete = models . CASCADE , ) , ) | Adds the links to the organization and to the organization user |
17,706 | def user_relation_name ( self ) : return "{0}_{1}" . format ( self . _meta . app_label . lower ( ) , self . __class__ . __name__ . lower ( ) ) | Returns the string name of the related name to the user . |
17,707 | def activate ( self , user ) : org_user = self . organization . add_user ( user , ** self . activation_kwargs ( ) ) self . invitee = user self . save ( ) return org_user | Updates the invitee value and saves the instance |
17,708 | def get_object ( self ) : if hasattr ( self , "organization_user" ) : return self . organization_user organization_pk = self . kwargs . get ( "organization_pk" , None ) user_pk = self . kwargs . get ( "user_pk" , None ) self . organization_user = get_object_or_404 ( self . get_user_model ( ) . objects . select_related ( ) , user__pk = user_pk , organization__pk = organization_pk , ) return self . organization_user | Returns the OrganizationUser object based on the primary keys for both the organization and the organization user . |
17,709 | def check_token ( self , user , token ) : try : ts_b36 , hash = token . split ( "-" ) except ValueError : return False try : ts = base36_to_int ( ts_b36 ) except ValueError : return False if not constant_time_compare ( self . _make_token_with_timestamp ( user , ts ) , token ) : return False if ( self . _num_days ( self . _today ( ) ) - ts ) > REGISTRATION_TIMEOUT_DAYS : return False return True | Check that a password reset token is correct for a given user . |
17,710 | def create_organization ( user , name , slug = None , is_active = None , org_defaults = None , org_user_defaults = None , ** kwargs ) : org_model = kwargs . pop ( "model" , None ) or kwargs . pop ( "org_model" , None ) or default_org_model ( ) kwargs . pop ( "org_user_model" , None ) org_owner_model = org_model . owner . related . related_model try : org_user_model = org_model . organization_users . rel . related_model except AttributeError : org_user_model = org_model . organization_users . related . related_model if org_defaults is None : org_defaults = { } if org_user_defaults is None : if "is_admin" in model_field_names ( org_user_model ) : org_user_defaults = { "is_admin" : True } else : org_user_defaults = { } if slug is not None : org_defaults . update ( { "slug" : slug } ) if is_active is not None : org_defaults . update ( { "is_active" : is_active } ) org_defaults . update ( { "name" : name } ) organization = org_model . objects . create ( ** org_defaults ) org_user_defaults . update ( { "organization" : organization , "user" : user } ) new_user = org_user_model . objects . create ( ** org_user_defaults ) org_owner_model . objects . create ( organization = organization , organization_user = new_user ) return organization | Returns a new organization also creating an initial organization user who is the owner . |
17,711 | def model_field_attr ( model , model_field , attr ) : fields = dict ( [ ( field . name , field ) for field in model . _meta . fields ] ) return getattr ( fields [ model_field ] , attr ) | Returns the specified attribute for the specified field on the model class . |
17,712 | def get_form ( self , ** kwargs ) : if not hasattr ( self , "form_class" ) : raise AttributeError ( _ ( "You must define a form_class" ) ) return self . form_class ( ** kwargs ) | Returns the form for registering or inviting a user |
17,713 | def activate_organizations ( self , user ) : try : relation_name = self . org_model ( ) . user_relation_name except TypeError : relation_name = "organizations_organization" organization_set = getattr ( user , relation_name ) for org in organization_set . filter ( is_active = False ) : org . is_active = True org . save ( ) | Activates the related organizations for the user . |
17,714 | def activate_view ( self , request , user_id , token ) : try : user = self . user_model . objects . get ( id = user_id , is_active = False ) except self . user_model . DoesNotExist : raise Http404 ( _ ( "Your URL may have expired." ) ) if not RegistrationTokenGenerator ( ) . check_token ( user , token ) : raise Http404 ( _ ( "Your URL may have expired." ) ) form = self . get_form ( data = request . POST or None , files = request . FILES or None , instance = user ) if form . is_valid ( ) : form . instance . is_active = True user = form . save ( ) user . set_password ( form . cleaned_data [ "password" ] ) user . save ( ) self . activate_organizations ( user ) user = authenticate ( username = form . cleaned_data [ "username" ] , password = form . cleaned_data [ "password" ] , ) login ( request , user ) return redirect ( self . get_success_url ( ) ) return render ( request , self . registration_form_template , { "form" : form } ) | View function that activates the given User by setting is_active to true if the provided information is verified . |
17,715 | def send_reminder ( self , user , sender = None , ** kwargs ) : if user . is_active : return False token = RegistrationTokenGenerator ( ) . make_token ( user ) kwargs . update ( { "token" : token } ) self . email_message ( user , self . reminder_subject , self . reminder_body , sender , ** kwargs ) . send ( ) | Sends a reminder email to the specified user |
17,716 | def email_message ( self , user , subject_template , body_template , sender = None , message_class = EmailMessage , ** kwargs ) : if sender : try : display_name = sender . get_full_name ( ) except ( AttributeError , TypeError ) : display_name = sender . get_username ( ) from_email = "%s <%s>" % ( display_name , email . utils . parseaddr ( settings . DEFAULT_FROM_EMAIL ) [ 1 ] ) reply_to = "%s <%s>" % ( display_name , sender . email ) else : from_email = settings . DEFAULT_FROM_EMAIL reply_to = from_email headers = { "Reply-To" : reply_to } kwargs . update ( { "sender" : sender , "user" : user } ) subject_template = loader . get_template ( subject_template ) body_template = loader . get_template ( body_template ) subject = subject_template . render ( kwargs ) . strip ( ) body = body_template . render ( kwargs ) return message_class ( subject , body , from_email , [ user . email ] , headers = headers ) | Returns an email message for a new user . This can be easily overridden . For instance to send an HTML message use the EmailMultiAlternatives message_class and attach the additional conent . |
17,717 | def register_by_email ( self , email , sender = None , request = None , ** kwargs ) : try : user = self . user_model . objects . get ( email = email ) except self . user_model . DoesNotExist : user = self . user_model . objects . create ( username = self . get_username ( ) , email = email , password = self . user_model . objects . make_random_password ( ) , ) user . is_active = False user . save ( ) self . send_activation ( user , sender , ** kwargs ) return user | Returns a User object filled with dummy data and not active and sends an invitation email . |
17,718 | def send_activation ( self , user , sender = None , ** kwargs ) : if user . is_active : return False token = self . get_token ( user ) kwargs . update ( { "token" : token } ) self . email_message ( user , self . activation_subject , self . activation_body , sender , ** kwargs ) . send ( ) | Invites a user to join the site |
17,719 | def create_view ( self , request ) : try : if request . user . is_authenticated ( ) : return redirect ( "organization_add" ) except TypeError : if request . user . is_authenticated : return redirect ( "organization_add" ) form = org_registration_form ( self . org_model ) ( request . POST or None ) if form . is_valid ( ) : try : user = self . user_model . objects . get ( email = form . cleaned_data [ "email" ] ) except self . user_model . DoesNotExist : user = self . user_model . objects . create ( username = self . get_username ( ) , email = form . cleaned_data [ "email" ] , password = self . user_model . objects . make_random_password ( ) , ) user . is_active = False user . save ( ) else : return redirect ( "organization_add" ) organization = create_organization ( user , form . cleaned_data [ "name" ] , form . cleaned_data [ "slug" ] , is_active = False , ) return render ( request , self . activation_success_template , { "user" : user , "organization" : organization } , ) return render ( request , self . registration_form_template , { "form" : form } ) | Initiates the organization and user account creation process |
17,720 | def invite_by_email ( self , email , sender = None , request = None , ** kwargs ) : try : user = self . user_model . objects . get ( email = email ) except self . user_model . DoesNotExist : if "username" in inspect . getargspec ( self . user_model . objects . create_user ) . args : user = self . user_model . objects . create ( username = self . get_username ( ) , email = email , password = self . user_model . objects . make_random_password ( ) , ) else : user = self . user_model . objects . create ( email = email , password = self . user_model . objects . make_random_password ( ) ) user . is_active = False user . save ( ) self . send_invitation ( user , sender , ** kwargs ) return user | Creates an inactive user with the information we know and then sends an invitation email for that user to complete registration . |
17,721 | def send_invitation ( self , user , sender = None , ** kwargs ) : if user . is_active : return False token = self . get_token ( user ) kwargs . update ( { "token" : token } ) self . email_message ( user , self . invitation_subject , self . invitation_body , sender , ** kwargs ) . send ( ) return True | An intermediary function for sending an invitation email that selects the templates generating the token and ensuring that the user has not already joined the site . |
17,722 | def send_notification ( self , user , sender = None , ** kwargs ) : if not user . is_active : return False self . email_message ( user , self . notification_subject , self . notification_body , sender , ** kwargs ) . send ( ) return True | An intermediary function for sending an notification email informing a pre - existing active user that they have been added to a new organization . |
17,723 | def add_user ( self , user , is_admin = False ) : users_count = self . users . all ( ) . count ( ) if users_count == 0 : is_admin = True org_user = self . _org_user_model . objects . create ( user = user , organization = self , is_admin = is_admin ) if users_count == 0 : self . _org_owner_model . objects . create ( organization = self , organization_user = org_user ) user_added . send ( sender = self , user = user ) return org_user | Adds a new user and if the first user makes the user an admin and the owner . |
17,724 | def remove_user ( self , user ) : org_user = self . _org_user_model . objects . get ( user = user , organization = self ) org_user . delete ( ) user_removed . send ( sender = self , user = user ) | Deletes a user from an organization . |
17,725 | def get_or_add_user ( self , user , ** kwargs ) : is_admin = kwargs . pop ( "is_admin" , False ) users_count = self . users . all ( ) . count ( ) if users_count == 0 : is_admin = True org_user , created = self . _org_user_model . objects . get_or_create ( organization = self , user = user , defaults = { "is_admin" : is_admin } ) if users_count == 0 : self . _org_owner_model . objects . create ( organization = self , organization_user = org_user ) if created : user_added . send ( sender = self , user = user ) return org_user , created | Adds a new user to the organization and if it s the first user makes the user an admin and the owner . Uses the get_or_create method to create or return the existing user . |
17,726 | def change_owner ( self , new_owner ) : old_owner = self . owner . organization_user self . owner . organization_user = new_owner self . owner . save ( ) owner_changed . send ( sender = self , old = old_owner , new = new_owner ) | Changes ownership of an organization . |
17,727 | def is_admin ( self , user ) : return True if self . organization_users . filter ( user = user , is_admin = True ) else False | Returns True is user is an admin in the organization otherwise false |
17,728 | def delete ( self , using = None ) : from organizations . exceptions import OwnershipRequired try : if self . organization . owner . organization_user . pk == self . pk : raise OwnershipRequired ( _ ( "Cannot delete organization owner " "before organization or transferring ownership." ) ) except self . _org_owner_model . DoesNotExist : pass super ( AbstractBaseOrganizationUser , self ) . delete ( using = using ) | If the organization user is also the owner this should not be deleted unless it s part of a cascade from the Organization . |
17,729 | def save ( self , * args , ** kwargs ) : from organizations . exceptions import OrganizationMismatch if self . organization_user . organization . pk != self . organization . pk : raise OrganizationMismatch else : super ( AbstractBaseOrganizationOwner , self ) . save ( * args , ** kwargs ) | Extends the default save method by verifying that the chosen organization user is associated with the organization . |
17,730 | def _kml_default_colors ( x ) : x = max ( [ x , 0 ] ) colors_arr = [ simplekml . Color . red , simplekml . Color . green , simplekml . Color . blue , simplekml . Color . violet , simplekml . Color . yellow , simplekml . Color . orange , simplekml . Color . burlywood , simplekml . Color . azure , simplekml . Color . lightblue , simplekml . Color . lawngreen , simplekml . Color . indianred , simplekml . Color . hotpink ] return colors_arr [ x ] | flight mode to color conversion |
17,731 | def _kml_add_camera_triggers ( kml , ulog , camera_trigger_topic_name , altitude_offset ) : data = ulog . data_list topic_instance = 0 cur_dataset = [ elem for elem in data if elem . name == camera_trigger_topic_name and elem . multi_id == topic_instance ] if len ( cur_dataset ) > 0 : cur_dataset = cur_dataset [ 0 ] pos_lon = cur_dataset . data [ 'lon' ] pos_lat = cur_dataset . data [ 'lat' ] pos_alt = cur_dataset . data [ 'alt' ] sequence = cur_dataset . data [ 'seq' ] for i in range ( len ( pos_lon ) ) : pnt = kml . newpoint ( name = 'Camera Trigger ' + str ( sequence [ i ] ) ) pnt . coords = [ ( pos_lon [ i ] , pos_lat [ i ] , pos_alt [ i ] + altitude_offset ) ] | Add camera trigger points to the map |
17,732 | def get_dataset ( self , name , multi_instance = 0 ) : return [ elem for elem in self . _data_list if elem . name == name and elem . multi_id == multi_instance ] [ 0 ] | get a specific dataset . |
17,733 | def _add_message_info_multiple ( self , msg_info ) : if msg_info . key in self . _msg_info_multiple_dict : if msg_info . is_continued : self . _msg_info_multiple_dict [ msg_info . key ] [ - 1 ] . append ( msg_info . value ) else : self . _msg_info_multiple_dict [ msg_info . key ] . append ( [ msg_info . value ] ) else : self . _msg_info_multiple_dict [ msg_info . key ] = [ [ msg_info . value ] ] | add a message info multiple to self . _msg_info_multiple_dict |
17,734 | def _load_file ( self , log_file , message_name_filter_list ) : if isinstance ( log_file , str ) : self . _file_handle = open ( log_file , "rb" ) else : self . _file_handle = log_file self . _read_file_header ( ) self . _last_timestamp = self . _start_timestamp self . _read_file_definitions ( ) if self . has_data_appended and len ( self . _appended_offsets ) > 0 : if self . _debug : print ( 'This file has data appended' ) for offset in self . _appended_offsets : self . _read_file_data ( message_name_filter_list , read_until = offset ) self . _file_handle . seek ( offset ) self . _read_file_data ( message_name_filter_list ) self . _file_handle . close ( ) del self . _file_handle | load and parse an ULog file into memory |
17,735 | def _check_file_corruption ( self , header ) : if header . msg_type == 0 or header . msg_size == 0 or header . msg_size > 10000 : if not self . _file_corrupt and self . _debug : print ( 'File corruption detected' ) self . _file_corrupt = True return self . _file_corrupt | check for file corruption based on an unknown message type in the header |
17,736 | def show_info ( ulog , verbose ) : m1 , s1 = divmod ( int ( ulog . start_timestamp / 1e6 ) , 60 ) h1 , m1 = divmod ( m1 , 60 ) m2 , s2 = divmod ( int ( ( ulog . last_timestamp - ulog . start_timestamp ) / 1e6 ) , 60 ) h2 , m2 = divmod ( m2 , 60 ) print ( "Logging start time: {:d}:{:02d}:{:02d}, duration: {:d}:{:02d}:{:02d}" . format ( h1 , m1 , s1 , h2 , m2 , s2 ) ) dropout_durations = [ dropout . duration for dropout in ulog . dropouts ] if len ( dropout_durations ) == 0 : print ( "No Dropouts" ) else : print ( "Dropouts: count: {:}, total duration: {:.1f} s, max: {:} ms, mean: {:} ms" . format ( len ( dropout_durations ) , sum ( dropout_durations ) / 1000. , max ( dropout_durations ) , int ( sum ( dropout_durations ) / len ( dropout_durations ) ) ) ) version = ulog . get_version_info_str ( ) if not version is None : print ( 'SW Version: {}' . format ( version ) ) print ( "Info Messages:" ) for k in sorted ( ulog . msg_info_dict ) : if not k . startswith ( 'perf_' ) or verbose : print ( " {0}: {1}" . format ( k , ulog . msg_info_dict [ k ] ) ) if len ( ulog . msg_info_multiple_dict ) > 0 : if verbose : print ( "Info Multiple Messages:" ) for k in sorted ( ulog . msg_info_multiple_dict ) : print ( " {0}: {1}" . format ( k , ulog . msg_info_multiple_dict [ k ] ) ) else : print ( "Info Multiple Messages: {}" . format ( ", " . join ( [ "[{}: {}]" . format ( k , len ( ulog . msg_info_multiple_dict [ k ] ) ) for k in sorted ( ulog . msg_info_multiple_dict ) ] ) ) ) print ( "" ) print ( "{:<41} {:7}, {:10}" . format ( "Name (multi id, message size in bytes)" , "number of data points" , "total bytes" ) ) data_list_sorted = sorted ( ulog . data_list , key = lambda d : d . name + str ( d . multi_id ) ) for d in data_list_sorted : message_size = sum ( [ ULog . get_field_size ( f . type_str ) for f in d . field_data ] ) num_data_points = len ( d . data [ 'timestamp' ] ) name_id = "{:} ({:}, {:})" . format ( d . name , d . multi_id , message_size ) print ( " {:<40} {:7d} {:10d}" . format ( name_id , num_data_points , message_size * num_data_points ) ) | Show general information from an ULog |
17,737 | def get_estimator ( self ) : mav_type = self . _ulog . initial_parameters . get ( 'MAV_TYPE' , None ) if mav_type == 1 : return 'EKF2' mc_est_group = self . _ulog . initial_parameters . get ( 'SYS_MC_EST_GROUP' , None ) return { 0 : 'INAV' , 1 : 'LPE' , 2 : 'EKF2' , 3 : 'IEKF' } . get ( mc_est_group , 'unknown ({})' . format ( mc_est_group ) ) | return the configured estimator as string from initial parameters |
17,738 | def get_configured_rc_input_names ( self , channel ) : ret_val = [ ] for key in self . _ulog . initial_parameters : param_val = self . _ulog . initial_parameters [ key ] if key . startswith ( 'RC_MAP_' ) and param_val == channel + 1 : ret_val . append ( key [ 7 : ] . capitalize ( ) ) if len ( ret_val ) > 0 : return ret_val return None | find all RC mappings to a given channel and return their names |
17,739 | def find_fragments ( base_directory , sections , fragment_directory , definitions ) : content = OrderedDict ( ) fragment_filenames = [ ] for key , val in sections . items ( ) : if fragment_directory is not None : section_dir = os . path . join ( base_directory , val , fragment_directory ) else : section_dir = os . path . join ( base_directory , val ) files = os . listdir ( section_dir ) file_content = { } for basename in files : parts = basename . split ( u"." ) counter = 0 if len ( parts ) == 1 : continue else : ticket , category = parts [ : 2 ] if len ( parts ) > 2 : try : counter = int ( parts [ 2 ] ) except ValueError : pass if category not in definitions : continue full_filename = os . path . join ( section_dir , basename ) fragment_filenames . append ( full_filename ) with open ( full_filename , "rb" ) as f : data = f . read ( ) . decode ( "utf8" , "replace" ) if ( ticket , category , counter ) in file_content : raise ValueError ( "multiple files for {}.{} in {}" . format ( ticket , category , section_dir ) ) file_content [ ticket , category , counter ] = data content [ key ] = file_content return content , fragment_filenames | Sections are a dictonary of section names to paths . |
17,740 | def indent ( text , prefix ) : def prefixed_lines ( ) : for line in text . splitlines ( True ) : yield ( prefix + line if line . strip ( ) else line ) return u"" . join ( prefixed_lines ( ) ) | Adds prefix to the beginning of non - empty lines in text . |
17,741 | def render_fragments ( template , issue_format , fragments , definitions , underlines , wrap ) : jinja_template = Template ( template , trim_blocks = True ) data = OrderedDict ( ) for section_name , section_value in fragments . items ( ) : data [ section_name ] = OrderedDict ( ) for category_name , category_value in section_value . items ( ) : entries = [ ] for text , issues in category_value . items ( ) : entries . append ( ( text , sorted ( issues , key = issue_key ) ) ) entries . sort ( key = entry_key ) categories = OrderedDict ( ) for text , issues in entries : rendered = [ render_issue ( issue_format , i ) for i in issues ] categories [ text ] = rendered data [ section_name ] [ category_name ] = categories done = [ ] res = jinja_template . render ( sections = data , definitions = definitions , underlines = underlines ) for line in res . split ( u"\n" ) : if wrap : done . append ( textwrap . fill ( line , width = 79 , subsequent_indent = u" " , break_long_words = False , break_on_hyphens = False , ) ) else : done . append ( line ) return u"\n" . join ( done ) . rstrip ( ) + u"\n" | Render the fragments into a news file . |
17,742 | def _ppoints ( n , a = 0.5 ) : a = 3 / 8 if n <= 10 else 0.5 return ( np . arange ( n ) + 1 - a ) / ( n + 1 - 2 * a ) | Ordinates For Probability Plotting . |
17,743 | def qqplot ( x , dist = 'norm' , sparams = ( ) , confidence = .95 , figsize = ( 5 , 4 ) , ax = None ) : if isinstance ( dist , str ) : dist = getattr ( stats , dist ) x = np . asarray ( x ) x = x [ ~ np . isnan ( x ) ] quantiles = stats . probplot ( x , sparams = sparams , dist = dist , fit = False ) theor , observed = quantiles [ 0 ] , quantiles [ 1 ] fit_params = dist . fit ( x ) loc = fit_params [ - 2 ] scale = fit_params [ - 1 ] shape = fit_params [ 0 ] if len ( fit_params ) == 3 else None if loc != 0 and scale != 1 : observed = ( np . sort ( observed ) - fit_params [ - 2 ] ) / fit_params [ - 1 ] slope , intercept , r , _ , _ = stats . linregress ( theor , observed ) if ax is None : fig , ax = plt . subplots ( 1 , 1 , figsize = figsize ) ax . plot ( theor , observed , 'bo' ) stats . morestats . _add_axis_labels_title ( ax , xlabel = 'Theoretical quantiles' , ylabel = 'Ordered quantiles' , title = 'Q-Q Plot' ) end_pts = [ ax . get_xlim ( ) , ax . get_ylim ( ) ] end_pts [ 0 ] = min ( end_pts [ 0 ] ) end_pts [ 1 ] = max ( end_pts [ 1 ] ) ax . plot ( end_pts , end_pts , color = 'slategrey' , lw = 1.5 ) ax . set_xlim ( end_pts ) ax . set_ylim ( end_pts ) fit_val = slope * theor + intercept ax . plot ( theor , fit_val , 'r-' , lw = 2 ) posx = end_pts [ 0 ] + 0.60 * ( end_pts [ 1 ] - end_pts [ 0 ] ) posy = end_pts [ 0 ] + 0.10 * ( end_pts [ 1 ] - end_pts [ 0 ] ) ax . text ( posx , posy , "$R^2=%.3f$" % r ** 2 ) if confidence is not False : n = x . size P = _ppoints ( n ) crit = stats . norm . ppf ( 1 - ( 1 - confidence ) / 2 ) pdf = dist . pdf ( theor ) if shape is None else dist . pdf ( theor , shape ) se = ( slope / pdf ) * np . sqrt ( P * ( 1 - P ) / n ) upper = fit_val + crit * se lower = fit_val - crit * se ax . plot ( theor , upper , 'r--' , lw = 1.25 ) ax . plot ( theor , lower , 'r--' , lw = 1.25 ) return ax | Quantile - Quantile plot . |
17,744 | def plot_paired ( data = None , dv = None , within = None , subject = None , order = None , boxplot = True , figsize = ( 4 , 4 ) , dpi = 100 , ax = None , colors = [ 'green' , 'grey' , 'indianred' ] , pointplot_kwargs = { 'scale' : .6 , 'markers' : '.' } , boxplot_kwargs = { 'color' : 'lightslategrey' , 'width' : .2 } ) : from pingouin . utils import _check_dataframe , remove_rm_na _check_dataframe ( data = data , dv = dv , within = within , subject = subject , effects = 'within' ) data = remove_rm_na ( dv = dv , within = within , subject = subject , data = data ) subj = data [ subject ] . unique ( ) x_cat = np . unique ( data [ within ] ) assert len ( x_cat ) == 2 , 'Within must have exactly two unique levels.' if order is None : order = x_cat else : assert len ( order ) == 2 , 'Order must have exactly two elements.' if ax is None : fig , ax = plt . subplots ( 1 , 1 , figsize = figsize , dpi = dpi ) for idx , s in enumerate ( subj ) : tmp = data . loc [ data [ subject ] == s , [ dv , within , subject ] ] x_val = tmp [ tmp [ within ] == order [ 0 ] ] [ dv ] . values [ 0 ] y_val = tmp [ tmp [ within ] == order [ 1 ] ] [ dv ] . values [ 0 ] if x_val < y_val : color = colors [ 0 ] elif x_val > y_val : color = colors [ 2 ] elif x_val == y_val : color = colors [ 1 ] sns . pointplot ( data = tmp , x = within , y = dv , order = order , color = color , ax = ax , ** pointplot_kwargs ) if boxplot : sns . boxplot ( data = data , x = within , y = dv , order = order , ax = ax , ** boxplot_kwargs ) sns . despine ( trim = True , ax = ax ) return ax | Paired plot . |
17,745 | def anova ( dv = None , between = None , data = None , detailed = False , export_filename = None ) : if isinstance ( between , list ) : if len ( between ) == 2 : return anova2 ( dv = dv , between = between , data = data , export_filename = export_filename ) elif len ( between ) == 1 : between = between [ 0 ] _check_dataframe ( dv = dv , between = between , data = data , effects = 'between' ) data = data [ [ dv , between ] ] . dropna ( ) data = data . reset_index ( drop = True ) groups = list ( data [ between ] . unique ( ) ) n_groups = len ( groups ) N = data [ dv ] . size grp = data . groupby ( between ) [ dv ] ssbetween = ( ( grp . mean ( ) - data [ dv ] . mean ( ) ) ** 2 * grp . count ( ) ) . sum ( ) sserror = grp . apply ( lambda x : ( x - x . mean ( ) ) ** 2 ) . sum ( ) ddof1 = n_groups - 1 ddof2 = N - n_groups msbetween = ssbetween / ddof1 mserror = sserror / ddof2 fval = msbetween / mserror p_unc = f ( ddof1 , ddof2 ) . sf ( fval ) np2 = ssbetween / ( ssbetween + sserror ) if not detailed : aov = pd . DataFrame ( { 'Source' : between , 'ddof1' : ddof1 , 'ddof2' : ddof2 , 'F' : fval , 'p-unc' : p_unc , 'np2' : np2 } , index = [ 0 ] ) col_order = [ 'Source' , 'ddof1' , 'ddof2' , 'F' , 'p-unc' , 'np2' ] else : aov = pd . DataFrame ( { 'Source' : [ between , 'Within' ] , 'SS' : np . round ( [ ssbetween , sserror ] , 3 ) , 'DF' : [ ddof1 , ddof2 ] , 'MS' : np . round ( [ msbetween , mserror ] , 3 ) , 'F' : [ fval , np . nan ] , 'p-unc' : [ p_unc , np . nan ] , 'np2' : [ np2 , np . nan ] } ) col_order = [ 'Source' , 'SS' , 'DF' , 'MS' , 'F' , 'p-unc' , 'np2' ] aov [ [ 'F' , 'np2' ] ] = aov [ [ 'F' , 'np2' ] ] . round ( 3 ) aov = aov . fillna ( '-' ) aov = aov . reindex ( columns = col_order ) aov . dropna ( how = 'all' , axis = 1 , inplace = True ) if export_filename is not None : _export_table ( aov , export_filename ) return aov | One - way and two - way ANOVA . |
17,746 | def welch_anova ( dv = None , between = None , data = None , export_filename = None ) : _check_dataframe ( dv = dv , between = between , data = data , effects = 'between' ) data = data . reset_index ( drop = True ) r = data [ between ] . nunique ( ) ddof1 = r - 1 grp = data . groupby ( between ) [ dv ] weights = grp . count ( ) / grp . var ( ) adj_grandmean = ( weights * grp . mean ( ) ) . sum ( ) / weights . sum ( ) ss_tr = np . sum ( weights * np . square ( grp . mean ( ) - adj_grandmean ) ) ms_tr = ss_tr / ddof1 lamb = ( 3 * np . sum ( ( 1 / ( grp . count ( ) - 1 ) ) * ( 1 - ( weights / weights . sum ( ) ) ) ** 2 ) ) / ( r ** 2 - 1 ) fval = ms_tr / ( 1 + ( 2 * lamb * ( r - 2 ) ) / 3 ) pval = f . sf ( fval , ddof1 , 1 / lamb ) aov = pd . DataFrame ( { 'Source' : between , 'ddof1' : ddof1 , 'ddof2' : 1 / lamb , 'F' : fval , 'p-unc' : pval , } , index = [ 0 ] ) col_order = [ 'Source' , 'ddof1' , 'ddof2' , 'F' , 'p-unc' ] aov = aov . reindex ( columns = col_order ) aov [ [ 'F' , 'ddof2' ] ] = aov [ [ 'F' , 'ddof2' ] ] . round ( 3 ) if export_filename is not None : _export_table ( aov , export_filename ) return aov | One - way Welch ANOVA . |
17,747 | def ancovan ( dv = None , covar = None , between = None , data = None , export_filename = None ) : from pingouin . utils import _is_statsmodels_installed _is_statsmodels_installed ( raise_error = True ) from statsmodels . api import stats from statsmodels . formula . api import ols assert all ( [ data [ covar [ i ] ] . dtype . kind in 'fi' for i in range ( len ( covar ) ) ] ) formula = dv + ' ~ C(' + between + ')' for c in covar : formula += ' + ' + c model = ols ( formula , data = data ) . fit ( ) aov = stats . anova_lm ( model , typ = 2 ) . reset_index ( ) aov . rename ( columns = { 'index' : 'Source' , 'sum_sq' : 'SS' , 'df' : 'DF' , 'PR(>F)' : 'p-unc' } , inplace = True ) aov . loc [ 0 , 'Source' ] = between aov [ 'DF' ] = aov [ 'DF' ] . astype ( int ) aov [ [ 'SS' , 'F' ] ] = aov [ [ 'SS' , 'F' ] ] . round ( 3 ) if export_filename is not None : _export_table ( aov , export_filename ) return aov | ANCOVA with n covariates . |
17,748 | def read_dataset ( dname ) : d , ext = op . splitext ( dname ) if ext . lower ( ) == '.csv' : dname = d if dname not in dts [ 'dataset' ] . values : raise ValueError ( 'Dataset does not exist. Valid datasets names are' , dts [ 'dataset' ] . values ) return pd . read_csv ( op . join ( ddir , dname + '.csv' ) , sep = ',' ) | Read example datasets . |
17,749 | def _perm_pval ( bootstat , estimate , tail = 'two-sided' ) : assert tail in [ 'two-sided' , 'upper' , 'lower' ] , 'Wrong tail argument.' assert isinstance ( estimate , ( int , float ) ) bootstat = np . asarray ( bootstat ) assert bootstat . ndim == 1 , 'bootstat must be a 1D array.' n_boot = bootstat . size assert n_boot >= 1 , 'bootstat must have at least one value.' if tail == 'upper' : p = np . greater_equal ( bootstat , estimate ) . sum ( ) / n_boot elif tail == 'lower' : p = np . less_equal ( bootstat , estimate ) . sum ( ) / n_boot else : p = np . greater_equal ( np . fabs ( bootstat ) , abs ( estimate ) ) . sum ( ) / n_boot return p | Compute p - values from a permutation test . |
17,750 | def print_table ( df , floatfmt = ".3f" , tablefmt = 'simple' ) : if 'F' in df . keys ( ) : print ( '\n=============\nANOVA SUMMARY\n=============\n' ) if 'A' in df . keys ( ) : print ( '\n==============\nPOST HOC TESTS\n==============\n' ) print ( tabulate ( df , headers = "keys" , showindex = False , floatfmt = floatfmt , tablefmt = tablefmt ) ) print ( '' ) | Pretty display of table . |
17,751 | def _export_table ( table , fname ) : import os . path as op extension = op . splitext ( fname . lower ( ) ) [ 1 ] if extension == '' : fname = fname + '.csv' table . to_csv ( fname , index = None , sep = ',' , encoding = 'utf-8' , float_format = '%.4f' , decimal = '.' ) | Export DataFrame to . csv |
17,752 | def _remove_na_single ( x , axis = 'rows' ) : if x . ndim == 1 : x_mask = ~ np . isnan ( x ) else : ax = 1 if axis == 'rows' else 0 x_mask = ~ np . any ( np . isnan ( x ) , axis = ax ) if ~ x_mask . all ( ) : ax = 0 if axis == 'rows' else 1 ax = 0 if x . ndim == 1 else ax x = x . compress ( x_mask , axis = ax ) return x | Remove NaN in a single array . This is an internal Pingouin function . |
17,753 | def remove_rm_na ( dv = None , within = None , subject = None , data = None , aggregate = 'mean' ) : assert isinstance ( aggregate , str ) , 'aggregate must be a str.' assert isinstance ( within , ( str , list ) ) , 'within must be str or list.' assert isinstance ( subject , str ) , 'subject must be a string.' assert isinstance ( data , pd . DataFrame ) , 'Data must be a DataFrame.' idx_cols = _flatten_list ( [ subject , within ] ) all_cols = data . columns if data [ idx_cols ] . isnull ( ) . any ( ) . any ( ) : raise ValueError ( "NaN are present in the within-factors or in the " "subject column. Please remove them manually." ) if ( data . groupby ( idx_cols ) . count ( ) > 1 ) . any ( ) . any ( ) : data = data . groupby ( idx_cols ) . agg ( aggregate ) else : data = data . set_index ( idx_cols ) . sort_index ( ) if dv is None : iloc_nan = data . isnull ( ) . values . nonzero ( ) [ 0 ] else : iloc_nan = data [ dv ] . isnull ( ) . values . nonzero ( ) [ 0 ] idx_nan = data . index [ iloc_nan ] . droplevel ( - 1 ) data = data . drop ( idx_nan ) . reset_index ( drop = False ) return data . reindex ( columns = all_cols ) . dropna ( how = 'all' , axis = 1 ) | Remove missing values in long - format repeated - measures dataframe . |
17,754 | def _flatten_list ( x ) : result = [ ] x = list ( filter ( None . __ne__ , x ) ) for el in x : x_is_iter = isinstance ( x , collections . Iterable ) if x_is_iter and not isinstance ( el , ( str , tuple ) ) : result . extend ( _flatten_list ( el ) ) else : result . append ( el ) return result | Flatten an arbitrarily nested list into a new list . |
17,755 | def _format_bf ( bf , precision = 3 , trim = '0' ) : if bf >= 1e4 or bf <= 1e-4 : out = np . format_float_scientific ( bf , precision = precision , trim = trim ) else : out = np . format_float_positional ( bf , precision = precision , trim = trim ) return out | Format BF10 to floating point or scientific notation . |
17,756 | def bayesfactor_pearson ( r , n ) : from scipy . special import gamma def fun ( g , r , n ) : return np . exp ( ( ( n - 2 ) / 2 ) * np . log ( 1 + g ) + ( - ( n - 1 ) / 2 ) * np . log ( 1 + ( 1 - r ** 2 ) * g ) + ( - 3 / 2 ) * np . log ( g ) + - n / ( 2 * g ) ) integr = quad ( fun , 0 , np . inf , args = ( r , n ) ) [ 0 ] bf10 = np . sqrt ( ( n / 2 ) ) / gamma ( 1 / 2 ) * integr return _format_bf ( bf10 ) | Bayes Factor of a Pearson correlation . |
17,757 | def normality ( * args , alpha = .05 ) : from scipy . stats import shapiro k = len ( args ) p = np . zeros ( k ) normal = np . zeros ( k , 'bool' ) for j in range ( k ) : _ , p [ j ] = shapiro ( args [ j ] ) normal [ j ] = True if p [ j ] > alpha else False if k == 1 : normal = bool ( normal ) p = float ( p ) return normal , np . round ( p , 3 ) | Shapiro - Wilk univariate normality test . |
17,758 | def homoscedasticity ( * args , alpha = .05 ) : from scipy . stats import levene , bartlett k = len ( args ) if k < 2 : raise ValueError ( "Must enter at least two input sample vectors." ) normal , _ = normality ( * args ) if np . count_nonzero ( normal ) != normal . size : _ , p = levene ( * args ) else : _ , p = bartlett ( * args ) equal_var = True if p > alpha else False return equal_var , np . round ( p , 3 ) | Test equality of variance . |
17,759 | def anderson ( * args , dist = 'norm' ) : from scipy . stats import anderson as ads k = len ( args ) from_dist = np . zeros ( k , 'bool' ) sig_level = np . zeros ( k ) for j in range ( k ) : st , cr , sig = ads ( args [ j ] , dist = dist ) from_dist [ j ] = True if ( st > cr ) . any ( ) else False sig_level [ j ] = sig [ np . argmin ( np . abs ( st - cr ) ) ] if k == 1 : from_dist = bool ( from_dist ) sig_level = float ( sig_level ) return from_dist , sig_level | Anderson - Darling test of distribution . |
17,760 | def epsilon ( data , correction = 'gg' ) : S = data . cov ( ) n = data . shape [ 0 ] k = data . shape [ 1 ] if correction == 'lb' : if S . columns . nlevels == 1 : return 1 / ( k - 1 ) elif S . columns . nlevels == 2 : ka = S . columns . levels [ 0 ] . size kb = S . columns . levels [ 1 ] . size return 1 / ( ( ka - 1 ) * ( kb - 1 ) ) mean_var = np . diag ( S ) . mean ( ) S_mean = S . mean ( ) . mean ( ) ss_mat = ( S ** 2 ) . sum ( ) . sum ( ) ss_rows = ( S . mean ( 1 ) ** 2 ) . sum ( ) . sum ( ) num = ( k * ( mean_var - S_mean ) ) ** 2 den = ( k - 1 ) * ( ss_mat - 2 * k * ss_rows + k ** 2 * S_mean ** 2 ) eps = np . min ( [ num / den , 1 ] ) if correction == 'hf' : num = n * ( k - 1 ) * eps - 2 den = ( k - 1 ) * ( n - 1 - ( k - 1 ) * eps ) eps = np . min ( [ num / den , 1 ] ) return eps | Epsilon adjustement factor for repeated measures . |
17,761 | def sphericity ( data , method = 'mauchly' , alpha = .05 ) : from scipy . stats import chi2 S = data . cov ( ) . values n = data . shape [ 0 ] p = data . shape [ 1 ] d = p - 1 S_pop = S - S . mean ( 0 ) [ : , np . newaxis ] - S . mean ( 1 ) [ np . newaxis , : ] + S . mean ( ) eig = np . linalg . eigvalsh ( S_pop ) [ 1 : ] if method == 'jns' : W = eig . sum ( ) ** 2 / np . square ( eig ) . sum ( ) chi_sq = 0.5 * n * d ** 2 * ( W - 1 / d ) if method == 'mauchly' : W = np . product ( eig ) / ( eig . sum ( ) / d ) ** d f = ( 2 * d ** 2 + p + 1 ) / ( 6 * d * ( n - 1 ) ) chi_sq = ( f - 1 ) * ( n - 1 ) * np . log ( W ) ddof = 0.5 * d * p - 1 ddof = 1 if ddof == 0 else ddof pval = chi2 . sf ( chi_sq , ddof ) sphericity = True if pval > alpha else False return sphericity , np . round ( W , 3 ) , np . round ( chi_sq , 3 ) , int ( ddof ) , pval | Mauchly and JNS test for sphericity . |
17,762 | def compute_esci ( stat = None , nx = None , ny = None , paired = False , eftype = 'cohen' , confidence = .95 , decimals = 2 ) : from scipy . stats import norm assert eftype . lower ( ) in [ 'r' , 'pearson' , 'spearman' , 'cohen' , 'd' , 'g' , 'hedges' ] assert stat is not None and nx is not None assert isinstance ( confidence , float ) assert 0 < confidence < 1 crit = np . abs ( norm . ppf ( ( 1 - confidence ) / 2 ) ) if eftype . lower ( ) in [ 'r' , 'pearson' , 'spearman' ] : z = np . arctanh ( stat ) se = 1 / np . sqrt ( nx - 3 ) ci_z = np . array ( [ z - crit * se , z + crit * se ] ) ci = np . tanh ( ci_z ) else : if ny == 1 or paired : se = np . sqrt ( 1 / nx + stat ** 2 / ( 2 * nx ) ) else : se = np . sqrt ( ( ( nx + ny ) / ( nx * ny ) ) + ( stat ** 2 ) / ( 2 * ( nx + ny ) ) ) ci = np . array ( [ stat - crit * se , stat + crit * se ] ) return np . round ( ci , decimals ) | Parametric confidence intervals around a Cohen d or a correlation coefficient . |
17,763 | def convert_effsize ( ef , input_type , output_type , nx = None , ny = None ) : it = input_type . lower ( ) ot = output_type . lower ( ) for input in [ it , ot ] : if not _check_eftype ( input ) : err = "Could not interpret input '{}'" . format ( input ) raise ValueError ( err ) if it not in [ 'r' , 'cohen' ] : raise ValueError ( "Input type must be 'r' or 'cohen'" ) if it == ot : return ef d = ( 2 * ef ) / np . sqrt ( 1 - ef ** 2 ) if it == 'r' else ef if ot == 'cohen' : return d elif ot == 'hedges' : if all ( v is not None for v in [ nx , ny ] ) : return d * ( 1 - ( 3 / ( 4 * ( nx + ny ) - 9 ) ) ) else : warnings . warn ( "You need to pass nx and ny arguments to compute " "Hedges g. Returning Cohen's d instead" ) return d elif ot == 'glass' : warnings . warn ( "Returning original effect size instead of Glass " "because variance is not known." ) return ef elif ot == 'r' : if all ( v is not None for v in [ nx , ny ] ) : a = ( ( nx + ny ) ** 2 - 2 * ( nx + ny ) ) / ( nx * ny ) else : a = 4 return d / np . sqrt ( d ** 2 + a ) elif ot == 'eta-square' : return ( d / 2 ) ** 2 / ( 1 + ( d / 2 ) ** 2 ) elif ot == 'odds-ratio' : return np . exp ( d * np . pi / np . sqrt ( 3 ) ) elif ot in [ 'auc' , 'cles' ] : from scipy . stats import norm return norm . cdf ( d / np . sqrt ( 2 ) ) else : return None | Conversion between effect sizes . |
17,764 | def compute_effsize ( x , y , paired = False , eftype = 'cohen' ) : if not _check_eftype ( eftype ) : err = "Could not interpret input '{}'" . format ( eftype ) raise ValueError ( err ) x = np . asarray ( x ) y = np . asarray ( y ) if x . size != y . size and paired : warnings . warn ( "x and y have unequal sizes. Switching to " "paired == False." ) paired = False x , y = remove_na ( x , y , paired = paired ) nx , ny = x . size , y . size if ny == 1 : d = ( x . mean ( ) - y ) / x . std ( ddof = 1 ) return d if eftype . lower ( ) == 'glass' : sd_control = np . min ( [ x . std ( ddof = 1 ) , y . std ( ddof = 1 ) ] ) d = ( x . mean ( ) - y . mean ( ) ) / sd_control return d elif eftype . lower ( ) == 'r' : from scipy . stats import pearsonr r , _ = pearsonr ( x , y ) return r elif eftype . lower ( ) == 'cles' : diff = x [ : , None ] - y return max ( ( diff < 0 ) . sum ( ) , ( diff > 0 ) . sum ( ) ) / diff . size else : if not paired : dof = nx + ny - 2 poolsd = np . sqrt ( ( ( nx - 1 ) * x . var ( ddof = 1 ) + ( ny - 1 ) * y . var ( ddof = 1 ) ) / dof ) d = ( x . mean ( ) - y . mean ( ) ) / poolsd else : d = ( x . mean ( ) - y . mean ( ) ) / ( .5 * ( x . std ( ddof = 1 ) + y . std ( ddof = 1 ) ) ) return convert_effsize ( d , 'cohen' , eftype , nx = nx , ny = ny ) | Calculate effect size between two set of observations . |
17,765 | def compute_effsize_from_t ( tval , nx = None , ny = None , N = None , eftype = 'cohen' ) : if not _check_eftype ( eftype ) : err = "Could not interpret input '{}'" . format ( eftype ) raise ValueError ( err ) if not isinstance ( tval , float ) : err = "T-value must be float" raise ValueError ( err ) if nx is not None and ny is not None : d = tval * np . sqrt ( 1 / nx + 1 / ny ) elif N is not None : d = 2 * tval / np . sqrt ( N ) else : raise ValueError ( 'You must specify either nx + ny, or just N' ) return convert_effsize ( d , 'cohen' , eftype , nx = nx , ny = ny ) | Compute effect size from a T - value . |
17,766 | def bsmahal ( a , b , n_boot = 200 ) : n , m = b . shape MD = np . zeros ( ( n , n_boot ) ) nr = np . arange ( n ) xB = np . random . choice ( nr , size = ( n_boot , n ) , replace = True ) for i in np . arange ( n_boot ) : s1 = b [ xB [ i , : ] , 0 ] s2 = b [ xB [ i , : ] , 1 ] X = np . column_stack ( ( s1 , s2 ) ) mu = X . mean ( 0 ) _ , R = np . linalg . qr ( X - mu ) sol = np . linalg . solve ( R . T , ( a - mu ) . T ) MD [ : , i ] = np . sum ( sol ** 2 , 0 ) * ( n - 1 ) return MD . mean ( 1 ) | Bootstraps Mahalanobis distances for Shepherd s pi correlation . |
17,767 | def shepherd ( x , y , n_boot = 200 ) : from scipy . stats import spearmanr X = np . column_stack ( ( x , y ) ) m = bsmahal ( X , X , n_boot ) outliers = ( m >= 6 ) r , pval = spearmanr ( x [ ~ outliers ] , y [ ~ outliers ] ) return r , pval , outliers | Shepherd s Pi correlation equivalent to Spearman s rho after outliers removal . |
17,768 | def rm_corr ( data = None , x = None , y = None , subject = None , tail = 'two-sided' ) : from pingouin import ancova , power_corr assert isinstance ( data , pd . DataFrame ) , 'Data must be a DataFrame' assert x in data , 'The %s column is not in data.' % x assert y in data , 'The %s column is not in data.' % y assert subject in data , 'The %s column is not in data.' % subject if data [ subject ] . nunique ( ) < 3 : raise ValueError ( 'rm_corr requires at least 3 unique subjects.' ) data = data [ [ x , y , subject ] ] . dropna ( axis = 0 ) aov , bw = ancova ( dv = y , covar = x , between = subject , data = data , return_bw = True ) sign = np . sign ( bw ) dof = int ( aov . loc [ 2 , 'DF' ] ) n = dof + 2 ssfactor = aov . loc [ 1 , 'SS' ] sserror = aov . loc [ 2 , 'SS' ] rm = sign * np . sqrt ( ssfactor / ( ssfactor + sserror ) ) pval = aov . loc [ 1 , 'p-unc' ] pval *= 0.5 if tail == 'one-sided' else 1 ci = compute_esci ( stat = rm , nx = n , eftype = 'pearson' ) . tolist ( ) pwr = power_corr ( r = rm , n = n , tail = tail ) stats = pd . DataFrame ( { "r" : round ( rm , 3 ) , "dof" : int ( dof ) , "pval" : pval , "CI95%" : str ( ci ) , "power" : round ( pwr , 3 ) } , index = [ "rm_corr" ] ) return stats | Repeated measures correlation . |
17,769 | def _dcorr ( y , n2 , A , dcov2_xx ) : b = squareform ( pdist ( y , metric = 'euclidean' ) ) B = b - b . mean ( axis = 0 ) [ None , : ] - b . mean ( axis = 1 ) [ : , None ] + b . mean ( ) dcov2_yy = np . vdot ( B , B ) / n2 dcov2_xy = np . vdot ( A , B ) / n2 return np . sqrt ( dcov2_xy ) / np . sqrt ( np . sqrt ( dcov2_xx ) * np . sqrt ( dcov2_yy ) ) | Helper function for distance correlation bootstrapping . |
17,770 | def distance_corr ( x , y , tail = 'upper' , n_boot = 1000 , seed = None ) : assert tail in [ 'upper' , 'lower' , 'two-sided' ] , 'Wrong tail argument.' x = np . asarray ( x ) y = np . asarray ( y ) if any ( [ np . isnan ( np . min ( x ) ) , np . isnan ( np . min ( y ) ) ] ) : raise ValueError ( 'Input arrays must not contain NaN values.' ) if x . ndim == 1 : x = x [ : , None ] if y . ndim == 1 : y = y [ : , None ] assert x . shape [ 0 ] == y . shape [ 0 ] , 'x and y must have same number of samples' n = x . shape [ 0 ] n2 = n ** 2 a = squareform ( pdist ( x , metric = 'euclidean' ) ) A = a - a . mean ( axis = 0 ) [ None , : ] - a . mean ( axis = 1 ) [ : , None ] + a . mean ( ) dcov2_xx = np . vdot ( A , A ) / n2 dcor = _dcorr ( y , n2 , A , dcov2_xx ) if n_boot is not None and n_boot > 1 : rng = np . random . RandomState ( seed ) bootsam = rng . random_sample ( ( n_boot , n ) ) . argsort ( axis = 1 ) bootstat = np . empty ( n_boot ) for i in range ( n_boot ) : bootstat [ i ] = _dcorr ( y [ bootsam [ i , : ] ] , n2 , A , dcov2_xx ) pval = _perm_pval ( bootstat , dcor , tail = tail ) return dcor , pval else : return dcor | Distance correlation between two arrays . |
17,771 | def _point_estimate ( X_val , XM_val , M_val , y_val , idx , n_mediator , mtype = 'linear' ) : beta_m = [ ] for j in range ( n_mediator ) : if mtype == 'linear' : beta_m . append ( linear_regression ( X_val [ idx ] , M_val [ idx , j ] , coef_only = True ) [ 1 ] ) else : beta_m . append ( logistic_regression ( X_val [ idx ] , M_val [ idx , j ] , coef_only = True ) [ 1 ] ) beta_y = linear_regression ( XM_val [ idx ] , y_val [ idx ] , coef_only = True ) [ 2 : ( 2 + n_mediator ) ] return beta_m * beta_y | Point estimate of indirect effect based on bootstrap sample . |
17,772 | def _pval_from_bootci ( boot , estimate ) : if estimate == 0 : out = 1 else : out = 2 * min ( sum ( boot > 0 ) , sum ( boot < 0 ) ) / len ( boot ) return min ( out , 1 ) | Compute p - value from bootstrap distribution . Similar to the pval function in the R package mediation . Note that this is less accurate than a permutation test because the bootstrap distribution is not conditioned on a true null hypothesis . |
17,773 | def _anova ( self , dv = None , between = None , detailed = False , export_filename = None ) : aov = anova ( data = self , dv = dv , between = between , detailed = detailed , export_filename = export_filename ) return aov | Return one - way and two - way ANOVA . |
17,774 | def _welch_anova ( self , dv = None , between = None , export_filename = None ) : aov = welch_anova ( data = self , dv = dv , between = between , export_filename = export_filename ) return aov | Return one - way Welch ANOVA . |
17,775 | def _mixed_anova ( self , dv = None , between = None , within = None , subject = None , correction = False , export_filename = None ) : aov = mixed_anova ( data = self , dv = dv , between = between , within = within , subject = subject , correction = correction , export_filename = export_filename ) return aov | Two - way mixed ANOVA . |
17,776 | def _mediation_analysis ( self , x = None , m = None , y = None , covar = None , alpha = 0.05 , n_boot = 500 , seed = None , return_dist = False ) : stats = mediation_analysis ( data = self , x = x , m = m , y = y , covar = covar , alpha = alpha , n_boot = n_boot , seed = seed , return_dist = return_dist ) return stats | Mediation analysis . |
17,777 | def mad ( a , normalize = True , axis = 0 ) : from scipy . stats import norm a = np . asarray ( a ) c = norm . ppf ( 3 / 4. ) if normalize else 1 center = np . apply_over_axes ( np . median , a , axis ) return np . median ( ( np . fabs ( a - center ) ) / c , axis = axis ) | Median Absolute Deviation along given axis of an array . |
17,778 | def madmedianrule ( a ) : from scipy . stats import chi2 a = np . asarray ( a ) k = np . sqrt ( chi2 . ppf ( 0.975 , 1 ) ) return ( np . fabs ( a - np . median ( a ) ) / mad ( a ) ) > k | Outlier detection based on the MAD - median rule . |
17,779 | def wilcoxon ( x , y , tail = 'two-sided' ) : from scipy . stats import wilcoxon x = np . asarray ( x ) y = np . asarray ( y ) x , y = remove_na ( x , y , paired = True ) wval , pval = wilcoxon ( x , y , zero_method = 'wilcox' , correction = False ) pval *= .5 if tail == 'one-sided' else pval diff = x [ : , None ] - y cles = max ( ( diff < 0 ) . sum ( ) , ( diff > 0 ) . sum ( ) ) / diff . size rank = np . arange ( x . size , 0 , - 1 ) rsum = rank . sum ( ) fav = rank [ np . sign ( y - x ) > 0 ] . sum ( ) unfav = rank [ np . sign ( y - x ) < 0 ] . sum ( ) rbc = fav / rsum - unfav / rsum stats = pd . DataFrame ( { } , index = [ 'Wilcoxon' ] ) stats [ 'W-val' ] = round ( wval , 3 ) stats [ 'p-val' ] = pval stats [ 'RBC' ] = round ( rbc , 3 ) stats [ 'CLES' ] = round ( cles , 3 ) col_order = [ 'W-val' , 'p-val' , 'RBC' , 'CLES' ] stats = stats . reindex ( columns = col_order ) return stats | Wilcoxon signed - rank test . It is the non - parametric version of the paired T - test . |
17,780 | def kruskal ( dv = None , between = None , data = None , detailed = False , export_filename = None ) : from scipy . stats import chi2 , rankdata , tiecorrect _check_dataframe ( dv = dv , between = between , data = data , effects = 'between' ) data = data . dropna ( ) data = data . reset_index ( drop = True ) groups = list ( data [ between ] . unique ( ) ) n_groups = len ( groups ) n = data [ dv ] . size data [ 'rank' ] = rankdata ( data [ dv ] ) grp = data . groupby ( between ) [ 'rank' ] sum_rk_grp = grp . sum ( ) . values n_per_grp = grp . count ( ) . values H = ( 12 / ( n * ( n + 1 ) ) * np . sum ( sum_rk_grp ** 2 / n_per_grp ) ) - 3 * ( n + 1 ) H /= tiecorrect ( data [ 'rank' ] . values ) ddof1 = n_groups - 1 p_unc = chi2 . sf ( H , ddof1 ) stats = pd . DataFrame ( { 'Source' : between , 'ddof1' : ddof1 , 'H' : np . round ( H , 3 ) , 'p-unc' : p_unc , } , index = [ 'Kruskal' ] ) col_order = [ 'Source' , 'ddof1' , 'H' , 'p-unc' ] stats = stats . reindex ( columns = col_order ) stats . dropna ( how = 'all' , axis = 1 , inplace = True ) if export_filename is not None : _export_table ( stats , export_filename ) return stats | Kruskal - Wallis H - test for independent samples . |
17,781 | def friedman ( dv = None , within = None , subject = None , data = None , export_filename = None ) : from scipy . stats import rankdata , chi2 , find_repeats _check_dataframe ( dv = dv , within = within , data = data , subject = subject , effects = 'within' ) data = data . groupby ( [ subject , within ] ) . mean ( ) . reset_index ( ) if data [ dv ] . isnull ( ) . any ( ) : data = remove_rm_na ( dv = dv , within = within , subject = subject , data = data [ [ subject , within , dv ] ] ) grp = data . groupby ( within ) [ dv ] rm = list ( data [ within ] . unique ( ) ) k = len ( rm ) X = np . array ( [ grp . get_group ( r ) . values for r in rm ] ) . T n = X . shape [ 0 ] ranked = np . zeros ( X . shape ) for i in range ( n ) : ranked [ i ] = rankdata ( X [ i , : ] ) ssbn = ( ranked . sum ( axis = 0 ) ** 2 ) . sum ( ) Q = ( 12 / ( n * k * ( k + 1 ) ) ) * ssbn - 3 * n * ( k + 1 ) ties = 0 for i in range ( n ) : replist , repnum = find_repeats ( X [ i ] ) for t in repnum : ties += t * ( t * t - 1 ) c = 1 - ties / float ( k * ( k * k - 1 ) * n ) Q /= c ddof1 = k - 1 p_unc = chi2 . sf ( Q , ddof1 ) stats = pd . DataFrame ( { 'Source' : within , 'ddof1' : ddof1 , 'Q' : np . round ( Q , 3 ) , 'p-unc' : p_unc , } , index = [ 'Friedman' ] ) col_order = [ 'Source' , 'ddof1' , 'Q' , 'p-unc' ] stats = stats . reindex ( columns = col_order ) stats . dropna ( how = 'all' , axis = 1 , inplace = True ) if export_filename is not None : _export_table ( stats , export_filename ) return stats | Friedman test for repeated measurements . |
17,782 | def cochran ( dv = None , within = None , subject = None , data = None , export_filename = None ) : from scipy . stats import chi2 _check_dataframe ( dv = dv , within = within , data = data , subject = subject , effects = 'within' ) if data [ dv ] . isnull ( ) . any ( ) : data = remove_rm_na ( dv = dv , within = within , subject = subject , data = data [ [ subject , within , dv ] ] ) grp = data . groupby ( within ) [ dv ] grp_s = data . groupby ( subject ) [ dv ] k = data [ within ] . nunique ( ) dof = k - 1 q = ( dof * ( k * np . sum ( grp . sum ( ) ** 2 ) - grp . sum ( ) . sum ( ) ** 2 ) ) / ( k * grp . sum ( ) . sum ( ) - np . sum ( grp_s . sum ( ) ** 2 ) ) p_unc = chi2 . sf ( q , dof ) stats = pd . DataFrame ( { 'Source' : within , 'dof' : dof , 'Q' : np . round ( q , 3 ) , 'p-unc' : p_unc , } , index = [ 'cochran' ] ) if export_filename is not None : _export_table ( stats , export_filename ) return stats | Cochran Q test . Special case of the Friedman test when the dependant variable is binary . |
17,783 | def _multiline_width ( multiline_s , line_width_fn = len ) : return max ( map ( line_width_fn , re . split ( "[\r\n]" , multiline_s ) ) ) | Visible width of a potentially multiline content . |
17,784 | def _choose_width_fn ( has_invisible , enable_widechars , is_multiline ) : if has_invisible : line_width_fn = _visible_width elif enable_widechars : line_width_fn = wcwidth . wcswidth else : line_width_fn = len if is_multiline : def width_fn ( s ) : return _multiline_width ( s , line_width_fn ) else : width_fn = line_width_fn return width_fn | Return a function to calculate visible cell width . |
17,785 | def _align_header ( header , alignment , width , visible_width , is_multiline = False , width_fn = None ) : "Pad string header to width chars given known visible_width of the header." if is_multiline : header_lines = re . split ( _multiline_codes , header ) padded_lines = [ _align_header ( h , alignment , width , width_fn ( h ) ) for h in header_lines ] return "\n" . join ( padded_lines ) ninvisible = len ( header ) - visible_width width += ninvisible if alignment == "left" : return _padright ( width , header ) elif alignment == "center" : return _padboth ( width , header ) elif not alignment : return "{0}" . format ( header ) else : return _padleft ( width , header ) | Pad string header to width chars given known visible_width of the header . |
17,786 | def _prepend_row_index ( rows , index ) : if index is None or index is False : return rows if len ( index ) != len ( rows ) : print ( 'index=' , index ) print ( 'rows=' , rows ) raise ValueError ( 'index must be as long as the number of data rows' ) rows = [ [ v ] + list ( row ) for v , row in zip ( index , rows ) ] return rows | Add a left - most index column . |
17,787 | def _expand_numparse ( disable_numparse , column_count ) : if isinstance ( disable_numparse , Iterable ) : numparses = [ True ] * column_count for index in disable_numparse : numparses [ index ] = False return numparses else : return [ not disable_numparse ] * column_count | Return a list of bools of length column_count which indicates whether number parsing should be used on each column . If disable_numparse is a list of indices each of those indices are False and everything else is True . If disable_numparse is a bool then the returned list is all the same . |
17,788 | def pairwise_tukey ( dv = None , between = None , data = None , alpha = .05 , tail = 'two-sided' , effsize = 'hedges' ) : from pingouin . external . qsturng import psturng aov = anova ( dv = dv , data = data , between = between , detailed = True ) df = aov . loc [ 1 , 'DF' ] ng = aov . loc [ 0 , 'DF' ] + 1 grp = data . groupby ( between ) [ dv ] n = grp . count ( ) . values gmeans = grp . mean ( ) . values gvar = aov . loc [ 1 , 'MS' ] / n g1 , g2 = np . array ( list ( combinations ( np . arange ( ng ) , 2 ) ) ) . T mn = gmeans [ g1 ] - gmeans [ g2 ] se = np . sqrt ( gvar [ g1 ] + gvar [ g2 ] ) tval = mn / se pval = psturng ( np . sqrt ( 2 ) * np . abs ( tval ) , ng , df ) pval *= 0.5 if tail == 'one-sided' else 1 d = tval * np . sqrt ( 1 / n [ g1 ] + 1 / n [ g2 ] ) ef = convert_effsize ( d , 'cohen' , effsize , n [ g1 ] , n [ g2 ] ) stats = pd . DataFrame ( { 'A' : np . unique ( data [ between ] ) [ g1 ] , 'B' : np . unique ( data [ between ] ) [ g2 ] , 'mean(A)' : gmeans [ g1 ] , 'mean(B)' : gmeans [ g2 ] , 'diff' : mn , 'SE' : np . round ( se , 3 ) , 'tail' : tail , 'T' : np . round ( tval , 3 ) , 'p-tukey' : pval , 'efsize' : np . round ( ef , 3 ) , 'eftype' : effsize , } ) return stats | Pairwise Tukey - HSD post - hoc test . |
17,789 | def pairwise_gameshowell ( dv = None , between = None , data = None , alpha = .05 , tail = 'two-sided' , effsize = 'hedges' ) : from pingouin . external . qsturng import psturng _check_dataframe ( dv = dv , between = between , effects = 'between' , data = data ) data = data . reset_index ( drop = True ) ng = data [ between ] . nunique ( ) grp = data . groupby ( between ) [ dv ] n = grp . count ( ) . values gmeans = grp . mean ( ) . values gvars = grp . var ( ) . values g1 , g2 = np . array ( list ( combinations ( np . arange ( ng ) , 2 ) ) ) . T mn = gmeans [ g1 ] - gmeans [ g2 ] se = np . sqrt ( 0.5 * ( gvars [ g1 ] / n [ g1 ] + gvars [ g2 ] / n [ g2 ] ) ) tval = mn / np . sqrt ( gvars [ g1 ] / n [ g1 ] + gvars [ g2 ] / n [ g2 ] ) df = ( gvars [ g1 ] / n [ g1 ] + gvars [ g2 ] / n [ g2 ] ) ** 2 / ( ( ( ( gvars [ g1 ] / n [ g1 ] ) ** 2 ) / ( n [ g1 ] - 1 ) ) + ( ( ( gvars [ g2 ] / n [ g2 ] ) ** 2 ) / ( n [ g2 ] - 1 ) ) ) pval = psturng ( np . sqrt ( 2 ) * np . abs ( tval ) , ng , df ) pval *= 0.5 if tail == 'one-sided' else 1 d = tval * np . sqrt ( 1 / n [ g1 ] + 1 / n [ g2 ] ) ef = convert_effsize ( d , 'cohen' , effsize , n [ g1 ] , n [ g2 ] ) stats = pd . DataFrame ( { 'A' : np . unique ( data [ between ] ) [ g1 ] , 'B' : np . unique ( data [ between ] ) [ g2 ] , 'mean(A)' : gmeans [ g1 ] , 'mean(B)' : gmeans [ g2 ] , 'diff' : mn , 'SE' : se , 'tail' : tail , 'T' : tval , 'df' : df , 'pval' : pval , 'efsize' : ef , 'eftype' : effsize , } ) col_round = [ 'mean(A)' , 'mean(B)' , 'diff' , 'SE' , 'T' , 'df' , 'efsize' ] stats [ col_round ] = stats [ col_round ] . round ( 3 ) return stats | Pairwise Games - Howell post - hoc test . |
17,790 | def circ_axial ( alpha , n ) : alpha = np . array ( alpha ) return np . remainder ( alpha * n , 2 * np . pi ) | Transforms n - axial data to a common scale . |
17,791 | def circ_corrcc ( x , y , tail = 'two-sided' ) : from scipy . stats import norm x = np . asarray ( x ) y = np . asarray ( y ) if x . size != y . size : raise ValueError ( 'x and y must have the same length.' ) x , y = remove_na ( x , y , paired = True ) n = x . size x_sin = np . sin ( x - circmean ( x ) ) y_sin = np . sin ( y - circmean ( y ) ) r = np . sum ( x_sin * y_sin ) / np . sqrt ( np . sum ( x_sin ** 2 ) * np . sum ( y_sin ** 2 ) ) tval = np . sqrt ( ( n * ( x_sin ** 2 ) . mean ( ) * ( y_sin ** 2 ) . mean ( ) ) / np . mean ( x_sin ** 2 * y_sin ** 2 ) ) * r pval = 2 * norm . sf ( abs ( tval ) ) pval = pval / 2 if tail == 'one-sided' else pval return np . round ( r , 3 ) , pval | Correlation coefficient between two circular variables . |
17,792 | def circ_corrcl ( x , y , tail = 'two-sided' ) : from scipy . stats import pearsonr , chi2 x = np . asarray ( x ) y = np . asarray ( y ) if x . size != y . size : raise ValueError ( 'x and y must have the same length.' ) x , y = remove_na ( x , y , paired = True ) n = x . size rxs = pearsonr ( y , np . sin ( x ) ) [ 0 ] rxc = pearsonr ( y , np . cos ( x ) ) [ 0 ] rcs = pearsonr ( np . sin ( x ) , np . cos ( x ) ) [ 0 ] r = np . sqrt ( ( rxc ** 2 + rxs ** 2 - 2 * rxc * rxs * rcs ) / ( 1 - rcs ** 2 ) ) pval = chi2 . sf ( n * r ** 2 , 2 ) pval = pval / 2 if tail == 'one-sided' else pval return np . round ( r , 3 ) , pval | Correlation coefficient between one circular and one linear variable random variables . |
17,793 | def circ_mean ( alpha , w = None , axis = 0 ) : alpha = np . array ( alpha ) if isinstance ( w , ( list , np . ndarray ) ) : w = np . array ( w ) if alpha . shape != w . shape : raise ValueError ( "w must have the same shape as alpha." ) else : w = np . ones_like ( alpha ) return np . angle ( np . multiply ( w , np . exp ( 1j * alpha ) ) . sum ( axis = axis ) ) | Mean direction for circular data . |
17,794 | def circ_r ( alpha , w = None , d = None , axis = 0 ) : alpha = np . array ( alpha ) w = np . array ( w ) if w is not None else np . ones ( alpha . shape ) if alpha . size is not w . size : raise ValueError ( "Input dimensions do not match" ) r = np . multiply ( w , np . exp ( 1j * alpha ) ) . sum ( axis = axis ) r = np . abs ( r ) / w . sum ( axis = axis ) if d is not None : c = d / 2 / np . sin ( d / 2 ) r = c * r return r | Mean resultant vector length for circular data . |
17,795 | def circ_rayleigh ( alpha , w = None , d = None ) : alpha = np . array ( alpha ) if w is None : r = circ_r ( alpha ) n = len ( alpha ) else : if len ( alpha ) is not len ( w ) : raise ValueError ( "Input dimensions do not match" ) r = circ_r ( alpha , w , d ) n = np . sum ( w ) R = n * r z = ( R ** 2 ) / n pval = np . exp ( np . sqrt ( 1 + 4 * n + 4 * ( n ** 2 - R ** 2 ) ) - ( 1 + 2 * n ) ) return np . round ( z , 3 ) , pval | Rayleigh test for non - uniformity of circular data . |
17,796 | def bonf ( pvals , alpha = 0.05 ) : pvals = np . asarray ( pvals ) num_nan = np . isnan ( pvals ) . sum ( ) pvals_corrected = pvals * ( float ( pvals . size ) - num_nan ) pvals_corrected = np . clip ( pvals_corrected , None , 1 ) with np . errstate ( invalid = 'ignore' ) : reject = np . less ( pvals_corrected , alpha ) return reject , pvals_corrected | P - values correction with Bonferroni method . |
17,797 | def holm ( pvals , alpha = .05 ) : pvals = np . asarray ( pvals ) shape_init = pvals . shape pvals = pvals . ravel ( ) num_nan = np . isnan ( pvals ) . sum ( ) pvals_sortind = np . argsort ( pvals ) pvals_sorted = pvals [ pvals_sortind ] sortrevind = pvals_sortind . argsort ( ) ntests = pvals . size - num_nan pvals_corr = np . diag ( pvals_sorted * np . arange ( ntests , 0 , - 1 ) [ ... , None ] ) pvals_corr = np . maximum . accumulate ( pvals_corr ) pvals_corr = np . clip ( pvals_corr , None , 1 ) pvals_corr = np . append ( pvals_corr , np . full ( num_nan , np . nan ) ) pvals_corrected = pvals_corr [ sortrevind ] . reshape ( shape_init ) with np . errstate ( invalid = 'ignore' ) : reject = np . less ( pvals_corrected , alpha ) return reject , pvals_corrected | P - values correction with Holm method . |
17,798 | def multicomp ( pvals , alpha = 0.05 , method = 'holm' ) : if not isinstance ( pvals , ( list , np . ndarray ) ) : err = "pvals must be a list or a np.ndarray" raise ValueError ( err ) if method . lower ( ) in [ 'b' , 'bonf' , 'bonferroni' ] : reject , pvals_corrected = bonf ( pvals , alpha = alpha ) elif method . lower ( ) in [ 'h' , 'holm' ] : reject , pvals_corrected = holm ( pvals , alpha = alpha ) elif method . lower ( ) in [ 'fdr' , 'fdr_bh' ] : reject , pvals_corrected = fdr ( pvals , alpha = alpha , method = 'fdr_bh' ) elif method . lower ( ) in [ 'fdr_by' ] : reject , pvals_corrected = fdr ( pvals , alpha = alpha , method = 'fdr_by' ) elif method . lower ( ) == 'none' : pvals_corrected = pvals with np . errstate ( invalid = 'ignore' ) : reject = np . less ( pvals_corrected , alpha ) else : raise ValueError ( 'Multiple comparison method not recognized' ) return reject , pvals_corrected | P - values correction for multiple comparisons . |
17,799 | def cronbach_alpha ( data = None , items = None , scores = None , subject = None , remove_na = False , ci = .95 ) : assert isinstance ( data , pd . DataFrame ) , 'data must be a dataframe.' if all ( [ v is not None for v in [ items , scores , subject ] ] ) : data = data . pivot ( index = subject , values = scores , columns = items ) n , k = data . shape assert k >= 2 , 'At least two items are required.' assert n >= 2 , 'At least two raters/subjects are required.' err = 'All columns must be numeric.' assert all ( [ data [ c ] . dtype . kind in 'bfi' for c in data . columns ] ) , err if data . isna ( ) . any ( ) . any ( ) and remove_na : data = data . dropna ( axis = 0 , how = 'any' ) C = data . cov ( ) cronbach = ( k / ( k - 1 ) ) * ( 1 - np . trace ( C ) / C . sum ( ) . sum ( ) ) alpha = 1 - ci df1 = n - 1 df2 = df1 * ( k - 1 ) lower = 1 - ( 1 - cronbach ) * f . isf ( alpha / 2 , df1 , df2 ) upper = 1 - ( 1 - cronbach ) * f . isf ( 1 - alpha / 2 , df1 , df2 ) return round ( cronbach , 6 ) , np . round ( [ lower , upper ] , 3 ) | Cronbach s alpha reliability measure . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.