-
Notifications
You must be signed in to change notification settings - Fork 0
/
Clear_sky_id_Reno-Hansen_apply_v13.1.R
executable file
·1255 lines (964 loc) · 44.9 KB
/
Clear_sky_id_Reno-Hansen_apply_v13.1.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
# /* !/usr/bin/env Rscript */
# /* Copyright (C) 2022 Athanasios Natsis <natsisphysicist@gmail.com> */
#' ---
#' title: "*Identification of Periods of Clear Sky Irradiance in
#' Time Series of GHI Measurements* Matthew J. Reno and Clifford W. Hansen."
#' author: "Natsis Athanasios"
#' institute: "AUTH"
#' affiliation: "Laboratory of Atmospheric Physics"
#' date: "`r format(Sys.time(), '%F')`"
#' abstract: "Construction of and examples of clear sky models"
#'
#' documentclass: article
#' classoption: a4paper,oneside
#' fontsize: 10pt
#' geometry: "left=0.5in,right=0.5in,top=0.5in,bottom=0.5in"
#'
#' link-citations: yes
#' colorlinks: yes
#'
#' header-includes:
#' - \usepackage{caption}
#' - \usepackage{placeins}
#' - \captionsetup{font=small}
#' - \usepackage{multicol}
#' - \setlength{\columnsep}{1cm}
#'
#' output:
#' bookdown::pdf_document2:
#' number_sections: no
#' fig_caption: no
#' keep_tex: no
#' toc_depth: 4
#' latex_engine: xelatex
#' toc: yes
#' fig_width: 7
#' fig_height: 4.5
#' html_document:
#' toc: true
#' fig_width: 7.5
#' fig_height: 5
#' ---
#'
#+ include=FALSE, echo=FALSE
####_ Document options _####
#+ echo=F, include=F
knitr::opts_chunk$set(comment = "" )
# knitr::opts_chunk$set(dev = "pdf" )
knitr::opts_chunk$set(dev = "png" )
knitr::opts_chunk$set(out.width = "100%" )
knitr::opts_chunk$set(fig.align = "center" )
# knitr::opts_chunk$set(fig.pos = '!h' )
####_ Notes _####
#
# Use the optimized alpha for the selected models and identify Clear-Sky
# minutes.
#
#### Set environment ####
Sys.setenv(TZ = "UTC")
tic <- Sys.time()
Script.Name <- "Clear_sky_id_Reno-Hansen_apply_v13.1.R"
if (!interactive()) {
pdf( file = paste0("~/CS_id/REPORTS/RUNTIME/", basename(sub("\\.R$",".pdf", Script.Name))))
sink(file = paste0("~/CS_id/REPORTS/RUNTIME/", basename(sub("\\.R$",".out", Script.Name))), split = TRUE)
}
options("width" = 130)
library(RAerosols)
library(RColorBrewer)
library(scales)
library(pander)
library(caTools)
library(data.table)
source("~/CODE/R_myRtools/myRtools/R/trigonometric.R")
## some plot configs ####
def.par <- par(no.readonly = TRUE) # save default, for resetting...
kcols <- brewer.pal(11, "Set3")
#### data walk function ####
walk <- function(i, nt_hw, tot_p) {
if (i <= nt_hw) {
w_sta <<- 1
w_end <<- i + nt_hw
} else if ( i >= tot_p - nt_hw ) {
w_sta <<- i - nt_hw
w_end <<- tot_p
} else {
w_sta <<- i - nt_hw
w_end <<- i + nt_hw
}
}
## Use monthly optimization of models
# MONTHLY <- T
MONTHLY <- FALSE
# TEST <- TRUE
TEST <- FALSE
SAMPLE_DAYS <- 1000 ## The total number of days to sample from data
# START_DAY <- "2022-01-01"
START_DAY <- "1993-01-01"
## load previous state have to override it for alpha to be used
if (MONTHLY) {
load("~/Aerosols/DATA/model_opt/Combinations_results_m_2019-12-12_082356.Rds")
} else {
load("~/Aerosols/DATA/model_opt/Combinations_results_2022-06-14_153313.Rds")
}
## Define the model to use for CS detection be inspecting the results of the 'a' optimization script.
model_selection <- "HAU"
monthly_alphas <- gather_results[gather_results$CS_models == model_selection,]
## daily plots
plotsbase <- paste0("~/Aerosols/DATA/Graphs/Level_2/CS_id/CS_detection_Reno-Hansen_",model_selection,"_")
par(mar = c(2,4,2,1))
#+ include=T, echo=F
source("/home/athan/Aerosols/source_R/THEORY/Extraterrestrial_radiation_models.R")
source("/home/athan/Aerosols/source_R/THEORY/Air_mass_models.R")
source("/home/athan/Aerosols/source_R/THEORY/Clear_sky_irradiance_models.R")
source("/home/athan/Aerosols/source_R/THEORY/Linke_turbidity_models.R")
#'
#'
#' \newpage
#'
#' ## DETECTION OF CLEAR PERIODS IN GHI MEASUREMENTS ##
#'
#+ include=T, echo=FALSE
#### Load data from QCRad procedure ########################################
## The "strict" input files were used before
strict_files <- list.files(path = "/home/athan/DATA/Broad_Band/",
pattern = "LAP_QCRad_CM21_CHP1_[0-9]{4}.Rds",
full.names = T ,
recursive = F)
strict_files <- sort(strict_files)
## build one data.frame
strict <- data.table()
for (in_f in strict_files) {
stctemp <- data.table(readRDS(in_f))
##TODO we have setup filters with the assumption of good.
## have to check the logic of other filters
allow <- c( "good", "Possible Direct Obstruction (23)")
stctemp <- stctemp[ QCF_DIR %in% allow | QCF_GLB %in% allow ]
strict <- rbind(strict, stctemp)
rm(stctemp)
}
## fill the names of dataframes
## FIXME some duplicates rows exist in the database!!!
strong <- unique(strict)
rm(strict)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# --- Limit date span of the data ----------------------------------------------
cat(paste("Use data after date:", START_DAY), "\n\n")
strong[, Day := as.Date(Date)]
strong <- strong[ strong$Day >= as.Date(START_DAY), ]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
## days to parse
dayslist <- unique( strong$Day )
## add id column
strong$CSflag <- 99
inverted <- strong$wattGLB < strong$wattHOR
#'
#' ### Data set input.
#'
#' First day: `r min(dayslist)`
#'
#' Last day: `r max(dayslist)`
#'
#' Days available: `r length(dayslist)`
#'
#### Exclude inversions ####
#' ### There are instances where global irradiance is less than direct. ###
#' This happens for `r sum(inverted, na.rm = T)`
#' minutes (records), near sunset and sunrise due to obstacles.
#' We will exclude all this data both for global and direct.
#'
#+ include=T, echo=FALSE
strong$wattGLB[ inverted] <- NA
strong$wattGLB_sds[ inverted] <- NA
strong$wattHOR[ inverted] <- NA
strong$wattHOR_sds[ inverted] <- NA
## set id flag for missing data
# strong$CSflag[ is.na(strong$wattGLB) ] <- 10
#####################################################################
#### Model status ####
MeanVIP_active <- F
MaxVIP_active <- F
VIL_active <- F
VCT_active <- F
VSM_active <- F
LDI_active <- F
LGI_active <- F
FCS_active <- F
FDP_active <- F
FAST_SKIP <- F
## Reno-Hansen filters
MeanVIP_active <- T
MaxVIP_active <- T
VIL_active <- T
VCT_active <- T
VSM_active <- T
## My filters
LDI_active <- T ## Low __Direct__ Irradiance limit (LDI)
## careful this also excludes points due to pole shade at
## afternoon and building in the morning
LGI_active <- T ## Low Global Irradiance limit (LGI)
## Global irradiance below this level can not be identified
FCS_active <- T ## Skip with few cs
FDP_active <- T ## Skip with few data in a day
FAST_SKIP <- F ## allow faster skip of filters also reduce data kept
# -- all the variables for this run are initialized here --------------------- #
MS <- data.frame( nt = 11, ## Window size prefer odd numbers so not to be left right bias
MeanVIP_fct = 1, ## 1. Factor Mean Value of Irradiance during the time Period (MeanVIP)
CS_ref_rm_VIP_low = 70, ## 1. MIN Offset Mean Value of Irradiance during the time Period (MeanVIP)
CS_ref_rm_VIP_upp = 80, ## 1. MAX Offset Mean Value of Irradiance during the time Period (MeanVIP)
MaxVIP_fct = 1 , ## 2. Factor Max Value of Irradiance during the time Period (MaxVIP)
MaxVIP_off_upp = 70, ## 2. MAX Offset Max Value of Irradiance during the time Period (MaxVIP)
MaxVIP_off_low = 75, ## 2. MIN Offset Max Value of Irradiance during the time Period (MaxVIP)
MaxVIL_fct = 1.2, ## 3. MAX Factor Variability in irradiance by the length (VIL)
MinVIL_fct = 1, ## 3. MIN Factor Variability in irradiance by the length (VIL)
offVIL_upl = 10, ## 3. MAX Offset Variability in irradiance by the length (VIL)
offVIL_dwl = 5, ## 3. MIN Offset Variability in irradiance by the length (VIL)
offVCT = 0.00011, ## 4. Variance of Changes in the Time series (VCT)
offVSM = 7.5, ## 5. Variability in the Shape of the irradiance Measurements (VSM)
alpha = 1,
relative_CS = 0.3, ## limit of CS day acceptance 0.3: 30% of the data points have to be id as clear within a day
sample_n_days = SAMPLE_DAYS, ## Sample of that much days to be evaluated
tolerance = 0.02, ## Optimization algorithm tolerance
start_day = START_DAY, ## The first day of the data we are using
DIR_s_T_fact = 25 ## percentage of direct under simple threshold CS_ref_DIR (TESTING)
)
CS_flags <- c( "MeanVIP", #1
"MaxVIP", #2
"VIL", #3
"VCT", #4
"VSM", #5
"LDI", #6
"LGI", #7
"FCS", #8
"FDP", #9
"NA", #10
"DsT", #11
NULL
)
#'
#' ### Threshold Values for Criteria
#'
#' For mean and max Most evaluations of clear sky models find that the average
#' bias error of the model is less than 10%, often around 7% [1, 83]. Therefore,
#' a fixed threshold of $\pm 75 W / m^2$ within the mean and max of the clear sky model
#' was chosen.
#'
# alpha_models <- data.frame(
# DPP = c( 0.9 , 1.25 , 1.054567 ),
# KC = c( 1 , 1.25 , 1.15983 ),
# HAU = c( 0.8 , 1.20 , 0.9858765 ),
# BD = c( 0.95 , 1.25 , 1.073723 ),
# ABCG = c( 0.95 , 1.30 , 1.102558 ),
# RS = c( 0.90 , 1.25 , 1.00482 ),
# KASTEN = c( 0.95 , 1.25 , 1.12107 ),
# INEICHEN = c( 0.85 , 1.25 , 1.155573 ),
# row.names = c("lower","upper","best") )
## select diffuse model
CS_models_list <- c(
"DPP",
"KC",
"HAU",
# "BD", ## too poor results
"ABCG",
"RS",
"KASTEN",
"INEICHEN"
)
#'
#' ### Clear Sky detection Algorithm values
#'
#'
#+ include=T, echo=F
# panderOptions('table.emphasize.rownames', F)
panderOptions('table.alignment.default', "right")
panderOptions('table.alignment.rownames', "right")
panderOptions('table.split.cells', c(50,10))
pander(t(MS))
pander(alpha_models)
pander(combinations)
#'
#+ include=T, echo=F
#### Model selection ####
#'
#' ### Reference clear sky irradiance model and air mass model (AM)
#'
#' We select the clear sky model, the air mass calculation
#' and the period of `r MS$nt`
#' minutes to use.
#'
AM <- AM_simple
CS_model <- get(model_selection)
# alpha = alpha_models["best",model_selection]
#+ include=T, echo=F
#### 6. LDI ###
MS$LDIlim <- 5
#'
#' ### 6. Low Direct Irradiance limit (LDI)
#'
#' Ignore Direct irradiance when it is bellow `r MS$LDIlim` $Watt/m^2$.
#' This limit is biased due to the slight location difference of the two Instruments.
#' The difference in shadow especially the afternoon "pole shadow" of some periods of the year.
#' May limit the implementation by time of day or/and period of the year
#'
#' Also this can not characterize all global measurements due to gaps on direct measurements.
#'
#+ include=T, echo=F
#### 7. LGI ####
MS$VGIlim <- 5
#'
#' ### 7. Low Global Irradiance limit (LGI)
#'
#' Global irradiance below `r MS$VGIlim` level can not be identified
#'
#+ include=T, echo=F
#### 8. FCS ####
FCSlim <- MS$nt
#'
#' ### 8. Too Few CS point for the day (FCS)
#'
#'
#' If in a day there less than `r FCSlim` clear sky points will exclude them from optimizing
#'
#+ include=T, echo=F
#### 9. FDP ####
FDPlim <- MS$nt * 3
#'
#' ### 9. Too Few data points for the day (FDP)
#'
#'
#' If in a day there are less than `r FDPlim` data points will be excluded from optimizing.
#'
#+ include=T, echo=F
#### 11. DsT ####
#'
#' ### 11. Too low Direct signal (DsT)
#'
#' This is a simple hard limit on the lower possible Direct radiation with clear sky.
#'
#' The threshold is `r MS$DIR_s_T_fact`% lower than a reference value.
#'
#' $$ I_d = I_0 * 0.7^{{AM}^{0.678}} * cos({ZSA}) $$
#'
#' Where ${AM}$ is the selected air-mass model.
#'
#' "Clear sky direct normal irradiance estimation based on adjustable inputs and error correction_Zhu2019.pdf"
#'
#+ include=T, echo=F
## create a list of days to use
if (TEST) {
if ( length(dayslist) < MS$sample_n_days) { MS$sample_n_days = length(dayslist) }
# dayslist <- sample(dayslist, MS$sample_n_days )
# dayslist = dayslist[1:10]
# dayslist = tail(dayslist, n = 20)
# dayslist <- dayslist[year(dayslist)>=2019]
# dayslist <- dayslist[year(dayslist)>=2019 & month(dayslist) == 7]
dayslist <- dayslist
}
dayslist <- sort( dayslist, decreasing = T )
#'
#' ### Day range
#'
range(dayslist)
#'
#+ include=T, echo=F
#'
#' ### Baseline value for direct irradiance
#'
#' See: Clear sky direct normal irradiance estimation based on adjustable inputs and error correction_Zhu2019.pdf
strong[ , CS_ref_HOR := ( TSIextEARTH_comb * 0.7 ^ AM(SZA) ^ 0.678 ) * cosde(SZA) ]
#+ include=T, echo=F
daily_stats <- data.frame()
#+ include=T, echo=F
## Iterate all years
for (ay in unique(year(dayslist))) {
gather <- data.table()
subdayslist <- dayslist[year(dayslist)==ay]
total_points <- sum(year(strong$Date)==ay)
pdf(file = paste0(plotsbase,ay,".pdf"), onefile = T, width = 10 )
## Iterate all days
for (aa in subdayslist) {
## Day variables
aday <- as.Date(aa , origin = "1970-01-01")
sell <- strong$Day == (aday)
doy <- as.numeric(format(aday, "%j"))
mont <- as.numeric(format(aday, "%m"))
nt_hw <- MS$nt %/% 2
if (interactive()) cat(paste(aday),"\n")
if (MONTHLY) {
## get alpha for month
alpha <- monthly_alphas$alpha[monthly_alphas$month == mont]
} else {
## get unique alpha for all days
alpha <- gather_results[gather_results$CS_models == model_selection, "alpha"]
stopifnot( length(alpha) == 1 )
stopifnot( typeof(alpha) == "double" )
}
## empty daily variables
MeanVIPcnt <- NA
MaxVIPcnt <- NA
VILcnt <- NA
VCTcnt <- NA
VSMcnt <- NA
## relative clear sky acceptance limit
relative_CS_lim <- sum(sell) * MS$relative_CS
## Data selection for day
subday <- strong[ sell, ]
have_glb <- !is.na(subday$wattGLB)
have_dir <- !is.na(subday$wattDIR)
tot_p <- length(subday$wattGLB)
## Values from Clear sky model used
## this model is used as clear sky reference
CS_ref <- CS_model(subday$SZA) * alpha
## Values from Air Mass model used
AM_ref <- AM(subday$SZA)
## create a more logical model
CS_ref_safe <- CS_ref
CS_ref_safe[ CS_ref_safe < 0 ] <- NA
## Create some empty columns
CS_ref_length <- CS_ref * NA
GLB_length <- CS_ref * NA
GLB_sigma <- CS_ref * NA
GLB_Xi <- CS_ref * NA
#### Apply filters ####
#---- 9. Too Few data point for the day (FDP) --------------------------
if (FDP_active) {
Flag_key <- 9
if (nrow(subday) > 0 & tot_p <= FDPlim ) {
subday$CSflag <- Flag_key
subday[[paste0("CSflag_",Flag_key)]] <- TRUE
cat(paste("Skip day FDP:",aday,tot_p),"\n")
next
}
}
#---- 1. Mean value of irradiance during the time period ---------------
if (MeanVIP_active & any(have_glb)) {
Flag_key <- 1
## create some modeled values
CS_ref_rm_base <- runmean(x = CS_ref_safe, k = MS$nt, alg = "C")
CS_ref_rm_VIP_low <- MS$MeanVIP_fct * CS_ref_rm_base - MS$CS_ref_rm_VIP_low
CS_ref_rm_VIP_upp <- MS$MeanVIP_fct * CS_ref_rm_base + MS$CS_ref_rm_VIP_upp
GLB_rm <- runmean(x = subday$wattGLB, k = MS$nt, alg = "C")
## TEST feature
## don't allow negative values on models
CS_ref_rm_base[ CS_ref_rm_base < 0 ] <- NA
CS_ref_rm_VIP_low[ CS_ref_rm_VIP_low < 0 ] <- NA
CS_ref_rm_VIP_upp[ CS_ref_rm_VIP_upp < 0 ] <- NA
GLB_rm[ GLB_rm < 0 ] <- NA
## do characterization if pass as clear
# MeanVIP_pass = GLB_rm > CS_ref_rm_VIP_low ## apply only lower limit (default)
MeanVIP_pass <- GLB_rm > CS_ref_rm_VIP_low & GLB_rm < CS_ref_rm_VIP_upp ## apply only lower and upper limit
indx_todo <- which( have_glb & MeanVIP_pass )
if (length(indx_todo) > 0) {
for (i in indx_todo) {
walk(i, nt_hw , tot_p )
subday$CSflag[w_sta:w_end][ ! subday$CSflag[w_sta:w_end] == 0 ] <- 0
}
}
## set MeanVIP flag
subday[[paste0("CSflag_", Flag_key)]][ subday$CSflag == 99 ] <- TRUE
subday$CSflag[subday$CSflag == 99] <- Flag_key
}
#---- 2. Max value of irradiance during the time period ----------------
if (MaxVIP_active & any(have_glb)) {
Flag_key <- 2
CS_ref_rmax_base <- runmax(x = CS_ref_safe, k = MS$nt, alg = "C")
CS_ref_rmax_VIP_upp <- MS$MaxVIP_fct * CS_ref_rmax_base + MS$MaxVIP_off_upp
CS_ref_rmax_VIP_low <- MS$MaxVIP_fct * CS_ref_rmax_base - MS$MaxVIP_off_low
GLB_rmax <- runmax(x = subday$wattGLB, k = MS$nt, alg = "C")
## TEST feature
CS_ref_rmax_base[ CS_ref_rmax_base < 0 ] <- NA
CS_ref_rmax_VIP_upp[ CS_ref_rmax_VIP_upp < 0 ] <- NA
CS_ref_rmax_VIP_low[ CS_ref_rmax_VIP_low < 0 ] <- NA
GLB_rmax[ GLB_rmax < 0 ] <- NA
## pass as clear
# MaxVIP_pass = GLB_rmax < CS_ref_rmax_VIP_upp ## apply only upper filter (default)
MaxVIP_pass <- GLB_rmax < CS_ref_rmax_VIP_upp & GLB_rmax > CS_ref_rmax_VIP_low ## apply upper and lower filter
indx_todo <- which( have_glb & MaxVIP_pass )
if ( length(indx_todo) > 0 ) {
## start with old clear as 99
subday$CSflag[subday$CSflag == 0] <- 99
for (i in indx_todo ) {
walk(i, nt_hw , tot_p )
subday$CSflag[w_sta:w_end][ (!subday$CSflag[w_sta:w_end] == 0 ) &
( subday$CSflag[w_sta:w_end] == 99) ] <- 0
} ##END for loop all time periods
}
## set MaxVIP flag
subday[[paste0("CSflag_", Flag_key)]][ subday$CSflag == 99 ] <- TRUE
subday$CSflag[subday$CSflag == 99] <- Flag_key
}
#---- 3. Variability in irradiance by the length (VIL) ----------------
if (VIL_active) {
Flag_key <- 3
indx_todo <- which( have_glb )
if ( length(indx_todo) > 0 ) {
## start with old clear as 99
subday$CSflag[subday$CSflag == 0] <- 99
for (i in 1:tot_p) {
## resolve window by index
walk(i, nt_hw , tot_p )
## Do calculation ##
data_win_glb <- subday$wattGLB[w_sta:w_end]
# date_win_ref = CS_ref[w_sta:w_end]
date_win_ref <- CS_ref_safe[w_sta:w_end]
# print(c(length(data_win_glb),w_sta,i,w_end))
## calculate length for data
DeltaVSq_GLB <- (data.table::shift(data_win_glb) - data_win_glb)**2
DeltaTSq_GLB <- as.numeric( !is.na(DeltaVSq_GLB) )**2
GLB_length[i] <- sum(sqrt(DeltaVSq_GLB + DeltaTSq_GLB), na.rm = T )
## calculate length for reference
DeltaVSq_ref <- (data.table::shift(date_win_ref) - date_win_ref)**2
DeltaTSq_ref <- as.numeric( !is.na(DeltaVSq_ref) )**2
CS_ref_length[i] <- sum(sqrt(DeltaVSq_ref + DeltaTSq_ref), na.rm = T )
## pass test as clear
pass <- GLB_length[i] < (MS$MaxVIL_fct * CS_ref_length[i] + MS$offVIL_upl) &
GLB_length[i] > (MS$MinVIL_fct * CS_ref_length[i] - MS$offVIL_dwl)
if (is.na(pass)) pass <- FALSE
## set VIL flag
subday$CSflag[w_sta:w_end][ (!subday$CSflag[w_sta:w_end] == 0) &
( subday$CSflag[w_sta:w_end] == 99) &
pass ] <- 0
} ##END for loop all points
}
#### if it is not clear is VIL
subday[[paste0("CSflag_", Flag_key)]][ subday$CSflag == 99 ] <- TRUE
subday$CSflag[subday$CSflag == 99] <- Flag_key
}
#---- 4. Variance of Changes in the Time series (VCT) -----------------
if (VCT_active) {
Flag_key <- 4
indx_todo <- which( have_glb )
if ( length(indx_todo) > 0 ) {
## start with old clear as 99
subday$CSflag[subday$CSflag == 0] <- 99
s_i <- data.table::shift(subday$wattGLB) - subday$wattGLB ## /(t_i+i - t_i)
for (i in indx_todo) {
## resolve window by index
walk(i, nt_hw , tot_p )
## Do calculation ##
data_win_glb <- subday$wattGLB[w_sta:w_end]
DeltaVSq_GLB <- (data.table::shift(data_win_glb) - data_win_glb) ## /(t_i+i - t_i)
s_bar <- sum(DeltaVSq_GLB, na.rm = T) / ( MS$nt - 1 )
GLB_sigma[i] <- sqrt( sum( (s_i[w_sta:w_end] - s_bar)**2 , na.rm = T ) / ( MS$nt - 1 ) ) /
sum( data_win_glb , na.rm = T) / MS$nt
## pass test as clear
pass <- GLB_sigma[i] < MS$offVCT
if (is.na(pass)) pass <- F
## set VCT flag
subday$CSflag[w_sta:w_end][ ( ! subday$CSflag[w_sta:w_end] == 0) &
( subday$CSflag[w_sta:w_end] == 99) &
pass ] <- 0
} ##END for loop all points
}
#### if it is not clear is VCT
subday[[paste0("CSflag_", Flag_key)]][ subday$CSflag == 99 ] <- TRUE
subday$CSflag[subday$CSflag == 99] <- Flag_key
}
#---- 5. Variability in the Shape of the irradiance Measurements (VSM) ----
if (VSM_active) {
Flag_key <- 5
indx_todo <- which( have_glb )
if ( length(indx_todo) > 0 ) {
## start with old clear as 99
subday$CSflag[subday$CSflag == 0] <- 99
x_i_CS <- data.table::shift(CS_ref) - CS_ref
for (i in indx_todo) {
## resolve window by index
walk(i, nt_hw , tot_p )
## Do calculation ##
data_win_glb <- subday$wattGLB[w_sta:w_end]
DeltaVSq_GLB <- (data.table::shift(data_win_glb) - data_win_glb)
suppressWarnings(
{GLB_Xi[i] <- max( abs( DeltaVSq_GLB - x_i_CS[i] ), na.rm = T)}
)
## pass test as clear
pass = GLB_Xi[i] < MS$offVSM
if (is.na(pass)) pass <- FALSE
## an info warning
if ( is.infinite(GLB_Xi[i]) & i > 1 ) {
if (interactive()) print(paste(GLB_Xi[i], format(aday, "%F"),i, pass ))
}
## set VCT flag
subday$CSflag[w_sta:w_end][ ( !subday$CSflag[w_sta:w_end] == 0) &
( subday$CSflag[w_sta:w_end] == 99) &
pass ] <- 0
} ##END for loop all points
}
#### if it is not clear is VCT
subday[[paste0("CSflag_", Flag_key)]][ subday$CSflag == 99 ] <- TRUE
subday$CSflag[subday$CSflag == 99] <- Flag_key
}
#---- 6. Low Direct Irradiance limit (LDI) -----------------------------
if (LDI_active) {
Flag_key <- 6
## low direct and not "Possible Direct Obstruction (23)"
## probably we know sun was obscured
subday[CSflag == 0 &
wattHOR < MS$LDIlim &
QCF_DIR != "Possible Direct Obstruction (23)",
CSflag := Flag_key ]
subday[CSflag == 99 &
wattHOR < MS$LDIlim &
QCF_DIR != "Possible Direct Obstruction (23)",
CSflag := Flag_key ]
subday[wattHOR < MS$LDIlim &
QCF_DIR != "Possible Direct Obstruction (23)",
paste0("CSflag_", Flag_key) := TRUE ]
subday[wattHOR < MS$LDIlim &
QCF_DIR != "Possible Direct Obstruction (23)",
paste0("CSflag_", Flag_key) := TRUE ]
}
#---- 7. Low Global Irradiance limit (LGI) -----------------------------
if (LGI_active) {
Flag_key <- 7
subday[ (CSflag == 0 ) & (wattGLB < MS$VGIlim), CSflag := Flag_key ]
subday[ (CSflag == 99) & (wattGLB < MS$VGIlim), CSflag := Flag_key ]
subday[ wattGLB < MS$VGIlim, paste0("CSflag_", Flag_key) := TRUE ]
subday[ wattGLB < MS$VGIlim, paste0("CSflag_", Flag_key) := TRUE ]
}
#---- 11. Too low direct radiation (DsT) -----------------~~~-----------
if (any(have_dir)) {
Flag_key <- 11
subday[ (CSflag == 0 ) & (wattHOR < CS_ref_HOR * ( 1 - (MS$DIR_s_T_fact / 100))), CSflag := Flag_key ]
subday[ (CSflag == 99) & (wattHOR < CS_ref_HOR * ( 1 - (MS$DIR_s_T_fact / 100))), CSflag := Flag_key ]
subday[ wattHOR < CS_ref_HOR * ( 1 - (MS$DIR_s_T_fact / 100)), paste0("CSflag_", Flag_key) := TRUE ]
}
#---- 8. Too Few CS point for the day (FCS) ----------------------------
if (FCS_active) {
Flag_key <- 8
## check all other CS flags to set this
wecare <- grep("CSflag_", names(subday), value = T)
acount <- nrow(subday[ rowSums( subday[, ..wecare ], na.rm = T ) == 0, ])
if ( acount < FCSlim ) {
subday[ subday$CSflag == 0 , CSflag := Flag_key ]
subday[ subday$CSflag == 99, CSflag := Flag_key ]
subday[, paste0("CSflag_", Flag_key) := TRUE ]
}
}
## rest is clear sky (we hope)
subday$CSflag[subday$CSflag == 99] <- 0
## Evaluation of CS detection
clear_sky <- subday$CSflag == 0
#----------------------------------------------------------------------#
# ## FIXME why I use that?
# ## skip day from training
# if (sum(clear_sky, na.rm = T) < relative_CS_lim ) {
# # print(paste(CS_name, "Skip Day minutes CS/lim/total ", sum(clear_sky, na.rm = T),"/",relative_CS_lim,"/", sum(sell)))
# next ## skip the rest of the loop and avoid alpha optimisation
# }
#----------------------------------------------------------------------#
RMSE <- RMSE(CS_ref_safe[clear_sky], subday$wattGLB[clear_sky])
MBE <- mean(CS_ref_safe[clear_sky] - subday$wattGLB[clear_sky], na.rm = T) /
mean(subday$wattGLB[clear_sky], na.rm = T)
cost <- sum( ( ( subday$wattGLB[clear_sky]) - CS_ref_safe[clear_sky] )**2 , na.rm = T ) /
sum(clear_sky, na.rm = T)
## ID statistics
MeanVIPcnt <- sum(subday$CSflag == 1, na.rm = T)
MaxVIPcnt <- sum(subday$CSflag == 2, na.rm = T)
VILcnt <- sum(subday$CSflag == 3, na.rm = T)
VCTcnt <- sum(subday$CSflag == 4, na.rm = T)
VSMcnt <- sum(subday$CSflag == 5, na.rm = T)
## plotting selection
# if ( any(clear_sky) &
# any(!is.na(subday$wattGLB[clear_sky])) &
# (RMSE < 0.005 | abs(MBE) < 0.005 ) ) {
#### PLOTS ####
## _ Main plot ---------------------------------------------------------
ylim <- range( c(subday$wattGLB, MS$MaxVIP_fct * CS_ref_safe), na.rm = T )
if ( ylim[2] > 1500 ) ylim[2] = 1500
# if ( ylim[2] > 400) ylim[2] = 400
ylim[1] = -25
par("mar" = c(2, 4.2, 1.5, 1) )
# par(mar = c(0, 0, 0, 0), oma = c(2, 4.2, 2, 1))
# par(mfrow = c(2,1))
# layout(matrix(c(1,1,1,2,3), nrow = 5, ncol = 1, byrow = TRUE))
layout(matrix(c(1), nrow = 1, ncol = 1, byrow = TRUE))
## plot global measurements
plot(subday$Date, subday$wattGLB, 'l', col = "green" ,
ylim = ylim, ylab = "Watt/m^2", xlab = "", xaxt = "n", lwd = 2 )
abline( v = axis.POSIXct(1, at = pretty(subday$Date, n=24, min.n=24) ),col = "lightgray", lty = "dotted", lwd = .5)
## plot direct measurements
lines(subday$Date, subday$wattHOR, "l", col = scales::alpha("blue", 0.8 ), lty = 1, lwd = 2 )
# lines(subday$Date, subday$wattDIR, "l", col = scales::alpha("blue", 0.8 ), lty = 2, lwd = 2 )
## plot expected global reference line
lines(subday$Date, CS_ref_safe, lty = 3, col = "green", lwd = 2 )
## direct irradiance test value !!
lines(subday$Date, subday$CS_ref_HOR, lty = 3, col = "red", lwd = 2 )
lines(subday$Date, subday$CS_ref_HOR * ( 1 - ( MS$DIR_s_T_fact / 100 )), "l", lty = 3, col = "red", lwd = 2 )
if (MeanVIP_active & any(have_glb)) {
lines(subday$Date, CS_ref_rm_VIP_low, col = kcols[1], lty = 2, lwd = 2 )
lines(subday$Date, CS_ref_rm_VIP_upp, col = kcols[1], lty = 3, lwd = 2 )
}
if (MaxVIP_active & any(have_glb)) {
lines(subday$Date, CS_ref_rmax_VIP_upp, col = kcols[2], lty = 2, lwd = 2 )
lines(subday$Date, CS_ref_rmax_VIP_low, col = kcols[2], lty = 3, lwd = 2 )
}
abline( h = MS$VGIlim, lty = 2 , col = kcols[7])
#---- Main plot ID points ----
## 1. mean value of irradiance during the time period
ddd = subday$Date[ subday$CSflag == 1 ]
vvv = subday$wattGLB[ subday$CSflag == 1 ]
points(ddd, vvv, pch = 8, col = kcols[1], cex = .4)
points(ddd, vvv - vvv - 15, pch = 8, col = kcols[1], cex = .2)
## 2. Max value of irradiance during the time period
ddd = subday$Date[ subday$CSflag == 2 ]
vvv = subday$wattGLB[ subday$CSflag == 2 ]
points(ddd, vvv, pch = 8, col = kcols[2], cex = .4)
points(ddd, vvv - vvv - 15, pch = 8, col = kcols[2], cex = .2)
## 3. Variability in irradiance by the length (VIL)
ddd <- subday$Date[ subday$CSflag == 3 ]
vvv <- subday$wattGLB[ subday$CSflag == 3 ]
points(ddd, vvv, pch = 8, col = kcols[3], cex = .4)
points(ddd, vvv - vvv - 15, pch = 8, col = kcols[3], cex = .2)
## 4. Variance of Changes in the Time series (VCT)
ddd <- subday$Date[ subday$CSflag == 4 ]
vvv <- subday$wattGLB[ subday$CSflag == 4 ]
points(ddd, vvv, pch = 8, col = kcols[4], cex = .4)
points(ddd, vvv - vvv - 15, pch = 8, col = kcols[4], cex = .2)
## 5. Variability in the Shape of the irradiance Measurements (VSM)
ddd <- subday$Date[ subday$CSflag == 5 ]
vvv <- subday$wattGLB[ subday$CSflag == 5 ]
points(ddd, vvv, pch = 8, col = kcols[5], cex = .4)
points(ddd, vvv - vvv - 15, pch = 8, col = kcols[5], cex = .2)
## 6. Low Direct Irradiance limit (LDI)
ddd <- subday$Date[ subday$CSflag == 6 ]
vvv <- subday$wattGLB[ subday$CSflag == 6 ]
LDIcnt <- sum(subday$CSflag == 6, na.rm = T)
points(ddd, vvv, pch = 8, col = kcols[6], cex = .4)
points(ddd, vvv - vvv - 15, pch = 8, col = kcols[6], cex = .2)
## 7. Low Global Irradiance limit (LGI)
ddd <- subday$Date[ subday$CSflag == 7 ]
vvv <- subday$wattGLB[ subday$CSflag == 7 ]
VGLcnt <- sum(subday$CSflag == 7, na.rm = T)
points(ddd, vvv, pch = 8, col = kcols[7], cex = .4)
points(ddd, vvv - vvv - 15, pch = 8, col = kcols[7], cex = .2)
## 11. Too low direct radiation (DsT)
ddd <- subday$Date[ subday$CSflag_11 ]
vvv <- subday$wattHOR[ subday$CSflag_11 ]
DsTcnt <- sum(subday$CSflag_11, na.rm = T)
points(ddd, vvv, pch = 8, col = kcols[11], cex = .4)
points(ddd, vvv - vvv - 15, pch = 8, col = kcols[11], cex = .2)
wecare <- grep("CSflag_", names(subday), value = T)
sel <- rowSums( subday[, ..wecare ], na.rm = T ) == 0
## the rest is clear
if (any(have_glb)) {
ddd <- subday$Date[ sel ]
vvv <- subday$wattGLB[ sel ]
Clear_cnt <- sum( sel, na.rm = T)
points(ddd, vvv - vvv - 25, pch = 8, col = "green", cex = .2)
}
if (any(have_dir)) {
ddd <- subday$Date[ sel ]
vvv <- subday$wattHOR[ sel ]
Clear_cnt <- sum( sel, na.rm = T)
points(ddd, vvv - vvv - 25, pch = 8, col = "green", cex = .2)
}
title(main = paste(aday, format(aday, "%j"),
"RMSE:", round(RMSE, 3),
"MBE:", round(MBE, 3) ), cex.main = 1)
legend("topright", bty = "n",
legend = c( paste("CS GLB: ", Clear_cnt),
paste("MeanVIP:", MeanVIPcnt),
paste("MaxVIP: ", MaxVIPcnt),
paste("VIL: ", VILcnt),
paste("VCT: ", VCTcnt),
paste("VSM: ", VSMcnt),
paste("LDI: ", LDIcnt),
paste("VGIlim: ", VGLcnt),
paste("DsT: ", DsTcnt) ),
col = c("green",
kcols[1],
kcols[2],
kcols[3],
kcols[4],
kcols[5],
kcols[6],
kcols[7],
kcols[11]),
pch = c(8) ,cex = 1.1)
#---- Filter Plots ----
layou_n <- sum(MeanVIP_active, MaxVIP_active, VIL_active, VCT_active, VSM_active)
layout(matrix(c(1,2,3,4,5), nrow = layou_n, ncol = 1, byrow = TRUE))
par("mar" = c(.5, 4.2, .5, 1) )
## _ 1. Mean value of irradiance during the time period ----------------
if (MeanVIP_active & any(have_glb)){
par("mar" = c(0, 4.2, .5, 1) )
ylim = range(c( - MS$CS_ref_rm_VIP_low * 1.7, MS$CS_ref_rm_VIP_upp * 1.7 ), na.rm = T)