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...
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...
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_delet...
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 ] ...
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_%(cl...
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 ...
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...
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...
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...
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 ....
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...
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 ( ...
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 ....
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 ( org...
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...
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...
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 . lig...
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 ] po...
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 ...
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_appen...
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}:{:...
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 ({})' . ...
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...
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...
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 se...
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 =...
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 } ...
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_dat...
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 . ...
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 ] ] ....
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_b...
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 = float...
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 ...
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 i...
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 ) ) [ ...
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 no...
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 = bart...
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...
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 )...
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 ...
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 ( co...
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 V...
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. Swit...
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 ...
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 ...
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...
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 ( dcov...
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 ...
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 [ i...
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 ...
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 = l...
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 ( ) . ...
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...
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_w...
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...
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 ) ] re...
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 ....
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 [ bet...
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 . ...
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 ...
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 . e...
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 = n...
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 . ...
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 )...
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_cor...
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 . lowe...
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 , col...
Cronbach s alpha reliability measure .