-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplottol.py
More file actions
2108 lines (1803 loc) · 85.3 KB
/
plottol.py
File metadata and controls
2108 lines (1803 loc) · 85.3 KB
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
#%matplotlib qt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st
import scipy.stats
import scipy.integrate as integrate
import scipy.optimize as opt
import warnings
import statistics
warnings.filterwarnings('ignore')
import warnings
from scipy.optimize import curve_fit
import math
warnings.filterwarnings('ignore')
def Kfactor(n, f = None, alpha = 0.05, P = 0.99, side = 1, method = 'HE', m=50):
K=None
if f == None:
f = n-1
if (len((n,)*1)) != len((f,)*1) and (len((f,)*1) > 1):
return 'Length of \'f\' needs to match length of \'n\'!'
if (side != 1) and (side != 2):
return 'Must specify one sided or two sided procedure'
if side ==1:
zp = scipy.stats.norm.ppf(P)
ncp = np.sqrt(n)*zp
ta = scipy.stats.nct.ppf(1-alpha,df = f, nc=ncp) #students t noncentralized
K = ta/np.sqrt(n)
else:
def Ktemp(n, f, alpha, P, method, m):
chia = scipy.stats.chi2.ppf(alpha, df = f)
k2 = np.sqrt(f*scipy.stats.ncx2.ppf(P,df=1,nc=(1/n))/chia) #noncentralized chi 2 (ncx2))
if method == 'HE':
def TEMP4(n, f, P, alpha):
chia = scipy.stats.chi2.ppf(alpha, df = f)
zp = scipy.stats.norm.ppf((1+P)/2)
za = scipy.stats.norm.ppf((2-alpha)/2)
dfcut = n**2*(1+(1/za**2))
V = 1 + (za**2)/n + ((3-zp**2)*za**4)/(6*n**2)
K1 = (zp * np.sqrt(V * (1 + (n * V/(2 * f)) * (1 + 1/za**2))))
G = (f-2-chia)/(2*(n+1)**2)
K2 = (zp * np.sqrt(((f * (1 + 1/n))/(chia)) * (1 + G)))
if f > dfcut:
K = K1
else:
K = K2
if K == np.nan or K == None:
K = 0
return K
#TEMP5 = np.vectorize(TEMP4())
K = TEMP4(n, f, P, alpha)
return K
elif method == 'HE2':
zp = scipy.stats.norm.ppf((1+P)/2)
K = zp * np.sqrt((1+1/n)*f/chia)
return K
elif method == 'WBE':
r = 0.5
delta = 1
while abs(delta) > 0.00000001:
Pnew = scipy.stats.norm.cdf(1/np.sqrt(n)+r) - scipy.stats.norm.cdf(1/np.sqrt(n)-r)
delta = Pnew-P
diff = scipy.stats.norm.pdf(1/np.sqrt(n)+r) + scipy.stats.norm.pdf(1/np.sqrt(n)-r)
r = r-delta/diff
K = r*np.sqrt(f/chia)
return K
elif method == 'ELL':
if f < n**2:
print("Warning Message:\nThe ellison method should only be used for f appreciably larger than n^2")
r = 0.5
delta = 1
zp = scipy.stats.norm.ppf((1+P)/2)
while abs(delta) > 0.00000001:
Pnew = scipy.stats.norm.cdf(zp/np.sqrt(n)+r) - scipy.stats.norm.cdf(zp/np.sqrt(n)-r)
delta = Pnew - P
diff = scipy.stats.norm.pdf(zp/np.sqrt(n)+r) + scipy.stats.norm.pdf(zp/np.sqrt(n)-r)
r = r-delta/diff
K = r*np.sqrt(f/chia)
return K
elif method == 'KM':
K = k2
return K
elif method == 'OCT':
delta = np.sqrt(n)*scipy.stats.norm.ppf((1+P)/2)
def Fun1(z,P,ke,n,f1,delta):
return (2 * scipy.stats.norm.cdf(-delta + (ke * np.sqrt(n * z))/(np.sqrt(f1))) - 1) * scipy.stats.chi2.pdf(z,f1)
def Fun2(ke, P, n, f1, alpha, m, delta):
if n < 75:
return integrate.quad(Fun1,a = f1 * delta**2/(ke**2 * n), b = np.inf, args=(P,ke,n,f1,delta),limit = m)
else:
return integrate.quad(Fun1,a = f1 * delta**2/(ke**2 * n), b = n*1000, args=(P,ke,n,f1,delta),limit = m)
def Fun3(ke,P,n,f1,alpha,m,delta):
f = Fun2(ke = ke, P = P, n = n, f1 = f1, alpha = alpha, m = m, delta = delta)
return abs(f[0] - (1-alpha))
K = opt.minimize(fun=Fun3, x0=k2,args=(P,n,f,alpha,m,delta), method = 'L-BFGS-B')['x']
return float(K)
elif method == 'EXACT':
def fun1(z,df1,P,X,n):
k = (scipy.stats.chi2.sf(df1*scipy.stats.ncx2.ppf(P,1,z**2)/X**2,df=df1)*np.exp(-0.5*n*z**2))
return k
def fun2(X,df1,P,n,alpha,m):
return integrate.quad(fun1,a =0, b = 5, args=(df1,P,X,n),limit=m)
def fun3(X,df1,P,n,alpha,m):
return np.sqrt(2*n/np.pi)*fun2(X,df1,P,n,alpha,m)[0]-(1-alpha)
K = opt.brentq(f=fun3,a=0,b=k2+(1000)/n, args=(f,P,n,alpha,m))
return K
K = Ktemp(n=n,f=f,alpha=alpha,P=P,method=method,m=m)
return K
def normtolint(x, alpha = 0.05, P = 0.99, side = 1, method = 'HE', m = 50, lognorm = False):
'''
normtolint(x, alpha = 0.05, P = 0.99, side = 1, method = ["HE", "HE2", "WBE", "ELL", "KM", "EXACT", "OCT"], m = 50, lognorm = False):
Parameters
----------
x: list
A vector of data which is distributed according to either a normal
distribution or a log-normal distribution.
alpha: float, optional
The level chosen such that 1-alpha is the confidence level.
The default is 0.05.
P: float, optional
The proportion of the population to be covered by this tolerance
interval. The default is 0.99.
side: 1 or 2, optional
Whether a 1-sided or 2-sided tolerance interval is required
(determined by side = 1 or side = 2, respectively). The default is 1.
method: string, optional
The method for calculating the k-factors. The k-factor for the 1-sided
tolerance intervals is performed exactly and thus is the same for the
chosen method.
"HE" is the Howe method and is often viewed as being extremely
accurate, even for small sample sizes.
"HE2" is a second method due to Howe, which performs similarly to the
Weissberg-Beatty method, but is computationally simpler.
"WBE" is the Weissberg-Beatty method
(also called the Wald-Wolfowitz method), which performs similarly to
the first Howe method for larger sample sizes.
"ELL" is the Ellison correction to the Weissberg-Beatty method when f
is appreciably larger than n^2. A warning message is displayed if f is
not larger than n^2. "KM" is the Krishnamoorthy-Mathew approximation
to the exact solution, which works well for larger sample sizes.
"EXACT" computes the k-factor exactly by finding the integral solution
to the problem via the integrate function. Note the computation time
of this method is largely determined by m.
"OCT" is the Owen approach to compute the k-factor when controlling
the tails so that there is not more than (1-P)/2 of the data in each
tail of the distribution.
The default is "HE"
m: int, optional
The maximum number of subintervals to be used in the integrate
function. This is necessary only for method = "EXACT" and method =
"OCT". The larger the number, the more accurate the solution. Too low
of a value can result in an error. A large value can also cause the
function to be slow for method = "EXACT". The default is m = 50.
lower: float, optional
If TRUE, then the data is considered to be from a log-normal
distribution, in which case the output gives tolerance intervals for
the log-normal distribution. The default is False.
Details
Recall that if the random variable X is distributed according to a
log-normal distribution, then the random variable Y = ln(X) is distributed
according to a normal distribution.
Returns
-------
normtolint returns a data frame with items:
alpha:
The specified significance level.
P:
The proportion of the population covered by this tolerance interval.
mean:
The sample mean.
1-sided.lower:
The 1-sided lower tolerance bound. This is given only if side = 1.
1-sided.upper:
The 1-sided upper tolerance bound. This is given only if side = 1.
2-sided.lower:
The 2-sided lower tolerance bound. This is given only if side = 2.
2-sided.upper:
The 2-sided upper tolerance bound. This is given only if side = 2.
References
----------
Derek S. Young (2010). tolerance: An R Package for Estimating Tolerance
Intervals. Journal of Statistical Software, 36(5), 1-39.
URL http://www.jstatsoft.org/v36/i05/.
Howe, W. G. (1969), Two-Sided Tolerance Limits for Normal Populations -
Some Improvements, Journal of the American Statistical Association,
64, 610–620.
Wald, A. and Wolfowitz, J. (1946), Tolerance Limits for a Normal
Distribution, Annals of Mathematical Statistics, 17, 208–215.
Weissberg, A. and Beatty, G. (1969), Tables of Tolerance Limit Factors
for Normal Distributions, Technometrics, 2, 483–500.
Examples
--------
## 95%/95% 2-sided normal tolerance intervals for a sample of size 100.
x = np.random.normal(size=100)
normtolint(x, alpha = 0.05, P = 0.95, side = 2,
method = "HE", log.norm = FALSE)
'''
if lognorm:
x = np.log(x)
xbar = np.mean(x)
s = statistics.stdev(x)
n = len(x)
K = Kfactor(n, alpha=alpha, P=P, side = side, method= method, m = m)
lower = xbar-s*K
upper = xbar+s*K
if(lognorm):
lower = np.exp(lower)
upper = np.exp(upper)
xbar = np.exp(xbar)
if side == 1:
temp = pd.DataFrame([[alpha,P, xbar,lower,upper]],columns=['alpha','P','mean','1-sided.lower','1-sided.upper'])
return temp
else:
temp = pd.DataFrame([[alpha,P, xbar,lower,upper]],columns=['alpha','P','mean','2-sided.lower','2-sided.upper'])
return temp
from statsmodels.formula.api import ols
from statsmodels.stats.anova import anova_lm
import scipy.stats as stats
def levels(data,out):
rownames = pd.Series(out.index)
levels = []
st = []
for i in range(1,len(rownames)):
levels.append(np.unique(np.array(data.iloc[:,i])))
st.append([rownames[i-1],[levels[i-1]]])
return st
def to_int(x):
try:
return int(x)
except:
return 0
def anovatolint(lmout, data, alpha = 0.05, P = 0.99, side = 1, method = 'HE', m = 50):
'''
Tolerance Intervals for ANOVA
Description
Tolerance intervals for each factor level in a balanced
(or nearly-balanced) ANOVA.
Usage
anovatolint(lmout, data, alpha = 0.05, P = 0.99, side = 1,
method = ["HE", "HE2", "WBE", "ELL", "KM", "EXACT", "OCT"],
m = 50)
Parameters
----------
lmout : lm object - ols('y~x*',data=data).fit()
An object of class lm (i.e., the results from the linear model fitting
routine such that the anova function can act upon).
data : dataframe
A data frame consisting of the data fitted in lm.out. Note that data
must have one column for each main effect (i.e., factor) that is
analyzed in lmout and that these columns must be of class factor.
alpha : float, optional
The level chosen such that 1-alpha is the confidence level. The
default is 0.05.
P : float, optional
The proportion of the population to be covered by this tolerance
interval. The default is 0.99.
side : TYPE, optional
Whether a 1-sided or 2-sided tolerance interval is required
(determined by side = 1 or side = 2, respectively). The default is 1.
method : string, optional
The method for calculating the k-factors. The k-factor for the 1-sided
tolerance intervals is performed exactly and thus is the same for the
chosen method.
"HE" is the Howe method and is often viewed as being extremely
accurate, even for small sample sizes.
"HE2" is a second method due to Howe, which performs similarly to the
Weissberg-Beatty method, but is computationally simpler.
"WBE" is the Weissberg-Beatty method
(also called the Wald-Wolfowitz method), which performs similarly to
the first Howe method for larger sample sizes.
"ELL" is the Ellison correction to the Weissberg-Beatty method when f
is appreciably larger than n^2. A warning message is displayed if f is
not larger than n^2. "KM" is the Krishnamoorthy-Mathew approximation
to the exact solution, which works well for larger sample sizes.
"EXACT" computes the k-factor exactly by finding the integral solution
to the problem via the integrate function. Note the computation time
of this method is largely determined by m.
"OCT" is the Owen approach to compute the k-factor when controlling
the tails so that there is not more than (1-P)/2 of the data in each
tail of the distribution.
The default is "HE"
m : TYPE, optional
The maximum number of subintervals to be used in the integrate
function. This is necessary only for method = "EXACT" and method =
"OCT". The larger the number, the more accurate the solution. Too low
of a value can result in an error. A large value can also cause the
function to be slow for method = "EXACT". The default is 50.
Returns
-------
anovatol.int returns a list where each element is a dataframe
corresponding to each main effect (i.e., factor) tested in the ANOVA and
the rows of each data frame are the levels of that factor. The columns of
each data frame report the following:
mean:
The mean for that factor level.
n:
The effective sample size for that factor level.
k:
The k-factor for constructing the respective factor level's
tolerance interval.
1-sided.lower:
The 1-sided lower tolerance bound. This is given only if side = 1.
1-sided.upper:
The 1-sided upper tolerance bound. This is given only if side = 1.
2-sided.lower:
The 2-sided lower tolerance bound. This is given only if side = 2.
2-sided.upper:
The 2-sided upper tolerance bound. This is given only if side = 2.
References
----------
Derek S. Young (2010). tolerance: An R Package for Estimating Tolerance
Intervals. Journal of Statistical Software, 36(5), 1-39.
URL http://www.jstatsoft.org/v36/i05/.
Howe, W. G. (1969), Two-Sided Tolerance Limits for Normal Populations -
Some Improvements, Journal of the American Statistical Association,
64, 610–620.
Weissberg, A. and Beatty, G. (1969), Tables of Tolerance Limit Factors
for Normal Distributions, Technometrics, 2, 483–500.
Examples
--------
## 90%/95% 2-sided tolerance intervals for a 2-way ANOVA
## NOTE: Response must be the leftmost entry in dataframe and lm object
breaks = '26 30 54 25 70 52 51 26 67 18 21 29 17 12 18 35 30 36 36 21 24 18 10 43 28 15 26 27 14 29 19 29 31 41 20 44 42 26 19 16 39 28 21 39 29 20 21 24 17 13 15 15 16 28'.split(" ")
breaks = [float(a) for a in breaks]
wool = 'A A A A A A A A A A A A A A A A A A A A A A A A A A A B B B B B B B B B B B B B B B B B B B B B B B B B B B'.split(' ')
tension = 'L L L L L L L L L M M M M M M M M M H H H H H H H H H L L L L L L L L L M M M M M M M M M H H H H H H H H H'.split(' ')
warpbreaks = pd.DataFrame({'breaks':breaks,'wool':wool,
'tension':tension})
lmout = ols('breaks ~ wool + tension',warpbreaks).fit()
anovatolint(lmout, data = warpbreaks, alpha = 0.10, P = 0.95, side = 2
, method = "HE")
Note for When Using
response variable y must be the leftmost object in the dataframe, the
first entered creating an lm object, 2 steps
1.) df = pandas.DataFrame({'response':response, 'x1':x1, 'x2':x2,
...}))
2.) ols('response ~ x1 + x2 +...', data = df).fit()
data MUST be entered with response being first in lm and dataframe
(on the leftmost) it should only have a format with the y and x's
being in their place below ols(response ~ x1 + x2 + ..., data = df).fit()
'''
out = anova_lm(lmout)
dim1 = len(out.iloc[:,0])-1
s = np.sqrt(out.iloc[dim1][2])
df = list(int(k) for k in out.iloc[:,0])
xlev = levels(data,out)
resp = data.columns[0] #gets the response variable, y
#resp_ind = int(np.where(data.columns == resp)[0]) #should be 0
#pred_ind = np.where(data.columns != resp)[0]
factors = [a[0] for a in xlev]
outlist = []
bal = []
lev = list([np.array(a[1]).ravel() for a in xlev])
for i in range(len(factors)):
tempmeans = []
templens = []
tempmeans_without_level = []
templens_without_level = []
templow = []
tempup = []
K = []
for j in range(len(lev[i])):
tempmeans.append([lev[i][j], np.mean(data[data[factors[i]] == lev[i][j]][resp])])
templens.append([lev[i][j], length(data[data[factors[i]] == lev[i][j]][resp])])
K.append(Kfactor(n = templens[j][1],f = df[-1], alpha = alpha, P = P, side = side, method = method, m = m))
templow.append(tempmeans[j][1]-K[j]*s)
tempup.append(tempmeans[j][1]+K[j]*s)
tempmeans_without_level.append(np.mean(data[data[factors[i]] == lev[i][j]][resp]))
templens_without_level.append(length(data[data[factors[i]] == lev[i][j]][resp]))
tempmat = pd.DataFrame({'temp.means':tempmeans_without_level,'temp.eff':templens_without_level, 'K':K, 'temp.low':templow, 'temp.up':tempup})
tempmat.index = [lev[i]]
if side == 1:
tempmat.columns = ["mean", "n", "k", "1-sided.lower", "1-sided.upper"]
else:
tempmat.columns = ["mean", "n", "k", "2-sided.lower", "2-sided.upper"]
outlist.append(tempmat)
#print(tempmat)
t = np.array([templen[1] for templen in templens])
bal.append(np.where(sum(abs(t - np.mean(t))>3)))
bal = [to_int(x) for x in bal]
bal = sum(bal)
if bal > 0:
return "This procedure should only be used for balanced (or nearly-balanced) designs."
if side == 1:
print(f'These are {(1-alpha)*100}%/{P*100}% {side}-sided tolerance limits.')
else:
print(f'These are {(1-alpha)*100}%/{P*100}% {side}-sided tolerance intervals.')
for i in range(length(outlist)):
outlist[i] = outlist[i].sort_values(by=['mean'],ascending = False)
fin = [[i[0] for i in xlev], [a for a in outlist]]
return dict(zip(fin[0],fin[1]))
#for i in range(len(fin[1])):
# st += f'{fin[0][i]}\n{fin[1][i]}\n\n'
#return st
import sympy as sp
import inspect
def length(x):
if type(x) == float or type(x) == int or type(x) == np.int32 or type(x) == np.float64 or type(x) == np.float32 or type(x) == np.int64:
return 1
return len(x)
def nonlinregtolint(formula, xydata, xnew = None, side = 1, alpha = 0.05, P = 0.99, maxiter = 100):
'''
Nonlinear Regression Tolerance Bounds
Description
Provides 1-sided or 2-sided nonlinear regression tolerance bounds.
Usage
nlregtolint(formula, xydata, xnew = None, side = 1, alpha = 0.05, P = 0.99)
Parameters
----------
formula: function
A nonlinear model formula including variables and parameters.
xydata: dataframe
A data frame in which to evaluate the formulas in formula. The first
column of xydata must be the response variable.
xnew: list or float, optional
Any new levels of the predictor(s) for which to report the tolerance
bounds. The number of columns must be 1 less than the number of
columns for xydata.
side: 1 or 2, optional
Whether a 1-sided or 2-sided tolerance bound is required
(determined by side = 1 or side = 2, respectively).
alpha: float, optional
The level chosen such that 1-alpha is the confidence level.
P: float, optional
The proportion of the population to be covered by the tolerance
bound(s).
maxiter: int, optional
A positive integer specifying the maximum number of iterations that
the nonlinear least squares routine (curve_fit) should run.
Details
It is highly recommended that the user specify starting values for the
curve_fit routine.
Returns
-------
nlregtolint returns a data frame with items:
alpha
The specified significance level.
P
The proportion of the population covered by the tolerance bound(s).
yhat
The predicted value of the response for the fitted nonlinear
regression model.
y
The value of the response given in the first column of xydata.
This data frame is sorted by this value.
1-sided.lower
The 1-sided lower tolerance bound. This is given only if side = 1.
1-sided.upper
The 1-sided upper tolerance bound. This is given only if side = 1.
2-sided.lower
The 2-sided lower tolerance bound. This is given only if side = 2.
2-sided.upper
The 2-sided upper tolerance bound. This is given only if side = 2.
References
Derek S. Young (2010). tolerance: An R Package for Estimating Tolerance
Intervals. Journal of Statistical Software, 36(5), 1-39.
URL http://www.jstatsoft.org/v36/i05/.
Wallis, W. A. (1951), Tolerance Intervals for Linear Regression, in Second
Berkeley Symposium on Mathematical Statistics and Probability, ed. J.
Neyman, Berkeley: University of CA Press, 43–51.
Young, D. S. (2013), Regression Tolerance Intervals, Communications in
Statistics - Simulation and Computation, 42, 2040–2055.
Examples
## 95%/95% 2-sided nonlinear regression tolerance bounds for a sample of
size 50.
np.random.seed(1)
def formula1(x, b1, b2,b3):
try:
#make this the regular function using numpy
return b1 + (0.49-b1)*np.exp(-b2*(x-8)) + b3**b3
except:
#make this the symbolic version of the function using sympy
return b1 + (0.49-b1)*sp.exp(-b2*(x-8)) + b3**b3
x = pd.DataFrame(st.uniform.rvs(size=50, loc=5, scale=45))
y = formula1(x.iloc[:,0], 0.39, 0.11,0.01) + st.norm.rvs(size = length(x), scale = 0.01) #response
xy = pd.concat([y,x],axis=1)
xy.columns = ['y','x']
nonlinregtolint(formula1, xydata=xy,alpha = 0.05, P = 0.95, side = 2)
'''
n = length(xydata.iloc[:,0])
popt, pcov = opt.curve_fit(formula, xydata.iloc[:,1], xydata.iloc[:,0],maxfev=maxiter)
residuals = xydata.iloc[:,0] - formula(xydata.iloc[:,1],*popt)
ss_residuals = np.sum(residuals**2) #sum of squares residuals
ms_residuals = ss_residuals/(n-2) #mean squares residuals
try:
sigma = np.sqrt(ms_residuals) #residual standard error
except:
return "Error in scipy.optimize.curve_fit(). Consider different staring estimates of the parameters."
beta_hat = popt
beta_names = inspect.getfullargspec(formula)[0][1:]
x_name = inspect.getfullargspec(formula)[0][0]
temp = pd.DataFrame(popt).T
temp.columns = beta_names
pars = length(beta_hat)
bgroup = []
for i in range(pars):
temp = beta_names[i]
bgroup.append(sp.Symbol(f'{temp}'))
x = sp.Symbol(f'{x_name}')
formula_prime_wrtb = []
for i in range(pars):
formula_prime_wrtb.append((sp.diff(formula(x, *bgroup),bgroup[i])))
Pmat = [[]]*pars
keys = [*bgroup]
values = [*beta_hat]
k = dict(zip(keys,values))
for j in range(pars):
sub = []
for i in range(length(xydata.iloc[:,1])):
sub.append(formula_prime_wrtb[j].subs({f'{x_name}':xydata.iloc[:,1][i],**k}))
Pmat.append(sub)
Pmat = [x for x in Pmat if x]
Pmat = pd.DataFrame(Pmat).T
PTP = np.dot(Pmat.T,Pmat).astype('float64')
PTP2 = None
PTP0 = PTP
while PTP2 is None:
try:
PTP2 = np.linalg.inv(PTP)
except:
PTP3 = PTP0 + np.diag(np.linspace(min(np.diag(PTP))/1000,min(np.diag(PTP))/1000,length(np.diag(PTP))))
try:
PTPnew = np.linalg.inv(PTP3)
PTP0 = PTP3
PTP = PTPnew
except:
continue
else:
PTP = PTP2
if xnew is not None:
if length(xnew) == 1:
xnew = pd.DataFrame(np.array([xnew]))
else:
xnew = pd.DataFrame(np.array(xnew))
xtemp = pd.concat([pd.DataFrame([None,]*length(xnew)),xnew],axis=1)
xtemp.columns = xydata.columns
xydata = pd.concat([xydata,xtemp],axis = 0)
xydata.index = range(length(xydata.iloc[:,1]))
Pmat = [[]]*pars
for j in range(pars):
sub = []
for i in range(length(xydata.iloc[:,1])):
sub.append(formula_prime_wrtb[j].subs({f'{x_name}':xydata.iloc[:,1][i],**k}))
Pmat.append(sub)
Pmat = [x for x in Pmat if x]
Pmat = pd.DataFrame(Pmat).T
yhat = []
for i in range(length(xydata.iloc[:,1])):
yhat.append(formula(xydata.iloc[:,1][i],*beta_hat))
nstar = [None,]*length(xydata.iloc[:,1])
nrow = length(xydata.iloc[:,1])
for i in range(nrow):
nstar[i] = np.linalg.multi_dot([Pmat.iloc[i].T,PTP,Pmat.iloc[i].T.T])
nstar = np.array(nstar)
nstar = 1/nstar.astype('float64')
df = n - pars
if side == 1:
zp = st.norm.ppf(P)
delta = np.sqrt(nstar)*zp
tdelta = st.nct.ppf(1-alpha, n - pars, nc = delta)
tdelta[np.where(np.isnan(tdelta))] = np.inf
K = tdelta/np.sqrt(nstar)
K[np.where(np.isnan(K))] = np.inf
upper = yhat + sigma*K
lower = yhat - sigma*K
temp = pd.DataFrame({"alpha":alpha, "P":P, "yhat":yhat, "y":xydata.iloc[:,0], "1-sided.lower":lower, "1-sided.upper":upper})
else:
K = np.sqrt(df*st.ncx2.ppf(P,1,1/nstar)/st.chi2.ppf(alpha,df))
upper = yhat + sigma*K
lower = yhat - sigma*K
temp = pd.DataFrame({"alpha":alpha, "P":P, "yhat":yhat, "y":xydata.iloc[:,0], "2-sided.lower":lower, "2-sided.upper":upper})
temp = temp.sort_values(by=['y'])
temp.index = range(nrow)
return temp
def regtolint(reg, DataFrame, newx = None, side = 1, alpha = 0.05, P = 0.99):
'''
(Multiple) Linear Regression Tolerance Bounds
Description
Provides 1-sided or 2-sided (multiple) linear regression tolerance bounds.
It is also possible to fit a regression through the origin model.
Usage
regtolint(reg, newx = None, side = 1, alpha = 0.05, P = 0.99)
Parameters
----------
reg: linear model
An object of class
statsmodels.regression.linear_model.RegressionResultsWrapper
(i.e., the results from a linear regression routine).
DataFrame : DataFrame
The DataFrame that holds all data.
newx: DataFrame
An optional data frame in which to look for variables with which to
predict. If omitted, the fitted values are used.
side: 1 or 2
Whether a 1-sided or 2-sided tolerance bound is required (determined
by side = 1 or side = 2, respectively).
alpha: float
The level chosen such that 1-alpha is the confidence level.
P: float
The proportion of the population to be covered by the tolerance
bound(s).
Returns
-------
regtolint returns a data frame with items:
alpha:
The specified significance level.
P:
The proportion of the population covered by the tolerance bound(s).
y:
The value of the response given on the left-hand side of the model
in reg.
y.hat:
The predicted value of the response for the fitted linear
regression model. This data frame is sorted by this value.
1-sided.lower:
The 1-sided lower tolerance bound. This is given only if side = 1.
1-sided.upper:
The 1-sided upper tolerance bound. This is given only if side = 1.
2-sided.lower:
The 2-sided lower tolerance bound. This is given only if side = 2.
2-sided.upper:
The 2-sided upper tolerance bound. This is given only if side = 2.
References
----------
Derek S. Young (2010). tolerance: An R Package for Estimating Tolerance
Intervals. Journal of Statistical Software, 36(5), 1-39.
URL http://www.jstatsoft.org/v36/i05/.
Wallis, W. A. (1951), Tolerance Intervals for Linear Regression, in Second
Berkeley Symposium on Mathematical Statistics and Probability, ed. J.
Neyman, Berkeley: University of CA Press, 43–51.
Young, D. S. (2013), Regression Tolerance Intervals, Communications in
Statistics - Simulation and Computation, 42, 2040–2055.
Examples
--------
grain = pd.DataFrame([40, 17, 9, 15, 6, 12, 5, 9],columns = ['grain'])
straw = pd.DataFrame([53, 19, 10, 29, 13, 27, 19, 30], columns = ['straw'])
df = pd.concat([grain,straw],axis = 1)
newx = pd.DataFrame({'grain':[3,6,9]})
reg = ols('straw ~ grain',data=df).fit()
regtolint(reg, newx = newx,side=1)
'''
if side != 1 and side != 2:
return "Must specify a one-sided or two-sided procedure!"
try:
reg.params
except:
return "Input must be of class statsmodels.regression.linear_model.RegressionResultsWrapper"
else:
n = length(reg.resid)
pars = length(reg.params)
newlength = 0
#est = reg.predict() #mvreg[i].predict(newx)
e = reg.get_prediction().summary_frame()
est_fit = e.iloc[:,0]
est_sefit = e.iloc[:,1]
est1_fit,est1_sefit = None,None
if type(newx) == pd.core.frame.DataFrame:
newlength = length(newx)
e1 = reg.get_prediction(newx).summary_frame()
est1_fit = e1.iloc[:,0]
est1_sefit = e1.iloc[:,1]
yhat = np.hstack([est_fit,est1_fit])
sey = np.hstack([est_sefit, est1_sefit])
else:
yhat = est_fit
sey = est_sefit
y = np.hstack([DataFrame.iloc[:,1].values, np.array([None,]*newlength)])
a_out = anova_lm(reg)
MSE = a_out['mean_sq'][length(a_out['mean_sq'])-1]
deg_freedom = int(a_out['df'][length(a_out['df'])-1])
nstar = MSE/sey**2
if side == 1:
zp = st.norm.ppf(P)
delta = np.sqrt(nstar) * zp
tdelta = st.nct.ppf(1-alpha,df= int(n-pars),nc = delta)
K = tdelta/np.sqrt(nstar)
upper = yhat + np.sqrt(MSE)*K
lower = yhat - np.sqrt(MSE)*K
temp = pd.DataFrame({'alpha':alpha,'P':P,'y':y,'yhat':yhat,'1-sided.lower':lower,'1-sided.upper':upper})
else:
K = np.sqrt(deg_freedom*st.ncx2.ppf(P,1,1/nstar)/st.chi2.ppf(alpha,deg_freedom))
upper = yhat + np.sqrt(MSE)*K
lower = yhat - np.sqrt(MSE)*K
temp = pd.DataFrame({'alpha':alpha,'P':P,'y':y,'yhat':yhat,'2-sided.lower':lower,'2-sided.upper':upper})
temp = temp.sort_values(by=['yhat'])
temp.index = range(length(temp.iloc[:,0]))
return temp
def tricubic(x):
y = np.zeros_like(x)
idx = (x >= -1) & (x <= 1)
y[idx] = np.power(1.0 - np.power(np.abs(x[idx]), 3), 3)
return y
#nonparametric smoothing routine
#https://github.com/joaofig/pyloess
class Loess(object):
@staticmethod
def normalize_array(array):
min_val = np.min(array)
max_val = np.max(array)
return (array - min_val) / (max_val - min_val), min_val, max_val
def __init__(self, xx, yy, degree=1):
self.n_xx, self.min_xx, self.max_xx = self.normalize_array(xx)
self.n_yy, self.min_yy, self.max_yy = self.normalize_array(yy)
self.degree = degree
@staticmethod
def get_min_range(distances, window):
min_idx = np.argmin(distances)
n = len(distances)
if min_idx == 0:
return np.arange(0, window)
if min_idx == n-1:
return np.arange(n - window, n)
min_range = [min_idx]
while len(min_range) < window:
i0 = min_range[0]
i1 = min_range[-1]
if i0 == 0:
min_range.append(i1 + 1)
elif i1 == n-1:
min_range.insert(0, i0 - 1)
elif distances[i0-1] < distances[i1+1]:
min_range.insert(0, i0 - 1)
else:
min_range.append(i1 + 1)
return np.array(min_range)
@staticmethod
def get_weights(distances, min_range):
max_distance = np.max(distances[min_range])
weights = tricubic(distances[min_range] / max_distance)
return weights
def normalize_x(self, value):
return (value - self.min_xx) / (self.max_xx - self.min_xx)
def denormalize_y(self, value):
return value * (self.max_yy - self.min_yy) + self.min_yy
def estimate(self, x, window, use_matrix=False, degree=1):
n_x = self.normalize_x(x)
distances = np.abs(self.n_xx - n_x)
min_range = self.get_min_range(distances, window)
weights = self.get_weights(distances, min_range)
if use_matrix or degree > 1:
wm = np.multiply(np.eye(window), weights)
xm = np.ones((window, degree + 1))
xp = np.array([[math.pow(n_x, p)] for p in range(degree + 1)])
for i in range(1, degree + 1):
xm[:, i] = np.power(self.n_xx[min_range], i)
ym = self.n_yy[min_range]
xmt_wm = np.transpose(xm) @ wm
beta = np.linalg.pinv(xmt_wm @ xm) @ xmt_wm @ ym
y = (beta @ xp)[0]
else:
xx = self.n_xx[min_range]
yy = self.n_yy[min_range]
sum_weight = np.sum(weights)
sum_weight_x = np.dot(xx, weights)
sum_weight_y = np.dot(yy, weights)
sum_weight_x2 = np.dot(np.multiply(xx, xx), weights)
sum_weight_xy = np.dot(np.multiply(xx, yy), weights)
mean_x = sum_weight_x / sum_weight
mean_y = sum_weight_y / sum_weight
b = (sum_weight_xy - mean_x * mean_y * sum_weight) / \
(sum_weight_x2 - mean_x * mean_x * sum_weight)
a = mean_y - b * mean_x
y = a + b * n_x
return self.denormalize_y(y)
def f(n,alpha,P):
return alpha - (n * P**(n - 1) - (n - 1) * P**n)
def bisection(a,b,n,alpha,tol=1e-8):
xl = a
xr = b
while np.abs(xl-xr) >= tol:
c = (xl+xr)/2
prod = f(n=n,alpha=alpha,P=xl)*f(n=n,alpha=alpha,P=c)
if prod > tol:
xl = c
else:
if prod < tol:
xr = c
return c
def distfreeest2(n = None, alpha = None, P = None, side = 1):
temp = 0
if n == None:
temp += 1
if alpha == None:
temp +=1
if P == None:
temp += 1
if temp > 1:
return 'Must specify values for any two of n, alpha, and P'
if (side != 1 and side != 2):
return 'Must specify a 1-sided or 2-sided interval'
if side == 1:
if n == None:
ret = int(np.ceil(np.log(alpha)/np.log(P)))
if P == None:
ret = np.exp(np.log(alpha)/n)
ret = float(f'{ret:.4f}')
if alpha == None:
ret = 1-P**n
else:
if alpha == None:
ret = 1-(np.ceil((n*P**(n-1)-(n-1)*P**n)*10000))/10000
if n == None:
ret = int(np.ceil(opt.brentq(f,a=0,b=1e100,args=(alpha,P),maxiter=1000)))
if P == None:
ret = np.ceil(bisection(0,1,alpha =alpha, n = n, tol = 1e-8)*10000)/10000
return ret
def distfreeest(n = None, alpha = None, P = None, side = 1):
if n == None:
if type(alpha) == float:
alpha = [alpha]
if type(P) == float:
P = [P]
A = length(alpha)
B = length(P)
column_names = np.zeros(B)
row_names = np.zeros(A)
matrix = np.zeros((A,B))
for i in range(A):
row_names[i] = alpha[i]
for j in range(B):
column_names[j] = P[j]
matrix[i,j] = distfreeest2(alpha=alpha[i],P=P[j],side=side)
out = pd.DataFrame(matrix,columns = column_names, index = row_names)
if alpha == None:
if type(n) == float or type(n) == int:
n = [n]
if type(P) == float:
P = [P]
A = length(n)
B = length(P)
column_names = np.zeros(B)
row_names = np.zeros(A)
matrix = np.zeros((A,B))
for i in range(A):
row_names[i] = n[i]
for j in range(B):
column_names[j] = P[j]
matrix[i,j] = distfreeest2(n=n[i],P=P[j],side=side)