-
Notifications
You must be signed in to change notification settings - Fork 45
/
_classes.py
3448 lines (2656 loc) · 122 KB
/
_classes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*-coding: utf-8 -*-
# Author: Joses Ho
# Email : joseshowh@gmail.com
class Dabest(object):
"""
Class for estimation statistics and plots.
"""
def __init__(self, data, idx, x, y, paired, id_col, ci,
resamples, random_seed, proportional, delta2,
experiment, experiment_label, x1_level, mini_meta):
"""
Parses and stores pandas DataFrames in preparation for estimation
statistics. You should not be calling this class directly; instead,
use `dabest.load()` to parse your DataFrame prior to analysis.
"""
# Import standard data science libraries.
import numpy as np
import pandas as pd
import seaborn as sns
self.__delta2 = delta2
self.__experiment = experiment
self.__ci = ci
self.__data = data
self.__id_col = id_col
self.__is_paired = paired
self.__resamples = resamples
self.__random_seed = random_seed
self.__proportional = proportional
self.__mini_meta = mini_meta
# Make a copy of the data, so we don't make alterations to it.
data_in = data.copy()
# data_in.reset_index(inplace=True)
# data_in_index_name = data_in.index.name
# Check if it is a valid mini_meta case
if mini_meta is True:
# Only mini_meta calculation but not proportional and delta-delta function
if proportional is True:
err0 = '`proportional` and `mini_meta` cannot be True at the same time.'
raise ValueError(err0)
elif delta2 is True:
err0 = '`delta` and `mini_meta` cannot be True at the same time.'
raise ValueError(err0)
# Check if the columns stated are valid
if all([isinstance(i, str) for i in idx]):
if len(pd.unique([t for t in idx]).tolist())!=2:
err0 = '`mini_meta` is True, but `idx` ({})'.format(idx)
err1 = 'does not contain exactly 2 columns.'
raise ValueError(err0 + err1)
elif all([isinstance(i, (tuple, list)) for i in idx]):
all_idx_lengths = [len(t) for t in idx]
if (np.array(all_idx_lengths) != 2).any():
err1 = "`mini_meta` is True, but some idx "
err2 = "in {} does not consist only of two groups.".format(idx)
raise ValueError(err1 + err2)
# Check if this is a 2x2 ANOVA case and x & y are valid columns
# Create experiment_label and x1_level
if delta2 is True:
if proportional is True:
err0 = '`proportional` and `delta` cannot be True at the same time.'
raise ValueError(err0)
# idx should not be specified
if idx:
err0 = '`idx` should not be specified when `delta2` is True.'.format(len(x))
raise ValueError(err0)
# Check if x is valid
if len(x) != 2:
err0 = '`delta2` is True but the number of variables indicated by `x` is {}.'.format(len(x))
raise ValueError(err0)
else:
for i in x:
if i not in data_in.columns:
err = '{0} is not a column in `data`. Please check.'.format(i)
raise IndexError(err)
# Check if y is valid
if not y:
err0 = '`delta2` is True but `y` is not indicated.'
raise ValueError(err0)
elif y not in data_in.columns:
err = '{0} is not a column in `data`. Please check.'.format(y)
raise IndexError(err)
# Check if experiment is valid
if experiment not in data_in.columns:
err = '{0} is not a column in `data`. Please check.'.format(experiment)
raise IndexError(err)
# Check if experiment_label is valid and create experiment when needed
if experiment_label:
if len(experiment_label) != 2:
err0 = '`experiment_label` does not have a length of 2.'
raise ValueError(err0)
else:
for i in experiment_label:
if i not in data_in[experiment].unique():
err = '{0} is not an element in the column `{1}` of `data`. Please check.'.format(i, experiment)
raise IndexError(err)
else:
experiment_label = data_in[experiment].unique()
# Check if x1_level is valid
if x1_level:
if len(x1_level) != 2:
err0 = '`x1_level` does not have a length of 2.'
raise ValueError(err0)
else:
for i in x1_level:
if i not in data_in[x[0]].unique():
err = '{0} is not an element in the column `{1}` of `data`. Please check.'.format(i, experiment)
raise IndexError(err)
else:
x1_level = data_in[x[0]].unique()
self.__experiment_label = experiment_label
self.__x1_level = x1_level
# Check if idx is specified
if delta2 is False and not idx:
err = '`idx` is not a column in `data`. Please check.'
raise IndexError(err)
# create new x & idx and record the second variable if this is a valid 2x2 ANOVA case
if delta2 is True:
# add a new column which is a combination of experiment and the first variable
new_col_name = experiment+x[0]
while new_col_name in data_in.columns:
new_col_name += "_"
data_in[new_col_name] = data_in[x[0]].astype(str) + " " + data_in[experiment].astype(str)
#create idx and record the first and second x variable
idx = []
for i in list(map(lambda x: str(x), experiment_label)):
temp = []
for j in list(map(lambda x: str(x), x1_level)):
temp.append(j + " " + i)
idx.append(temp)
self.__idx = idx
self.__x1 = x[0]
self.__x2 = x[1]
x = new_col_name
else:
self.__idx = idx
self.__x1 = None
self.__x2 = None
# Determine the kind of estimation plot we need to produce.
if all([isinstance(i, str) for i in idx]):
# flatten out idx.
all_plot_groups = pd.unique([t for t in idx]).tolist()
if len(idx) > len(all_plot_groups):
err0 = '`idx` contains duplicated groups. Please remove any duplicates and try again.'
raise ValueError(err0)
# We need to re-wrap this idx inside another tuple so as to
# easily loop thru each pairwise group later on.
self.__idx = (idx,)
elif all([isinstance(i, (tuple, list)) for i in idx]):
all_plot_groups = pd.unique([tt for t in idx for tt in t]).tolist()
actual_groups_given = sum([len(i) for i in idx])
if actual_groups_given > len(all_plot_groups):
err0 = 'Groups are repeated across tuples,'
err1 = ' or a tuple has repeated groups in it.'
err2 = ' Please remove any duplicates and try again.'
raise ValueError(err0 + err1 + err2)
else: # mix of string and tuple?
err = 'There seems to be a problem with the idx you'
'entered--{}.'.format(idx)
raise ValueError(err)
# Having parsed the idx, check if it is a kosher paired plot,
# if so stated.
#if paired is True:
# all_idx_lengths = [len(t) for t in self.__idx]
# if (np.array(all_idx_lengths) != 2).any():
# err1 = "`is_paired` is True, but some idx "
# err2 = "in {} does not consist only of two groups.".format(idx)
# raise ValueError(err1 + err2)
# Check if there is a typo on paired
if paired is not None:
if paired not in ("baseline", "sequential"):
err = '{} assigned for `paired` is not valid.'.format(paired)
raise ValueError(err)
# Determine the type of data: wide or long.
if x is None and y is not None:
err = 'You have only specified `y`. Please also specify `x`.'
raise ValueError(err)
elif y is None and x is not None:
err = 'You have only specified `x`. Please also specify `y`.'
raise ValueError(err)
# Identify the type of data that was passed in.
elif x is not None and y is not None:
# Assume we have a long dataset.
# check both x and y are column names in data.
if x not in data_in.columns:
err = '{0} is not a column in `data`. Please check.'.format(x)
raise IndexError(err)
if y not in data_in.columns:
err = '{0} is not a column in `data`. Please check.'.format(y)
raise IndexError(err)
# check y is numeric.
if not np.issubdtype(data_in[y].dtype, np.number):
err = '{0} is a column in `data`, but it is not numeric.'.format(y)
raise ValueError(err)
# check all the idx can be found in data_in[x]
for g in all_plot_groups:
if g not in data_in[x].unique():
err0 = '"{0}" is not a group in the column `{1}`.'.format(g, x)
err1 = " Please check `idx` and try again."
raise IndexError(err0 + err1)
# Select only rows where the value in the `x` column
# is found in `idx`.
plot_data = data_in[data_in.loc[:, x].isin(all_plot_groups)].copy()
# plot_data.drop("index", inplace=True, axis=1)
# Assign attributes
self.__x = x
self.__y = y
self.__xvar = x
self.__yvar = y
elif x is None and y is None:
# Assume we have a wide dataset.
# Assign attributes appropriately.
self.__x = None
self.__y = None
self.__xvar = "group"
self.__yvar = "value"
# First, check we have all columns in the dataset.
for g in all_plot_groups:
if g not in data_in.columns:
err0 = '"{0}" is not a column in `data`.'.format(g)
err1 = " Please check `idx` and try again."
raise IndexError(err0 + err1)
set_all_columns = set(data_in.columns.tolist())
set_all_plot_groups = set(all_plot_groups)
id_vars = set_all_columns.difference(set_all_plot_groups)
plot_data = pd.melt(data_in,
id_vars=id_vars,
value_vars=all_plot_groups,
value_name=self.__yvar,
var_name=self.__xvar)
# Added in v0.2.7.
# remove any NA rows.
plot_data.dropna(axis=0, how='any', subset=[self.__yvar], inplace=True)
# Lines 131 to 140 added in v0.2.3.
# Fixes a bug that jammed up when the xvar column was already
# a pandas Categorical. Now we check for this and act appropriately.
if isinstance(plot_data[self.__xvar].dtype,
pd.CategoricalDtype) is True:
plot_data[self.__xvar].cat.remove_unused_categories(inplace=True)
plot_data[self.__xvar].cat.reorder_categories(all_plot_groups,
ordered=True,
inplace=True)
else:
plot_data.loc[:, self.__xvar] = pd.Categorical(plot_data[self.__xvar],
categories=all_plot_groups,
ordered=True)
# # The line below was added in v0.2.4, removed in v0.2.5.
# plot_data.dropna(inplace=True)
self.__plot_data = plot_data
self.__all_plot_groups = all_plot_groups
# Sanity check that all idxs are paired, if so desired.
#if paired is True:
# if id_col is None:
# err = "`id_col` must be specified if `is_paired` is set to True."
# raise IndexError(err)
# elif id_col not in plot_data.columns:
# err = "{} is not a column in `data`. ".format(id_col)
# raise IndexError(err)
# Check if `id_col` is valid
if paired:
if id_col is None:
err = "`id_col` must be specified if `paired` is assigned with a not NoneType value."
raise IndexError(err)
elif id_col not in plot_data.columns:
err = "{} is not a column in `data`. ".format(id_col)
raise IndexError(err)
EffectSizeDataFrame_kwargs = dict(ci=ci, is_paired=paired,
random_seed=random_seed,
resamples=resamples,
proportional=proportional,
delta2=delta2,
experiment_label=self.__experiment_label,
x1_level=self.__x1_level,
x2=self.__x2,
mini_meta = mini_meta)
self.__mean_diff = EffectSizeDataFrame(self, "mean_diff",
**EffectSizeDataFrame_kwargs)
self.__median_diff = EffectSizeDataFrame(self, "median_diff",
**EffectSizeDataFrame_kwargs)
self.__cohens_d = EffectSizeDataFrame(self, "cohens_d",
**EffectSizeDataFrame_kwargs)
self.__cohens_h = EffectSizeDataFrame(self, "cohens_h",
**EffectSizeDataFrame_kwargs)
self.__hedges_g = EffectSizeDataFrame(self, "hedges_g",
**EffectSizeDataFrame_kwargs)
if not paired:
self.__cliffs_delta = EffectSizeDataFrame(self, "cliffs_delta",
**EffectSizeDataFrame_kwargs)
else:
self.__cliffs_delta = "The data is paired; Cliff's delta is therefore undefined."
def __repr__(self):
from .__init__ import __version__
import datetime as dt
import numpy as np
from .misc_tools import print_greeting
# Removed due to the deprecation of is_paired
#if self.__is_paired:
# es = "Paired e"
#else:
# es = "E"
greeting_header = print_greeting()
RM_STATUS = {'baseline' : 'for repeated measures against baseline \n',
'sequential': 'for the sequential design of repeated-measures experiment \n',
'None' : ''
}
PAIRED_STATUS = {'baseline' : 'Paired e',
'sequential' : 'Paired e',
'None' : 'E'
}
first_line = {"rm_status" : RM_STATUS[str(self.__is_paired)],
"paired_status": PAIRED_STATUS[str(self.__is_paired)]}
s1 = "{paired_status}ffect size(s) {rm_status}".format(**first_line)
s2 = "with {}% confidence intervals will be computed for:".format(self.__ci)
desc_line = s1 + s2
out = [greeting_header + "\n\n" + desc_line]
comparisons = []
if self.__is_paired == 'sequential':
for j, current_tuple in enumerate(self.__idx):
for ix, test_name in enumerate(current_tuple[1:]):
control_name = current_tuple[ix]
comparisons.append("{} minus {}".format(test_name, control_name))
else:
for j, current_tuple in enumerate(self.__idx):
control_name = current_tuple[0]
for ix, test_name in enumerate(current_tuple[1:]):
comparisons.append("{} minus {}".format(test_name, control_name))
if self.__delta2 is True:
comparisons.append("{} minus {} (only for mean difference)".format(self.__experiment_label[1], self.__experiment_label[0]))
if self.__mini_meta is True:
comparisons.append("weighted delta (only for mean difference)")
for j, g in enumerate(comparisons):
out.append("{}. {}".format(j+1, g))
resamples_line1 = "\n{} resamples ".format(self.__resamples)
resamples_line2 = "will be used to generate the effect size bootstraps."
out.append(resamples_line1 + resamples_line2)
return "\n".join(out)
# def __variable_name(self):
# return [k for k,v in locals().items() if v is self]
#
# @property
# def variable_name(self):
# return self.__variable_name()
@property
def mean_diff(self):
"""
Returns an :py:class:`EffectSizeDataFrame` for the mean difference, its confidence interval, and relevant statistics, for all comparisons as indicated via the `idx` and `paired` argument in `dabest.load()`.
Example
-------
>>> from scipy.stats import norm
>>> import pandas as pd
>>> import dabest
>>> control = norm.rvs(loc=0, size=30, random_state=12345)
>>> test = norm.rvs(loc=0.5, size=30, random_state=12345)
>>> my_df = pd.DataFrame({"control": control,
"test": test})
>>> my_dabest_object = dabest.load(my_df, idx=("control", "test"))
>>> my_dabest_object.mean_diff
Notes
-----
This is simply the mean of the control group subtracted from
the mean of the test group.
.. math::
\\text{Mean difference} = \\overline{x}_{Test} - \\overline{x}_{Control}
where :math:`\\overline{x}` is the mean for the group :math:`x`.
"""
return self.__mean_diff
@property
def median_diff(self):
"""
Returns an :py:class:`EffectSizeDataFrame` for the median difference, its confidence interval, and relevant statistics, for all comparisons as indicated via the `idx` and `paired` argument in `dabest.load()`.
Example
-------
>>> from scipy.stats import norm
>>> import pandas as pd
>>> import dabest
>>> control = norm.rvs(loc=0, size=30, random_state=12345)
>>> test = norm.rvs(loc=0.5, size=30, random_state=12345)
>>> my_df = pd.DataFrame({"control": control,
"test": test})
>>> my_dabest_object = dabest.load(my_df, idx=("control", "test"))
>>> my_dabest_object.median_diff
Notes
-----
This is the median difference between the control group and the test group.
If the comparison(s) are unpaired, median_diff is computed with the following equation:
.. math::
\\text{Median difference} = \\widetilde{x}_{Test} - \\widetilde{x}_{Control}
where :math:`\\widetilde{x}` is the median for the group :math:`x`.
If the comparison(s) are paired, median_diff is computed with the following equation:
.. math::
\\text{Median difference} = \\widetilde{x}_{Test - Control}
"""
return self.__median_diff
@property
def cohens_d(self):
"""
Returns an :py:class:`EffectSizeDataFrame` for the standardized mean difference Cohen's `d`, its confidence interval, and relevant statistics, for all comparisons as indicated via the `idx` and `paired` argument in `dabest.load()`.
Example
-------
>>> from scipy.stats import norm
>>> import pandas as pd
>>> import dabest
>>> control = norm.rvs(loc=0, size=30, random_state=12345)
>>> test = norm.rvs(loc=0.5, size=30, random_state=12345)
>>> my_df = pd.DataFrame({"control": control,
"test": test})
>>> my_dabest_object = dabest.load(my_df, idx=("control", "test"))
>>> my_dabest_object.cohens_d
Notes
-----
Cohen's `d` is simply the mean of the control group subtracted from
the mean of the test group.
If `paired` is None, then the comparison(s) are unpaired;
otherwise the comparison(s) are paired.
If the comparison(s) are unpaired, Cohen's `d` is computed with the following equation:
.. math::
d = \\frac{\\overline{x}_{Test} - \\overline{x}_{Control}} {\\text{pooled standard deviation}}
For paired comparisons, Cohen's d is given by
.. math::
d = \\frac{\\overline{x}_{Test} - \\overline{x}_{Control}} {\\text{average standard deviation}}
where :math:`\\overline{x}` is the mean of the respective group of observations, :math:`{Var}_{x}` denotes the variance of that group,
.. math::
\\text{pooled standard deviation} = \\sqrt{ \\frac{(n_{control} - 1) * {Var}_{control} + (n_{test} - 1) * {Var}_{test} } {n_{control} + n_{test} - 2} }
and
.. math::
\\text{average standard deviation} = \\sqrt{ \\frac{{Var}_{control} + {Var}_{test}} {2}}
The sample variance (and standard deviation) uses N-1 degrees of freedoms.
This is an application of `Bessel's correction <https://en.wikipedia.org/wiki/Bessel%27s_correction>`_, and yields the unbiased
sample variance.
References:
https://en.wikipedia.org/wiki/Effect_size#Cohen's_d
https://en.wikipedia.org/wiki/Bessel%27s_correction
https://en.wikipedia.org/wiki/Standard_deviation#Corrected_sample_standard_deviation
"""
return self.__cohens_d
@property
def cohens_h(self):
"""
Returns an :py:class:`EffectSizeDataFrame` for the standardized mean difference Cohen's `h`, its confidence interval, and relevant statistics, for all comparisons as indicated via the `idx` and `directional` argument in `dabest.load()`.
Example
-------
>>> from scipy.stats import randint
>>> import pandas as pd
>>> import dabest
>>> control = randint.rvs(0, 2, size=30, random_state=12345)
>>> test = randint.rvs(0, 2, size=30, random_state=12345)
>>> my_df = pd.DataFrame({"control": control,
"test": test})
>>> my_dabest_object = dabest.load(my_df, idx=("control", "test")
>>> my_dabest_object.cohens_h
Notes
-----
Cohen's *h* uses the information of proportion in the control and test groups to calculate the distance between two proportions.
It can be used to describe the difference between two proportions as "small", "medium", or "large".
It can be used to determine if the difference between two proportions is "meaningful".
A directional Cohen's *h* is computed with the following equation:
.. math::
h = 2 * \\arcsin{\\sqrt{proportion_{Test}}} - 2 * \\arcsin{\\sqrt{proportion_{Control}}}
For a non-directional Cohen's *h*, the equation is:
.. math::
h = |2 * \\arcsin{\\sqrt{proportion_{Test}}} - 2 * \\arcsin{\\sqrt{proportion_{Control}}}|
References:
https://en.wikipedia.org/wiki/Cohen%27s_h
"""
return self.__cohens_h
@property
def hedges_g(self):
"""
Returns an :py:class:`EffectSizeDataFrame` for the standardized mean difference Hedges' `g`, its confidence interval, and relevant statistics, for all comparisons as indicated via the `idx` and `paired` argument in `dabest.load()`.
Example
-------
>>> from scipy.stats import norm
>>> import pandas as pd
>>> import dabest
>>> control = norm.rvs(loc=0, size=30, random_state=12345)
>>> test = norm.rvs(loc=0.5, size=30, random_state=12345)
>>> my_df = pd.DataFrame({"control": control,
"test": test})
>>> my_dabest_object = dabest.load(my_df, idx=("control", "test"))
>>> my_dabest_object.hedges_g
Notes
-----
Hedges' `g` is :py:attr:`cohens_d` corrected for bias via multiplication with the following correction factor:
.. math::
\\frac{ \\Gamma( \\frac{a} {2} )} {\\sqrt{ \\frac{a} {2} } \\times \\Gamma( \\frac{a - 1} {2} )}
where
.. math::
a = {n}_{control} + {n}_{test} - 2
and :math:`\\Gamma(x)` is the `Gamma function <https://en.wikipedia.org/wiki/Gamma_function>`_.
References:
https://en.wikipedia.org/wiki/Effect_size#Hedges'_g
https://journals.sagepub.com/doi/10.3102/10769986006002107
"""
return self.__hedges_g
@property
def cliffs_delta(self):
"""
Returns an :py:class:`EffectSizeDataFrame` for Cliff's delta, its confidence interval, and relevant statistics, for all comparisons as indicated via the `idx` and `paired` argument in `dabest.load()`.
Example
-------
>>> from scipy.stats import norm
>>> import pandas as pd
>>> import dabest
>>> control = norm.rvs(loc=0, size=30, random_state=12345)
>>> test = norm.rvs(loc=0.5, size=30, random_state=12345)
>>> my_df = pd.DataFrame({"control": control,
"test": test})
>>> my_dabest_object = dabest.load(my_df, idx=("control", "test"))
>>> my_dabest_object.cliffs_delta
Notes
-----
Cliff's delta is a measure of ordinal dominance, ie. how often the values from the test sample are larger than values from the control sample.
.. math::
\\text{Cliff's delta} = \\frac{\\#({x}_{test} > {x}_{control}) - \\#({x}_{test} < {x}_{control})} {{n}_{Test} \\times {n}_{Control}}
where :math:`\\#` denotes the number of times a value from the test sample exceeds (or is lesser than) values in the control sample.
Cliff's delta ranges from -1 to 1; it can also be thought of as a measure of the degree of overlap between the two samples. An attractive aspect of this effect size is that it does not make an assumptions about the underlying distributions that the samples were drawn from.
References:
https://en.wikipedia.org/wiki/Effect_size#Effect_size_for_ordinal_data
https://psycnet.apa.org/record/1994-08169-001
"""
return self.__cliffs_delta
@property
def data(self):
"""
Returns the pandas DataFrame that was passed to `dabest.load()`.
When `delta2` is True, a new column is added to support the
function. The name of this new column is indicated by `x`.
"""
return self.__data
@property
def idx(self):
"""
Returns the order of categories that was passed to `dabest.load()`.
"""
return self.__idx
@property
def x1(self):
"""
Returns the first variable declared in x when it is a delta-delta
case; returns None otherwise.
"""
return self.__x1
@property
def x1_level(self):
"""
Returns the levels of first variable declared in x when it is a
delta-delta case; returns None otherwise.
"""
return self.__x1_level
@property
def x2(self):
"""
Returns the second variable declared in x when it is a delta-delta
case; returns None otherwise.
"""
return self.__x2
@property
def experiment(self):
"""
Returns the column name of experiment labels that was passed to
`dabest.load()` when it is a delta-delta case; returns None otherwise.
"""
return self.__experiment
@property
def experiment_label(self):
"""
Returns the experiment labels in order that was passed to `dabest.load()`
when it is a delta-delta case; returns None otherwise.
"""
return self.__experiment_label
@property
def delta2(self):
"""
Returns the boolean parameter indicating if this is a delta-delta
situation.
"""
return self.__delta2
@property
def is_paired(self):
"""
Returns the type of repeated-measures experiment.
"""
return self.__is_paired
@property
def id_col(self):
"""
Returns the id column declared to `dabest.load()`.
"""
return self.__id_col
@property
def ci(self):
"""
The width of the desired confidence interval.
"""
return self.__ci
@property
def resamples(self):
"""
The number of resamples used to generate the bootstrap.
"""
return self.__resamples
@property
def random_seed(self):
"""
The number used to initialise the numpy random seed generator, ie.
`seed_value` from `numpy.random.seed(seed_value)` is returned.
"""
return self.__random_seed
@property
def x(self):
"""
Returns the x column that was passed to `dabest.load()`, if any.
When `delta2` is True, `x` returns the name of the new column created
for the delta-delta situation. To retrieve the 2 variables passed into
`x` when `delta2` is True, please call `x1` and `x2` instead.
"""
return self.__x
@property
def y(self):
"""
Returns the y column that was passed to `dabest.load()`, if any.
"""
return self.__y
@property
def _xvar(self):
"""
Returns the xvar in dabest.plot_data.
"""
return self.__xvar
@property
def _yvar(self):
"""
Returns the yvar in dabest.plot_data.
"""
return self.__yvar
@property
def _plot_data(self):
"""
Returns the pandas DataFrame used to produce the estimation stats/plots.
"""
return self.__plot_data
@property
def proportional(self):
"""
Returns the proportional parameter class.
"""
return self.__proportional
@property
def mini_meta(self):
"""
Returns the mini_meta boolean parameter.
"""
return self.__mini_meta
@property
def _all_plot_groups(self):
"""
Returns the all plot groups, as indicated via the `idx` keyword.
"""
return self.__all_plot_groups
class DeltaDelta(object):
"""
A class to compute and store the delta-delta statistics. In a 2-by-2 arrangement where two independent variables, A and B, each have two categorical values, two primary deltas are first calculated with one independent variable and a delta-delta effect size is calculated as a difference between the two primary deltas.
.. math::
\\hat{\\theta}_{B1} = \\overline{X}_{A2, B1} - \\overline{X}_{A1, B1}
\\hat{\\theta}_{B2} = \\overline{X}_{A2, B2} - \\overline{X}_{A1, B2}
.. math::
\\hat{\\theta}_{\\theta} = \\hat{\\theta}_{B2} - \\hat{\\theta}_{B1}
and:
.. math::
s_{\\theta} = \\frac{(n_{A2, B1}-1)s_{A2, B1}^2+(n_{A1, B1}-1)s_{A1, B1}^2+(n_{A2, B2}-1)s_{A2, B2}^2+(n_{A1, B2}-1)s_{A1, B2}^2}{(n_{A2, B1} - 1) + (n_{A1, B1} - 1) + (n_{A2, B2} - 1) + (n_{A1, B2} - 1)}
Example
-------
>>> import numpy as np
>>> import pandas as pd
>>> from scipy.stats import norm # Used in generation of populations.
>>> np.random.seed(9999) # Fix the seed so the results are replicable.
>>> from scipy.stats import norm # Used in generation of populations.
>>> N = 20
>>> # Create samples
>>> y = norm.rvs(loc=3, scale=0.4, size=N*4)
>>> y[N:2*N] = y[N:2*N]+1
>>> y[2*N:3*N] = y[2*N:3*N]-0.5
>>> # Add drug column
>>> t1 = np.repeat('Placebo', N*2).tolist()
>>> t2 = np.repeat('Drug', N*2).tolist()
>>> treatment = t1 + t2
>>> # Add a `rep` column as the first variable for the 2 replicates of experiments done
>>> rep = []
>>> for i in range(N*2):
>>> rep.append('Rep1')
>>> rep.append('Rep2')
>>> # Add a `genotype` column as the second variable
>>> wt = np.repeat('W', N).tolist()
>>> mt = np.repeat('M', N).tolist()
>>> wt2 = np.repeat('W', N).tolist()
>>> mt2 = np.repeat('M', N).tolist()
>>> genotype = wt + mt + wt2 + mt2
>>> # Add an `id` column for paired data plotting.
>>> id = list(range(0, N*2))
>>> id_col = id + id
>>> # Combine all columns into a DataFrame.
>>> df_delta2 = pd.DataFrame({'ID' : id_col,
>>> 'Rep' : rep,
>>> 'Genotype' : genotype,
>>> 'Drug': treatment,
>>> 'Y' : y
>>> })
"""
def __init__(self, effectsizedataframe, permutation_count,
ci=95):
import numpy as np
from numpy import sort as npsort
from numpy import sqrt, isinf, isnan
from ._stats_tools import effsize as es
from ._stats_tools import confint_1group as ci1g
from ._stats_tools import confint_2group_diff as ci2g
from string import Template
import warnings
self.__effsizedf = effectsizedataframe.results
self.__dabest_obj = effectsizedataframe.dabest_obj
self.__ci = ci
self.__resamples = effectsizedataframe.resamples
self.__alpha = ci2g._compute_alpha_from_ci(ci)
self.__permutation_count = permutation_count
self.__bootstraps = np.array(self.__effsizedf["bootstraps"])
self.__control = self.__dabest_obj.experiment_label[0]
self.__test = self.__dabest_obj.experiment_label[1]
# Compute the bootstrap delta-delta and the true dela-delta based on
# the raw data
self.__bootstraps_delta_delta = self.__bootstraps[1] - self.__bootstraps[0]
self.__difference = self.__effsizedf["difference"][1] - self.__effsizedf["difference"][0]
sorted_delta_delta = npsort(self.__bootstraps_delta_delta)
self.__bias_correction = ci2g.compute_meandiff_bias_correction(
self.__bootstraps_delta_delta, self.__difference)
self.__jackknives = np.array(ci1g.compute_1group_jackknife(
self.__bootstraps_delta_delta,
np.mean))
self.__acceleration_value = ci2g._calc_accel(self.__jackknives)
# Compute BCa intervals.
bca_idx_low, bca_idx_high = ci2g.compute_interval_limits(
self.__bias_correction, self.__acceleration_value,
self.__resamples, ci)
self.__bca_interval_idx = (bca_idx_low, bca_idx_high)
if ~isnan(bca_idx_low) and ~isnan(bca_idx_high):
self.__bca_low = sorted_delta_delta[bca_idx_low]
self.__bca_high = sorted_delta_delta[bca_idx_high]
err1 = "The $lim_type limit of the interval"
err2 = "was in the $loc 10 values."
err3 = "The result should be considered unstable."
err_temp = Template(" ".join([err1, err2, err3]))
if bca_idx_low <= 10:
warnings.warn(err_temp.substitute(lim_type="lower",
loc="bottom"),
stacklevel=1)
if bca_idx_high >= self.__resamples-9:
warnings.warn(err_temp.substitute(lim_type="upper",
loc="top"),
stacklevel=1)
else:
err1 = "The $lim_type limit of the BCa interval cannot be computed."
err2 = "It is set to the effect size itself."
err3 = "All bootstrap values were likely all the same."
err_temp = Template(" ".join([err1, err2, err3]))
if isnan(bca_idx_low):
self.__bca_low = self.__difference
warnings.warn(err_temp.substitute(lim_type="lower"),
stacklevel=0)