-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathRHtests.R
9916 lines (9445 loc) · 335 KB
/
RHtests.R
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
#**** Copyright agreement ****
# All users of any code in this package agree to the terms and conditions described in the
#file Copyright_RHtests__RClimDex_SoftwarePackages.pdf, which is also included in this package.
#*****************************
# last updated at 2019-03-01
# in QMadjGaussian.wRef(), change osmean estimation from the way QMadjGaussian to just take the
# mean value of adjusted segments, since there has extra adjustments for the difference b/w
# QMadj and mean-adj
# last updated at 2018-03-01
# in QMadjGaussian.wRef(), added check sample size during EBa calculation, and reduce Mq once
# sample size too small detected (the same consequence as EBb estimation)
# last updated at 2016-12-28
# set all QMadj output as missing once Mq==1
# last updated at 2016-10-05
# changed FindU.wRef(), FindUD.wRef(), StepSize.wRef(), switched LSmultipleRed to LSmultiRedCycle
# for trend estimation on original and mean-adjusted series
# last updated at 2014-02-03
# 1) Fixed Read.wRef(), changed merge() parameter sort=F to sort=T for itable.nmb, otherwise,
# non-match date for Bseries will be at the end of itable.nmb
# 2) Changed all pdf(), added paper='letter'
# 3) Changed OnQMadjGaussian.wRef(), make output filename correctly involved reference file name.
# last updated on 2013-06-28
# Changed all as.real() to as.numeric(), since R 2.15 no longer support as.real()
# last updated on 2013-04-03
# Changed Mq upper limit in StartGUI(), QMadjGaussian(), QMadjGaussian.wRef(), from 20 to 100,
# changed button locations on main manu.
# last updated on 2013-04-03
# Changed plots for QMadjust distribution
# last updated on 2013-03-19
# Added function QMadjGaussian.wRef(), changed FindU.wRef(), FindUD.wRef(),
# StepSize.wRef(), replaced QMadjGaussian() with QMadjGaussian.wRef().
# Modified Read.wRef(), append ref series to bdata matrix.
# Added a button 'QMadj.wRef' at StartGUI(), corresponding subroutine: QMadj.GaussianDLY.wRef
# last updated on 2012-09-25
# fixed a bug at StepSize() and StepSize.wRef() regarding to fitted value for Feb. 29th
# last updated on 2012-04-26
# at FindU() FindUD() StepSize() FindU.wRef() FindUD.wRef() and
# StepSize.wRef(), add fitted value for Feb. 29th to fitted
# value data files.
# last updated on 2011-12-11
# Change output format for *Ustat.txt in *.wRef(), from "PMF" -> "PMT"
# Change QMadj.GuassianDLY() and ReadDLY.g(), add vector olflg which indicate
# non-missing data only, but contains Feb 29th data.
# last updated on 2010-06-08
# In FindU(), FindUD(), StepSize() and 3 corresponding .wRef() functions,
# added a text indication "Yes ", "YifD", "No " or "? " in changepoint list
# output file, also changed corresponding read-in part.
# last updated on 2010-10-29
# add a sample format for 1Cs when there has no changepoint
# last updated on 2010-05-06
# in QMadjGaussian(), add Nadj option, set empirical prob. segment as length
# Nadj instead of whole segment.
#
# Bug fixed at 2010-02-08
# In FindU.wRef(), FindUD.wRef(), if 0 changepoint found, set meanhatD with
# fitted value, but not 0. Output *_U.dat or *_UD.dat affected.
# NT=1, 12, and 365 for annual, monthly, and daily series, respectively
# p.lev is the nominal level of confidence; (1 - p.lev) is the nominal level
# of significance
# choose one of the following 6 p.lev values: 0.75, 0.80, 0.90, 0.95, 0.99,
# 0.9999
# Mq (=0, 1, 2, ..., 20) is the number of points (categories) on which
# the empirical cumulative distribution function are estimated.
# If Mq=0, the actual Mq is determined by the length of the shortest segment
# Mq=1 corresponds to mean adjustments (one adjustment for all data in
# the same segment)
# In the output: Ns >= 0 is the number of changepoints identified;
# changepoint positions are Ip(1), Ip(2),...,Ip(Ns)
# If Iadj = 0, the data series is adjusted to the longest segment;
# otherwise the data series is adjusted to the chosen segment Iadj (if the
# given integer Iadj > Ns+1, we re-set Iadj=Ns+1, which corresponds to
# adjusting the series to the last segment). Set Iadj = 10000 if you want
# to ensure that the series is adjusted to the last segment
FindU<-function(InSeries,output,MissingValueCode,GUI=FALSE,p.lev=0.95,
Iadj=10000,Mq=10,Ny4a=0){
ErrorMSG<-NA
assign("ErrorMSG",ErrorMSG,envir=.GlobalEnv)
Nmin<-10
if(Ny4a>0&Ny4a<=5) Ny4a<-5
if(!p.lev%in%c(0.75,0.8,0.9,0.95,0.99,0.9999)){
ErrorMSG<<-paste("FindU: input p.lev",p.lev,"error\n",
get("ErrorMSG",env=.GlobalEnv),"\n")
if(!GUI) cat(ErrorMSG)
return(-1)
}
plev<-p.lev
pkth<-match(p.lev,c(0.75,0.8,0.9,0.95,0.99,0.9999))
assign("Nmin",Nmin,envir=.GlobalEnv)
itmp<-Read(InSeries,MissingValueCode)
if(itmp==(-1)){
ErrorMSG<<-paste("FindU: Error in read data from",InSeries,"\n",
get("ErrorMSG",env=.GlobalEnv),"\n")
if(!GUI) cat(ErrorMSG)
return(-1)
}
ofileAout<-paste(output,"_U.dat",sep="")
ofilePdf<-paste(output,"_U.pdf",sep="")
ofileSout<-paste(output,"_Ustat.txt",sep="")
file.create(ofileAout)
file.create(ofilePdf)
file.create(ofileSout)
N<-length(Y0); Nadj<-Ny4a*Nt
cat(paste("The nominal level of confidence (1-alpha)=",plev,"\n"),file=ofileSout)
cat(paste("Input data filename:", InSeries, "N=",N, "\n"),file=ofileSout,append=T)
readPFtable(N,pkth)
Pk0<-Pk.PMFT(N)
oout<-rmCycle(itable)
Y1<-oout$Base
EB<-oout$EB
assign("EB",EB,envir=.GlobalEnv)
if(length(EB)!=length(Icy)) {
ErrorMSG<<-paste("Annual cycle length (from non-missing data) differ from original dataset",
"\n",get("ErrorMSG",env=.GlobalEnv),"\n")
if(GUI==F) print(ErrorMSG)
return(-1)
}
Ip0<-N
otmp<-LSmultiRedCycle(Y1,Ti,Ip0,1)
beta0<-otmp$trend
meanhat0<-otmp$meanhat
Ehat0<-mean(meanhat0)
cat(file=ofileSout,paste(" Ignore changepoints -> trend0 =",
round(beta0,6),"(",round(otmp$betaL,6),",",round(otmp$betaU,6),")",
"(p=",round(otmp$p.tr,4),"); cor=",
round(otmp$cor,4),"(", round(otmp$corl,4),",",
round(otmp$corh,4),")\n"),append=T)
oout<-PMFT(Y1,Ti,Pk0)
I0<-0
I2<-oout$KPx
I4<-N
oout1<-PMFxKxI0I2(Y1,Ti,I0,I2)
I1<-oout1$Ic
oout2<-PMFxKxI0I2(Y1,Ti,I2,I4)
I3<-oout2$Ic
oout3<-PMFxKxI0I2(Y1,Ti,I1,I3)
I2<-oout3$Ic
Ns<-1
Ips<-c(I1,N)
if(I1>0){
otmp<-LSmultiple(Y1,Ti,Ips)
resi<-otmp$resi
fitted<-otmp$fitted
otmp<-Rphi(resi,Ips,Ns)
cor1<-otmp$cor
corL1<-otmp$corl
corU1<-otmp$corh
W<-otmp$W+fitted
otmp<-PMFxKc(Y1,Ti,I0,I4,I1)
PFx1<-otmp$PFc
otmp<-PMFxKc(W,Ti,I0,I4,I1)
prob1<-otmp$prob
}
else{
prob1<-0
PFx1<-0
cor1<-0
corL1<-0
}
Ips<-c(I2,N)
if(I2>0){
otmp<-LSmultiple(Y1,Ti,Ips)
resi<-otmp$resi
fitted<-otmp$fitted
otmp<-Rphi(resi,Ips,Ns)
cor2<-otmp$cor
corL2<-otmp$corl
corU2<-otmp$corh
W<-otmp$W+fitted
otmp<-PMFxKc(Y1,Ti,I0,I4,I2)
PFx2<-otmp$PFc
otmp<-PMFxKc(W,Ti,I0,I4,I2)
prob2<-otmp$prob
}
else{
prob2<-0
PFx2<-0
cor2<-0
corL2<-0
}
Ips<-c(I3,N)
if(I3>0){
otmp<-LSmultiple(Y1,Ti,Ips)
resi<-otmp$resi
fitted<-otmp$fitted
otmp<-Rphi(resi,Ips,Ns)
cor3<-otmp$cor
corL3<-otmp$corl
corU3<-otmp$corh
W<-otmp$W+fitted
otmp<-PMFxKc(Y1,Ti,I0,I4,I3)
PFx3<-otmp$PFc
otmp<-PMFxKc(W,Ti,I0,I4,I3)
prob3<-otmp$prob
}
else{
prob3<-0
PFx3<-0
cor3<-0
corL3<-0
}
ofileIout<-paste(output,"_1Cs.txt",sep="")
ofileMout<-paste(output,"_mCs.txt",sep="")
file.create(ofileIout)
tmp<-sort(c(PFx1,PFx2,PFx3),decreasing=T,index.return=T)
PFx.mx<-tmp$x[1]
prob.mx<-c(prob1,prob2,prob3)[tmp$ix[1]]
Imx<-c(I1,I2,I3)[tmp$ix[1]]
cor.mx<-c(corL1,corL2,corL3)[tmp$ix[1]]
PFx95L<-getPFx95(cor.mx,N)
if(PFx.mx<PFx95L){
Ns<-0
Ips<-N
cat(paste(Ns,"changepoints in Series", InSeries,
paste("sample:(",sprintf("%1.0f",1)," ",sprintf("%-4.4s","YifD"),
sprintf("%10.0f",19000101),")",sep=""),"\n"),file=ofileIout)
cat("PMF finds no Type-1 changepoints in the series!\n")
# return(0)
}
else{
Ns<-1
Ips<-c(Imx,N)
# if(Debug) cat(file=flog,c("First Ips:",Ips,"\n"))
tt<-TRUE
Niter<-0
while(tt){ # condition on is there any more Bps to insert in Ips?
Niter<-Niter+1
tt<-FALSE
Ips0<-NULL
for(i in 1:(Ns+1)){ # search for new break points
I0<- if(i==1) 0 else Ips[i-1]
I2<-Ips[i]
otmp<-PMFxKxI0I2(Y1,Ti,I0,I2)
if(otmp$prob>0) Ips0<-sort(c(Ips0,otmp$Ic))
}
# if(Debug) {
# cat(file=flog,paste("Niter",Niter,"new Ips:",length(Ips0),"\n"),append=T)
# cat(file=flog,c(Ips0,"\n"),append=T)
# cat(file=flog,paste("Niter",Niter,"old Ns",Ns," "),append=T)
# }
# finished search for possible new changepoints, start estimate the p-value
# of the Ips0 series and find the most significant changepoint Iseg.mx
tt1<-TRUE
while(tt1){
PFx.mx<-(-9999)
Iseg.mx<-0
PFx95L.mx<-0
if(length(Ips0)==0) tt1<-FALSE
else{
for(i in 1:length(Ips0)){
Ips1<-sort(c(Ips,Ips0[i]))
ith<-match(Ips0[i],Ips1)
otmp<-PMFxIseg(Y1,Ti,Ips1,ith)
if(otmp$PFx<otmp$PFx95L) Ips0[i]<-0
else
if(otmp$PFx>PFx.mx){
PFx.mx<-otmp$PFx
Iseg.mx<-Ips0[i]
PFx95L.mx<-otmp$PFx95L
}
}
if(PFx.mx>=PFx95L.mx){
Ips<-sort(c(Ips,Iseg.mx))
Ns<-Ns+1
Ips0<-Ips0[Ips0!=Iseg.mx]
tt<-TRUE
}
else tt1<-FALSE
Ips0<-Ips0[Ips0!=0]
}
}
# if(Debug) cat(file=flog,paste("new Ns:", Ns,"\n"),append=T)
}
# finish finding any possible new changepoints
# start to delete the least significant changepoint if it is insignificant
tt<-TRUE
while(tt){
tt<-FALSE
Iseg.mn<-0
PFx.mn<-99999
PFx95L.mn<-99999
for(i in 1:Ns){
otmp<-PMFxIseg(Y1,Ti,Ips,i)
if(otmp$PFx<PFx.mn){
Iseg.mn<-i
PFx.mn<-otmp$PFx
PFx95L.mn<-otmp$PFx95L
}
}
if(Iseg.mn>0&PFx.mn<PFx95L.mn){
Ips<-Ips[-Iseg.mn]
Ns<-Ns-1
if(Ns>0) tt<-TRUE
}
}
}
# end of detection
if(Ns>0) {
Nsegs<-Ips-c(0,Ips[1:Ns])
Iseg.longest<-sort(Nsegs,index=T,decreasing=T)$ix[1]
}
else Iseg.longest<-0
if(Iadj>(Ns+1)|Iseg.longest==0) Iseg.adj<-Ns+1
else if(Iadj==0)Iseg.adj<-Iseg.longest
else Iseg.adj<-Iadj
oout<-LSmultiRedCycle(Y1,Ti,Ips,Iseg.adj)
Y1<-oout$Y0
cor<-oout$cor
corl<-oout$corl
corh<-oout$corh
df<-(N-2-Nt-Ns)
pcor<-pt(abs(cor)*sqrt(df/(1-cor^2)),df)
W<-oout$W
WL<-oout$WL
WU<-oout$WU
EB1<-oout$EB
itmp1<-cbind(EB1,Icy)
itmp2<-cbind(1:N,Imd)
colnames(itmp2)<-c("idx","Icy")
itmp<-merge(itmp1,itmp2,by="Icy")
EBfull<-itmp[order(itmp[,"idx"]),"EB1"]
EEB<-mean(EB1,na.rm=T)
if(Ns>0){
Rb<-Y1-oout$trend*Ti+EBfull
QMout<-QMadjGaussian(Rb,Ips,Mq,Iseg.adj,Nadj)
B<-QMout$PA
cat(paste("Nseg_shortest =",QMout$Nseg.mn,"; Mq = ",QMout$Mq,"; Ny4a = ",Ny4a,"\n"),
file=ofileSout,append=T)
cat(paste("\n Adjust to segment", Iseg.adj,": from",
if(Iseg.adj==1) 1 else Ips[Iseg.adj-1]+1,
"to",Ips[Iseg.adj],"\n"),file=ofileSout,append=T)
# cat("#Fcat, DP (CDF and Differnces in category mean)\n",file=ofileSout,
# append=T)
if(Mq>1){
oline<-paste('#Fcat: frequency category boundaries\n',
'#DP: Difference in the category means\n#',sep='')
for(i in 1:Ns) oline<-paste(oline,paste('Fcat.Seg',i,sep=''),paste('DP.Seg',i,sep=''))
oline<-paste(oline,'\n')
cat(oline,file=ofileSout,append=T)
write.table(round(QMout$osmean,4),file=ofileSout,append=T,
row.names=F,col.names=F)
for(i in 1:(Ns+1)){
I1<-if(i==1) 1 else Ips[i-1]+1
I2<-Ips[i]
if(i!=Iseg.adj)
cat(paste("Seg. ",i,": mean of QM-adjustments =",round(mean(QMout$W[I1:I2]),4),
"\n",sep=""),file=ofileSout,append=T)
}
}
}
else B<-Y1-oout$trend*Ti+EBfull
# itmp1<-cbind(EB1,Icy)
# itmp2<-cbind(1:N,Imd)
# colnames(itmp2)<-c("idx","Icy")
# itmp<-merge(itmp1,itmp2,by="Icy")
# EBfull<-itmp[order(itmp[,"idx"]),"EB1"]
# EEB<-mean(EB1,na.rm=T)
adj<-oout$Y0+EBfull
# B<-B+EBfull+oout$trend*Ti
B<-B+oout$trend*Ti
cat("Common trend TPR fit to the de-seasonalized Base series:\n",
file=ofileSout,append=T)
cat(paste("#steps= ",Ns,"; trend=",round(oout$trend,6),"(",
round(oout$betaL,6),",",round(oout$betaU,6),") (p=",
round(oout$p.tr,4),"); cor=",
round(cor,4),"(",round(corl,4),",",round(corh,4),")",
round(pcor,4),"\n"),
file=ofileSout,append=T)
if(Ns>0) for(i in 1:(Ns+1)){
I1<-if(i==1) 1 else Ips[i-1]+1
I2<-Ips[i]
Delta<-oout$mu[Iseg.adj]-oout$mu[i]
adj[I1:I2]<-adj[I1:I2]+Delta
stepsize<-oout$mu[i+1]-oout$mu[i]
cat(paste(Ips[i],IY0[Ips[i]],"stepsize=",round(stepsize,4),"\n"),
file=ofileSout,append=T)
}
oR<-Y1-oout$meanhat
oR[2:N]<-oR[2:N]-oR[1:(N-1)]*cor
Ehat<-mean(oout$meanhat)
meanhat0<-meanhat0-Ehat0+Ehat
pdf(file=ofilePdf,onefile=T,paper='letter')
op <- par(no.readonly = TRUE) # the whole list of settable par's.
par(mfrow=c(2,1))
par(mar=c(3,4,3,2)+.1,cex.main=.8,cex.lab=.8,cex.axis=.8,cex=.8)
uyrs<-unique(floor(ori.itable[,1]/10))*10
labels<-NULL
ats<-NULL
for(i in 1:length(uyrs)){
if(!is.na(match(uyrs[i],ori.itable[,1]))){
labels<-c(labels,uyrs[i])
ats<-c(ats,match(uyrs[i],ori.itable[,1]))
}
}
pdata<-rep(NA,dim(ori.itable)[1])
pdata[ooflg]<-oout$Y0
plot(1:dim(ori.itable)[1],pdata,type="l",xlab="",ylab="",
ylim=c(min(oout$Y0,oout$meanhat),max(oout$Y0,oout$meanhat)),
xaxt="n",col="black",lwd=0.5,
main="Base anomaly series and regression fit")
axis(side=1,at=ats,labels=labels)
pdata[ooflg]<-oout$meanhat
lines(1:dim(ori.itable)[1],pdata,col="red")
pdata[ooflg]<-oout$Y0+EBfull
plot(1:dim(ori.itable)[1],pdata,type="l",xlab="",ylab="",
ylim=c(min(oout$Y0+EBfull,oout$meanhat+EEB),
max(oout$Y0+EBfull,oout$meanhat+EEB)),
xaxt="n",col="black",lwd=0.5,
main="Base series and regression fit")
axis(side=1,at=ats,labels=labels)
pdata[ooflg]<-oout$meanhat+EEB
lines(1:dim(ori.itable)[1],pdata,col="red")
pdata[ooflg]<-adj
plot(1:dim(ori.itable)[1],pdata,type="l",xlab="",ylab="",
ylim=c(min(c(adj,B)),max(c(adj,B))),
xaxt="n",col="black",lwd=0.5,
main="Mean-adjusted base series")
axis(side=1,at=ats,labels=labels)
if(Mq>1){
pdata[ooflg]<-B
plot(1:dim(ori.itable)[1],pdata,type="l",xlab="",ylab="",
ylim=c(min(c(adj,B)),max(c(adj,B))),
xaxt="n",col="black",lwd=0.5,
main="QM-adjusted base series")
axis(side=1,at=ats,labels=labels)
}
# test plot
if(Ns>0&Mq>1){
par(mar=c(4,5,3,2)+.1,cex=.8,mfrow=c(2,2),mgp=c(1.2,.5,0))
col=0
np<-0
osp<-QMout$osp
osmean<-QMout$osmean
for(i in 1:(Ns+1)){
Fd<-.5/QMout$Mq
I1<-if(i==1) 1 else Ips[i-1]+1
I2<-Ips[i]
ymax<-max(osp[,2:3],na.rm=T); ymin<-min(osp[,2:3],na.rm=T)
if(i!=Iseg.adj){
np<-np+1
if(col==0) {
col<-2
plot(osp[I1:I2,2],osp[I1:I2,3],xlim=c(0,1),ylim=c(ymin,ymax),
type="l",lwd=1,col=col,xlab="Cumulative Frequency",
ylab="QM Adjustment")
title(cex.main=0.9,main=paste("distribution of QM adjustments with Mq=",QMout$Mq),line=.5)
icol<-2*np
for(j in 1:QMout$Mq){
lines(c(osmean[(j+1),icol]-Fd,osmean[(j+1),icol]+Fd),
c(rep(osmean[(j+1),(icol+1)],2)),col=col,lty=2,lwd=.5)
if(j>=1&j<QMout$Mq) lines(rep(osmean[(j+1),icol]+Fd,2),
c(osmean[(j+1),(icol+1)],osmean[(j+2),(icol+1)]),col=col,lty=2,lwd=0.5)
}
}
else{
col<-col+1
lines(osp[I1:I2,2],osp[I1:I2,3],lwd=1,col=col)
icol<-2*np
for(j in 1:QMout$Mq){
lines(c(osmean[(j+1),icol]-Fd,osmean[(j+1),icol]+Fd),
c(rep(osmean[(j+1),(icol+1)],2)),col=col,lty=2,lwd=.5)
if(j>=1&j<QMout$Mq) lines(rep(osmean[(j+1),icol]+Fd,2),
c(osmean[(j+1),(icol+1)],osmean[(j+2),(icol+1)]),col=col,lty=2,lwd=0.5)
}
}
text(.15,ymax-np*(ymax-ymin)/(Ns*3),paste("Seg.",i))
lines(c(.25,.30),rep(ymax-np*(ymax-ymin)/(Ns*3),2),lwd=2,col=col)
}
else np<-np+1
}
}
par(op)
dev.off()
odata<-matrix(NA,dim(ori.itable)[1],10)
# odata[ooflg,1]<-Ti
odata[,1]<-c(1:dim(ori.itable)[1])
odata[,2]<-ori.itable[,1]*10000+ori.itable[,2]*100+ori.itable[,3]
# odata[ooflg,3]<-round(oout$Y0+EBfull,4)
odata[,3]<-ori.itable[,4]
odata[ooflg,4]<-round(oout$meanhat+EEB,4)
odata[ooflg,5]<-round(adj,4)
odata[ooflg,6]<-round(oout$Y0,4)
odata[ooflg,7]<-round(oout$meanhat,4)
odata[ooflg,8]<-round(oout$meanhat+EBfull,4)
if(Ns>0) if(QMout$Mq>1) odata[ooflg,9]<-round(B,4)
odata[ooflg,10]<-round(meanhat0,4)
Imd1<-ori.itable[,2]*100+ori.itable[,3]
if(sum(is.na(ori.itable[,4])==F&Imd1==229)>0){
if(Ns>0){
tdata<-ori.itable[is.na(ori.itable[,4])==F,]
IY1<-tdata[,1]*10000+tdata[,2]*100+tdata[,3]
Ips.ymd<-IY0[Ips]
Ips.1<-rep(NA,Ns+1)
for(i in 1:Ns) Ips.1[i]<-c(1:length(IY1))[IY1==Ips.ymd[i]]
Ips.1[Ns+1]<-length(IY1)
# Ips.1<-c(1:length(IY1))[Ips.ymd==IY1]
Imd2<-tdata[,2]*100+tdata[,3]
Ids.leap<-c(1:length(Imd2))[Imd2==229]
Nl<-length(Ids.leap)
Rb<-Y1-oout$trend*Ti+EBfull
Rb1<-tdata[,4]; Rb1[-Ids.leap]<-Rb
Ti1<-rep(NA,length(IY1)); Ti1[-Ids.leap]<-Ti
for(i in 1:length(Ids.leap)) {
Rb1[Ids.leap[i]]<-tdata[Ids.leap[i],4]+Rb1[Ids.leap[i]-1]-tdata[Ids.leap[i]-1,4]
Ti1[Ids.leap[i]]<-Ti1[Ids.leap[i]-1]
}
if(QMout$Mq>1){
B1<-QMadjGaussian(Rb1,Ips.1,Mq,Iseg.adj,Nadj)$PA
B1<-B1+oout$trend*Ti1
B1.leap<-B1[Ids.leap]
odata[is.na(odata[,3])==F&Imd1==229,9]<-round(B1.leap,4)
}
}
else
odata[Imd1==229,9]<-odata[Imd1==229,3]
Ids.leapo<-c(1:dim(ori.itable)[1])[is.na(ori.itable[,4])==F&Imd1==229]
for(jth in 1:length(Ids.leapo)){
kth<-Ids.leapo[jth]
if(Ns>0){
k1th<-if(odata[kth-1,2]%in%IY0[Ips]) (kth+1) else (kth-1)
}
else k1th<-kth-1
for(pth in c(4,7,8,10)) odata[kth,pth]<-odata[k1th,pth]
for(pth in c(5,6)){delta1<-odata[k1th,3]-odata[k1th,pth]; odata[kth,pth]<-odata[kth,3]-delta1}
}
}
write.table(file=ofileAout,odata,na=MissingValueCode,
col.names=F,row.names=F)
otmp<-LSmultiple(Y1,Ti,Ips)
resi<-otmp$resi
otmpW<-LSmultiple(W,Ti,Ips)
resiW<-otmpW$resi
otmpWL<-LSmultiple(WL,Ti,Ips)
resiWL<-otmpWL$resi
otmpWU<-LSmultiple(WU,Ti,Ips)
resiWU<-otmpWU$resi
if(Ns==0) {
cat(paste(Ns,"changepoints in Series", InSeries,
paste("sample:(",sprintf("%1.0f",1)," ",sprintf("%-4.4s","YifD"),
sprintf("%10.0f",19000101),")",sep=""),"\n"),file=ofileIout)
cat("PMF finds no Type-1 changepoints in the series!\n")
# return(0)
}
else{
cat(paste(Ns,"changepoints in Series", InSeries,"\n"),
file=ofileIout)
for(i in 1:Ns){
I1<- if(i==1) 1 else Ips[i-1]+1
Ic<-Ips[i]
I3<-Ips[i+1]
Nseg<-I3-I1+1
PFx95<-getPFx95(cor,Nseg)
PFx95l<-getPFx95(corl,Nseg)
PFx95h<-getPFx95(corh,Nseg)
SSEf.Iseg<-sum(resi[I1:I3]^2)
Ips1<-Ips[-i]
otmp1<-LSmultiple(Y1,Ti,Ips1)
SSE0.Iseg<-sum(otmp1$resi[I1:I3]^2)
Fx<-(SSE0.Iseg-SSEf.Iseg)*(Nseg-3)/SSEf.Iseg
Pk1<-Pk.PMFT(Nseg)
PFx<-Fx*Pk1[Ic-I1+1]
SSEf.Iseg<-sum(resiW[I1:I3]^2)
otmp1<-LSmultiple(W,Ti,Ips1)
SSE0.Iseg<-sum(otmp1$resi[I1:I3]^2)
Fx<-(SSE0.Iseg-SSEf.Iseg)*(Nseg-3)/SSEf.Iseg
if(Fx>0) prob<-pf(Fx,1,Nseg-3)
else{
Fx<-0
prob<-0
PFx<-0
}
SSEf.Iseg<-sum(resiWL[I1:I3]^2)
otmp1<-LSmultiple(WL,Ti,Ips1)
SSE0.Iseg<-sum(otmp1$resi[I1:I3]^2)
FxL<-(SSE0.Iseg-SSEf.Iseg)*(Nseg-3)/SSEf.Iseg
if(FxL>0) probL<-pf(Fx,1,Nseg-3)
else probL<-0
SSEf.Iseg<-sum(resiWU[I1:I3]^2)
otmp1<-LSmultiple(WU,Ti,Ips1)
SSE0.Iseg<-sum(otmp1$resi[I1:I3]^2)
FxU<-(SSE0.Iseg-SSEf.Iseg)*(Nseg-3)/SSEf.Iseg
if(FxU>0) probU<-pf(Fx,1,Nseg-3)
else probU<-0
# else if(Id==1) { # type-1 changepoints
if(PFx<PFx95l) Idc<-"No "
else if(PFx>=PFx95l&PFx<PFx95h) Idc<-"? "
else if(PFx>=PFx95h) Idc<-"Yes "
# }
cat(paste(sprintf("%1.0f",1)," ",
sprintf("%-4.4s",Idc),
sprintf("%10.0f", IY0[Ic])," (",
sprintf("%6.4f",probL),"-",
sprintf("%6.4f",probU),")",
sprintf("%6.3f",plev),
sprintf("%10.4f",PFx)," (",
sprintf("%10.4f",PFx95l),"-",
sprintf("%10.4f",PFx95h),")\n",sep=""),
file=ofileIout,
append=TRUE)
cat(paste("PMF : c=", sprintf("%4.0f",Ic),
"; (Time ", sprintf("%10.0f",IY0[Ic]),
"); Type= 1; p=",sprintf("%10.4f",prob),"(",
sprintf("%6.4f",probL),"-",
sprintf("%6.4f",probU),")",
"; PFmax=", sprintf("%10.4f",PFx),
"; CV95=", sprintf("%10.4f",PFx95),
"(", sprintf("%10.4f",PFx95l),
"-", sprintf("%10.4f",PFx95h),
"); Nseg=", sprintf("%4.0f",Nseg),"\n",sep=""),
file=ofileSout, append=T)
}
}
if(GUI)
return(0)
else{
file.copy(from=ofileIout,to=ofileMout,overwrite=TRUE)
cat("FindU finished successfully...\n")
}
}
FindUD<-function(InSeries,InCs,output,MissingValueCode,GUI=FALSE,p.lev=0.95,
Iadj=10000,Mq=10,Ny4a=0){
Debug<-TRUE
ErrorMSG<-NA
assign("ErrorMSG",ErrorMSG,envir=.GlobalEnv)
flog<-paste(output,".log",sep="")
Nmin<-10
if(Ny4a>0&Ny4a<=5) Ny4a<-5
if(!p.lev%in%c(0.75,0.8,0.9,0.95,0.99,0.9999)){
ErrorMSG<<-paste("FindU: input p.lev",p.lev,"error\n",
get("ErrorMSG",env=.GlobalEnv),"\n")
if(!GUI) cat(ErrorMSG)
return(-1)
}
plev<-p.lev
pkth<-match(p.lev,c(0.75,0.8,0.9,0.95,0.99,0.9999))
assign("Nmin",Nmin,envir=.GlobalEnv)
itmp<-Read(InSeries,MissingValueCode)
if(itmp<0){
ErrorMSG<<-paste("FindUD: Error in read data from",InSeries,"\n",
get("ErrorMSG",env=.GlobalEnv),"\n")
if(!GUI) cat(ErrorMSG)
return(-1)
}
N<-length(Y0); Nadj<-Ny4a*Nt
readPFtable(N,pkth)
itmp<-readLines(InCs)
Pk0<-Pk.PMFT(N)
oout<-rmCycle(itable)
Y1<-oout$Base
EB<-oout$EB
assign("EB",EB,envir=.GlobalEnv)
if(length(EB)!=length(Icy)) {
ErrorMSG<<-paste("Annual cycle length (from non-missing data) differ from original dataset",
"\n",get("ErrorMSG",env=.GlobalEnv),"\n")
if(!GUI) cat(ErrorMSG)
return(-1)
}
ofileIout<-paste(output,"_pCs.txt",sep="")
ofileMout<-paste(output,"_mCs.txt",sep="")
file.create(ofileIout)
ofileAout<-paste(output,"_UD.dat",sep="")
ofilePdf<-paste(output,"_UD.pdf",sep="")
ofileSout<-paste(output,"_UDstat.txt",sep="")
file.create(ofileAout)
file.create(ofilePdf)
file.create(ofileSout)
cat(paste("The nominal level of confidence (1-alpha)=",plev,"\n"),file=ofileSout)
cat(paste("Input data filename:", InSeries,"N=",N,"\n"),file=ofileSout,append=T)
Ip0<-N
oout<-LSmultiRedCycle(Y1,Ti,Ip0,1)
beta0<-oout$trend
betaL0<-oout$betaL
betaU0<-oout$betaU
meanhat0<-oout$meanhat
Ehat0<-mean(meanhat0)
p.tr0<-oout$p.tr
corD<-oout$cor
corDL<-oout$corl
corDU<-oout$corh
if(length(itmp)<2){ # no input changepoints
oout<-PMFT(Y1,Ti,Pk0)
I0<-0
I2<-oout$KPx
I4<-N
oout1<-PMFxKxI0I2(Y1,Ti,I0,I2)
I1<-oout1$Ic
oout2<-PMFxKxI0I2(Y1,Ti,I2,I4)
I3<-oout2$Ic
oout3<-PMFxKxI0I2(Y1,Ti,I1,I3)
I2<-oout3$Ic
Ns<-1
Ips<-c(I1,N)
if(I1>0){
otmp<-LSmultiple(Y1,Ti,Ips)
resi<-otmp$resi
fitted<-otmp$fitted
otmp<-Rphi(resi,Ips,Ns)
cor1<-otmp$cor
corL1<-otmp$corl
corU1<-otmp$corh
W<-otmp$W+fitted
otmp<-PMFxKc(Y1,Ti,I0,I4,I1)
PFx1<-otmp$PFc
otmp<-PMFxKc(W,Ti,I0,I4,I1)
prob1<-otmp$prob
}
else{
prob1<-0
PFx1<-0
}
Ips<-c(I2,N)
if(I2>0){
otmp<-LSmultiple(Y1,Ti,Ips)
resi<-otmp$resi
fitted<-otmp$fitted
otmp<-Rphi(resi,Ips,Ns)
cor2<-otmp$cor
corL2<-otmp$corl
corU2<-otmp$corh
W<-otmp$W+fitted
otmp<-PMFxKc(Y1,Ti,I0,I4,I2)
PFx2<-otmp$PFc
otmp<-PMFxKc(W,Ti,I0,I4,I2)
prob2<-otmp$prob
}
else{
prob2<-0
PFx2<-0
}
Ips<-c(I3,N)
if(I3>0){
otmp<-LSmultiple(Y1,Ti,Ips)
resi<-otmp$resi
fitted<-otmp$fitted
otmp<-Rphi(resi,Ips,Ns)
cor3<-otmp$cor
corL3<-otmp$corl
corU3<-otmp$corh
W<-otmp$W+fitted
otmp<-PMFxKc(Y1,Ti,I0,I4,I3)
PFx3<-otmp$PFc
otmp<-PMFxKc(W,Ti,I0,I4,I3)
prob3<-otmp$prob
}
else{
prob3<-0
PFx3<-0
}
tmp<-sort(c(PFx1,PFx2,PFx3),decreasing=T,index.return=T)
PFx.mx<-tmp$x[1]
prob.mx<-c(prob1,prob2,prob3)[tmp$ix[1]]
Imx<-c(I1,I2,I3)[tmp$ix[1]]
if(prob.mx<plev){
# cat("PMF finds the series to be homogeneous!\n",file=ofileIout)
cat(paste(0,"changepoints in Series", InSeries,"\n"),file=ofileIout)
cat("PMF finds the series to be homogeneous!\n")
# return()
Ns<-0
Ips<-N
Ids<-c(0)
}
else{
Ns<-1
Ips<-c(Imx,N)
Ids<-c(0,1)
}
}
else{
Ns<-length(itmp)-1
Ips<-c(rep(0,Ns),N)
Ids<-rep(0,Ns)
for(i in 1:Ns){ # using YYYYMMDD as index, searching for the largest
# date less or equal to given YYYYMMDD
ymdtmp<-as.numeric(substr(itmp[i+1],7,16))
it<-match(ymdtmp,IY0)
if(!is.na(it)) Ips[i]<-it
else Ips[i]<-max(c(1:N)[IY0<=ymdtmp])
Ids[i]<-as.numeric(substr(itmp[i+1],1,1))
}
if(sum(is.na(Ips))>0|!identical(Ips,sort(Ips))){
ErrorMSG<<-paste("FindUD: Ips read in from ",InCs,"error:")
for(i in 1:Ns)
ErrorMSG<<-paste(get("ErrorMSG",env=.GlobalEnv),Ips[i])
ErrorMSG<<-paste(get("ErrorMSG",env=.GlobalEnv),"\n")
if(!GUI) cat(ErrorMSG)
return(-1)
}
}
if(Ns>0){
Ips.i<-Ips
Niter<-0
# start search for all possible changepoints
tt<-TRUE
while(tt){
Niter<-Niter+1
tt<-FALSE
Ips0<-NULL
for(i in 1:(Ns+1)){
I0<- if(i==1) 0 else Ips[i-1]
I2<-Ips[i]
otmp<-PMFxKxI0I2(Y1,Ti,I0,I2)
if(otmp$prob>0) Ips0<-sort(c(Ips0,otmp$Ic))
}
# estimate p-value of each changepoint in series Ips0, find the most significant
# changepoint Iseg.mx
tt1<-TRUE
while(tt1){
if(length(Ips0)==0) tt1<-FALSE
else{
Iseg.mx<-0
prob.mx<-(-1)
probL.mx<-(-1)
PFx.mx<-(-1)
for(i in 1:length(Ips0)){
Ips1<-sort(c(Ips,Ips0[i]))
ith<-match(Ips0[i],Ips1)
otmp<-PMFxIseg(Y1,Ti,Ips1,ith)
probL<-min(c(otmp$probL,otmp$probU,otmp$prob))
probU<-max(c(otmp$probL,otmp$probU,otmp$prob))
PFx<-otmp$PFx
if(probU<plev) Ips0[i]<-0
else
if(PFx>PFx.mx){
prob.mx<-otmp$prob
probL.mx<-probL
Iseg.mx<-Ips0[i]
PFx.mx<-PFx
}
}
if(probL.mx>=plev){
Ips<-sort(c(Ips,Iseg.mx))
Ns<-Ns+1
Ips0<-Ips0[Ips0!=Iseg.mx]
tt<-TRUE
}
else tt1<-FALSE
Ips0<-Ips0[Ips0!=0]
}
}
}
Ids0<-rep(NA,length(Ips))
for(i in 1:length(Ips)){
if(Ips[i]%in%Ips.i) Ids0[i]<-Ids[Ips.i==Ips[i]]
else Ids0[i]<-0
}
Ids<-Ids0
# Ids<-as.integer(Ips%in%Ips.i)
tt<-TRUE
while(tt){
tt<-FALSE
probL.mn<-9999
Iseg.mn<-0
for(i in 1:Ns){
if(Ids[i]==0){ # check those un-documented
Ips0<-Ips[-i]
otmp<-PMFxIseg(Y1,Ti,Ips,i)
probL<-min(otmp$probL,otmp$probU)
if(probL<probL.mn){
Iseg.mn<-i
probL.mn<-probL
}
} # end if documented
}
if(Iseg.mn>0&probL.mn<plev){
Ips<-Ips[-Iseg.mn]
Ids<-Ids[-Iseg.mn]
Ns<-Ns-1
if(Ns>0) tt<-TRUE
}
}
}
# all changepoints are significant, calculate stats and output
if(Ns>0) {
Nsegs<-Ips-c(0,Ips[1:Ns])
Iseg.longest<-sort(Nsegs,index=T,decreasing=T)$ix[1]
}
else Iseg.longest<-0
if(Iadj>(Ns+1)|Iseg.longest==0) Iseg.adj<-Ns+1
else if(Iadj==0)Iseg.adj<-Iseg.longest
else Iseg.adj<-Iadj
otmp<-LSmultiRedCycle(Y1,Ti,Ips,Iseg.adj)
Y1<-otmp$Y0
cor<-otmp$cor
corl<-otmp$corl
corh<-otmp$corh
df<-(N-2-Nt-Ns)
pcor<-pt(abs(cor)*sqrt(df/(1-cor^2)),df)
Rf<-otmp$resi
W<-otmp$W
WL<-otmp$WL
WU<-otmp$WU
EB1<-otmp$EB
itmp1<-cbind(EB1,Icy)
itmp2<-cbind(1:N,Imd)
colnames(itmp2)<-c("idx","Icy")
itmp<-merge(itmp1,itmp2,by="Icy")
EBfull<-itmp[order(itmp[,"idx"]),"EB1"]
EEB<-mean(EB1,na.rm=T)
if(Ns>0){
Rb<-Y1-otmp$trend*Ti+EBfull
QMout<-QMadjGaussian(Rb,Ips,Mq,Iseg.adj,Nadj)
B<-QMout$PA
cat(paste("Nseg_shortest =",QMout$Nseg.mn,"; Mq = ",QMout$Mq,"; Ny4a = ",Ny4a,"\n"),
file=ofileSout,append=T)
cat(paste("\n Adjust to segment", Iseg.adj,": from",
if(Iseg.adj==1) 1 else Ips[Iseg.adj-1]+1,
"to",Ips[Iseg.adj],"\n"),file=ofileSout,append=T)
# cat("#Fcat, DP (CDF and Differnces in category mean)\n",file=ofileSout,
# append=T)
if(QMout$Mq>1){
oline<-paste('#Fcat: frequency category boundaries\n',
'#DP: Difference in the category means\n#',sep='')
for(i in 1:Ns) oline<-paste(oline,paste('Fcat.Seg',i,sep=''),paste('DP.Seg',i,sep=''))
oline<-paste(oline,'\n')
cat(oline,file=ofileSout,append=T)
write.table(round(QMout$osmean,4),file=ofileSout,append=T,
row.names=F,col.names=F)
for(i in 1:(Ns+1)){
I1<-if(i==1) 1 else Ips[i-1]+1
I2<-Ips[i]
if(i!=Iseg.adj)
cat(paste("Seg. ",i,": mean of QM-adjustments =",round(mean(QMout$W[I1:I2]),4),
"\n",sep=""),file=ofileSout,append=T)
}
}
}
else B<-Y1-otmp$trend*Ti+EBfull
adj<-otmp$Y0+EBfull
# B<-B+EBfull+otmp$trend*Ti
B<-B+otmp$trend*Ti
cat(file=ofileSout,paste(" Ignore changepoints -> trend0 =",
round(beta0,6),"(",round(betaL0,6),",",round(betaU0,6),") (p=",
round(p.tr0,4),"); cor=", round(corD,4),"(",round(corDL,4),