-
Notifications
You must be signed in to change notification settings - Fork 6
/
aggregateResult.R
802 lines (677 loc) · 28.8 KB
/
aggregateResult.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
#' Creation of Mc_all (only antares > V6)
#'
#' @param opts \code{list} of simulation parameters returned by the function \link{setSimulationPath}
#' @param nbcl \code{numeric} Number of parralel process
#' @param verbose \code{numeric} see logs (1) or not (0)
#'
#' @import data.table parallel pipeR
#'
#'
#' @examples
#' \dontrun{
#' parAggregateMCall(opts)
#'
#' }
#'
#' @export
parAggregateMCall <- function(opts, nbcl = 8, verbose = 1){
if(verbose == 1){
cat("Mc all start\n")
}
if(verbose == 0){
pboptions(type = "none")
}
areas <- getAreas(opts = opts)
links <- getLinks(opts = opts)
clusters <- areas
todo <- data.table(V1 = c(areas, links, clusters),
V2 = c(rep("area", length(areas)),
rep("link", length(links)),
rep("cluster", length(clusters))
))
todo <- apply(todo, 1, function(X)list(X))
if(nbcl>1){
parallel <- TRUE
}else{
parallel <- FALSE
}
if(parallel){
cl <- makeCluster(nbcl)
clusterEvalQ(cl, library(antaresEditObject))
clusterExport(cl, "opts")
registerDoParallel(cl)
}else{
cl <- NULL
}
pblapply(todo, function(X){
d <- list(X[[1]][1])
names(d) <- X[[1]][2]
aggregateResult(opts, filtering = TRUE, verbose = 0, selected = d)
}, cl = cl)
if(verbose == 1){
cat("Start computing\n")
}
if(parallel){
stopCluster(cl)
}
if(verbose == 1){
cat("Mc all done\n")
}
}
#' Creation of Mc_all
#'
#' @param opts \code{list} of simulation parameters returned by the function \link{setSimulationPath}
#' @param verbose \code{numeric} show log in console. Defaut to 1
#' \itemize{
#' \item{0}{ : No log}
#' \item{1}{ : Short log}
#' \item{2}{ : Long log}
#'}
#' @param filtering \code{boolean} filtering control
#' @param timestep \code{character} antares timestep
#' @param selected \code{list} named list (pass to antaresRead) : list(areas = 'a', links = 'a - e')
#'
#' @import data.table
#'
#' @export
aggregateResult <- function(opts, verbose = 1, filtering = FALSE,
selected = NULL, timestep = c("annual", "daily", "hourly", "monthly", "weekly")){
if(verbose > 0)
{
try({
pb <- txtProgressBar(style = 3)
})
}
oldw <- getOption("warn")
options(warn = -1)
opts <- antaresRead::setSimulationPath(opts$simPath)
options(warn = oldw)
#Version which readAntares
linkTable <- try(data.table::fread(system.file("/format_output/tableOutput.csv", package = "antaresEditObject")),
silent = TRUE)
.errorTest(linkTable, verbose, "Load of link table")
#load link table
linkTable$progNam <- linkTable$Stats
linkTable$progNam[which(linkTable$progNam == "values")] <- "EXP"
# dtaMc <- paste0(opts$simDataPath, "/mc-ind")
numMc <- opts$mcYears
#sapply on timeStep
#allTyped <- c("annual", "daily", "hourly", "monthly", "weekly")
#allTyped <- 'hourly'
sapply(timestep, function(type, verbose)
{
.addMessage(verbose, paste0("------- Mc-all : ", type, " -------"))
try({
#load first MC-year
a <- Sys.time()
oldw <- getOption("warn")
options(warn = -1)
if(!filtering)
{
dta <- antaresRead::readAntares(area = "all", links = "all", clusters = "all",
timeStep = type, simplify = FALSE, mcYears = numMc[1], showProgress = FALSE)
}else{
if(is.null(selected)){
areasselect <- .getAreasToAggregate(opts, type)
linksSelect <- .getLinksToAggregate(opts, type)
dta <- antaresRead::readAntares(area = areasselect,
links = linksSelect,
clusters = areasselect,
timeStep = type,
simplify = FALSE,
mcYears = numMc[1],
showProgress = FALSE)
}else{
dta <- antaresRead::readAntares(area = selected$area,
links = selected$link,
clusters = selected$cluster,
timeStep = type,
simplify = FALSE,
mcYears = numMc[1],
showProgress = FALSE)
}
}
options(warn = oldw)
if(length(dta)>0){
dtaLoadAndcalcul <- try({
aTot <- as.numeric(Sys.time() - a)
SDcolsStartareas <- switch(type,
daily = 6,
annual = 4,
hourly = 7,
monthly = 5,
weekly = 4
)
SDcolsStartClust <- SDcolsStartareas + 1
#make structure
struct <- list(areas = dta$areas[,.SD, .SDcols = 1:SDcolsStartareas],
links = dta$links[,.SD, .SDcols = 1:SDcolsStartareas],
clusters = dta$clusters[,.SD, .SDcols = 1:SDcolsStartClust])
if(type == "weekly"){
struct$areas$timeId <- as.numeric(substr(struct$areas$time, nchar(as.character(struct$areas$time[1]))-1,
nchar(as.character(struct$areas$time[1]))))
struct$link$timeId <- as.numeric(substr(struct$link$time, nchar(as.character(struct$link$time[1]))-1,
nchar(as.character(struct$link$time[1]))))
struct$clusters$timeId <- as.numeric(substr(struct$clusters$time, nchar(as.character(struct$clusters$time[1]))-1,
nchar(as.character(struct$clusters$time[1]))))
}
if(!is.null(struct$areas$day)){
struct$areas$day <- ifelse(nchar(struct$areas$day) == 1,
paste0("0", struct$areas$day),
as.character(struct$areas$day))
}
if(!is.null(struct$links$day)){
struct$links$day <- ifelse(nchar(struct$links$day) == 1,
paste0("0", struct$links$day),
as.character(struct$links$day))
}
if(!is.null(struct$links$day)){
struct$clusters$day <- ifelse(nchar(struct$clusters$day) == 1,
paste0("0", struct$clusters$day),
as.character(struct$clusters$day))
}
b <- Sys.time()
#value structure
value <- .giveValue(dta, SDcolsStartareas, SDcolsStartClust)
N <- length(numMc)
value <- lapply(value, .creatStats)
btot <- as.numeric(Sys.time() - b)
if(verbose>0)
{
try({
.progBar(pb, type, 1, N)
})
}
#sequentially add values
if(N>1)
{
for(i in 2:N){
a <- Sys.time()
oldw <- getOption("warn")
options(warn = -1)
if(!filtering)
{
dtaTP <- antaresRead::readAntares(area = "all", links = "all", clusters = "all",
timeStep = type, simplify = FALSE, mcYears = numMc[i], showProgress = FALSE)
}else{
if(is.null(selected)){
dtaTP <- antaresRead::readAntares(area = areasselect, links = linksSelect, clusters = areasselect,
timeStep = type, simplify = FALSE, mcYears = numMc[i], showProgress = FALSE)
}
else{
dtaTP <- antaresRead::readAntares(area = selected$area,
links = selected$link,
clusters = selected$cluster,
timeStep = type,
simplify = FALSE,
mcYears = numMc[i],
showProgress = FALSE)
}
}
options(warn = oldw)
aTot <- aTot + as.numeric(Sys.time() - a)
b <- Sys.time()
valueTP <- .giveValue(dtaTP, SDcolsStartareas, SDcolsStartClust)
valueTP <- lapply(valueTP, .creatStats)
value$areas <- .updateStats(value$areas, valueTP$areas)
value$links <- .updateStats(value$links, valueTP$links)
value$clusters <- .updateStats(value$clusters, valueTP$clusters)
btot <- btot + as.numeric(Sys.time() - b)
if(verbose>0)
{
try({
.progBar(pb, type, i, N)
})
}
}
}
#Calcul of sd
oldw <- getOption("warn")
options(warn = -1)
b <- Sys.time()
value$areas$std <- sqrt((value$areas$sumC - ((value$areas$sum * value$areas$sum)/N))/(N))
#nan due to round
for (i in names(value$areas$std))
value$areas$std[is.nan(get(i)), (i) := 0]
value$links$std <- sqrt((value$links$sumC - ((value$links$sum * value$links$sum)/N))/(N))
#nan due to round
for (i in names(value$links$std))
value$links$std[is.nan(get(i)), (i) := 0]
value$clusters$std <- sqrt((value$clusters$sumC - ((value$clusters$sum * value$clusters$sum)/N))/(N))
#nan due to round
for (i in names(value$clusters$std))
value$clusters$std[is.nan(get(i)), (i) := 0]
options(warn = oldw)
value$areas$sumC <- NULL
value$links$sumC <- NULL
value$clusters$sumC <- NULL
value$areas$sum <- value$areas$sum / N
value$links$sum <- value$links$sum / N
value$clusters$sum <- value$clusters$sum / N
btot <- btot + as.numeric(Sys.time() - b)
.addMessage(verbose, paste0("Time for reading data : ", round(aTot,1), " secondes"))
.addMessage(verbose, paste0("Time for calculating : ", round(btot,1), " secondes"))
}, silent = TRUE)
.errorTest(dtaLoadAndcalcul, verbose, "Load data and calcul")
#Write area
allfiles <- c("values")
areaWrite <- try(sapply(allfiles, function(f)
{
#prepare data for all country
areaSpecialFile <- linkTable[Folder == "area" & Files == f & Mode == tolower(opts$mode)]
namekeep <- paste(areaSpecialFile$Name, areaSpecialFile$Stats)
namekeepprog <- paste(areaSpecialFile$Name, areaSpecialFile$progNam)
areas <- cbind(value$areas$sum, value$areas$std, value$areas$min, value$areas$max)
if(nrow(areas) > 0)
{
areas <- areas[, .SD, .SDcols = which(names(areas)%in%namekeepprog)]
areas <- areas[, .SD, .SDcols = match(namekeepprog, names(areas))]
nbvar <- ncol(areas)
areas <- cbind(struct$areas, areas)
ncolFix <- ncol(struct$areas) - 3
areas[, c("mcYear", "time") := NULL]
allAreas <- unique(areas$area)
for(i in 1:length(namekeepprog))
{
var <- namekeepprog[i]
dig <- areaSpecialFile[var == paste(Name,progNam )]$digits
areas[, c(var) := .(do.call(round, args = list(get(var), digits = dig)))]
}
if(length(allAreas) > 0)
{
sapply(allAreas, function(areasel){
#for each country prepare file
areastowrite <- areas[area == areasel]
areastowrite[,c("area") := NULL]
indexMin <- min(areas$timeId)
indexMax <- max(areas$timeId)
kepNam <- names(struct$areas)[!names(struct$areas)%in%c("area","mcYear","time")]
nameIndex <- ifelse(type == "weekly", "week", "index")
kepNam[which(kepNam == "timeId")] <- nameIndex
#write txt
.writeFileOut(dta = areastowrite, timestep = type, fileType = f,
ctry = areasel, opts = opts, folderType = "areas", nbvar = nbvar,
indexMin = indexMin, indexMax = indexMax, ncolFix = ncolFix,
nomcair = areaSpecialFile$Name, unit = areaSpecialFile$Unit,
nomStruct = kepNam,Stats = areaSpecialFile$Stats)
})
}
}
}), silent = TRUE)
.errorTest(areaWrite, verbose, "Area write")
allfiles <- c("values")
linkWrite <- try(sapply(allfiles, function(f)
{
#prepare data for all link
linkSpecialFile <- linkTable[Folder == "link" & Files == f & Mode == tolower(opts$mode)]
namekeep <- paste(linkSpecialFile$Name, linkSpecialFile$Stats)
namekeepprog <- paste(linkSpecialFile$Name, linkSpecialFile$progNam)
links <- cbind(value$links$sum, value$links$std, value$links$min, value$links$max)
if(nrow(links) > 0)
{
links <- links[, .SD, .SDcols = which(names(links)%in%namekeepprog)]
links <- links[, .SD, .SDcols = match(namekeepprog, names(links))]
nbvar <- ncol(links)
links <- cbind(struct$links, links)
ncolFix <- ncol(struct$links)-3
links[, c("mcYear", "time") := NULL]
allLink<- unique(links$link)
for(i in 1:length(namekeepprog))
{
var <- namekeepprog[i]
dig <- linkSpecialFile[var == paste(Name,progNam )]$digits
links[, c(var) := .(do.call(round, args = list(get(var), digits = dig)))]
}
sapply(allLink, function(linksel){
#for eatch link prepare file
linkstowrite <- links[link == linksel]
linkstowrite[,c("link") := NULL]
indexMin <- min(links$timeId)
indexMax <- max(links$timeId)
kepNam <- names(struct$link)[!names(struct$link)%in%c("link","mcYear","time")]
nameIndex <- ifelse(type == "weekly", "week", "index")
kepNam[which(kepNam == "timeId")] <- nameIndex
#write txt
.writeFileOut(dta = linkstowrite, timestep = type, fileType = f,
ctry = linksel, opts = opts, folderType = "links", nbvar = nbvar,
indexMin = indexMin, indexMax = indexMax, ncolFix = ncolFix,
nomcair = linkSpecialFile$Name, unit = linkSpecialFile$Unit,
nomStruct = kepNam,Stats = linkSpecialFile$Stats)
})
}
}), silent = TRUE)
.errorTest(linkWrite, verbose, "Link write")
##Details
details <- value$clusters$sum
if(!is.null(struct$clusters$day))
{
if(length(struct$clusters$day) > 0)
{
endClust <- cbind(struct$clusters, details)
endClust[, c("mcYear") := NULL]
detailWrite <- try(sapply(unique(endClust$area), function(ctry){
#for each country prepare file
endClustctry <- endClust[area == ctry]
orderBeg <- unique(endClustctry$time)
endClustctry[,c("area") := NULL]
if(tolower(opts$mode) == "economy")
{
nameBy <- c("production EXP", "NP Cost EXP", "NODU EXP")
}else{
nameBy <- c("production EXP")
}
nomStruct <- names(endClustctry)[!names(endClustctry)%in%
c("cluster", nameBy)]
tmp_formula <- nomStruct
tmp_formula <- as.formula(paste0(paste0(tmp_formula, collapse = "+"), "~cluster"))
if(tolower(opts$mode) == "economy")
{
endClustctry[, c(nameBy) := list(round(`production EXP`),
round(`NP Cost EXP`),
round(`NODU EXP`))]
}else{
endClustctry[, c(nameBy) := list(round(`production EXP`))]
}
endClustctry <- data.table::dcast(endClustctry, tmp_formula,
value.var = c(nameBy))
endClustctry <- endClustctry[match(orderBeg, endClustctry$time)]
endClustctry[,c("time") := NULL]
nomStruct <- nomStruct[-which(nomStruct == "time")]
nomcair <- names(endClustctry)
nomcair <- nomcair[!nomcair%in%nomStruct]
nbvar <- length(nomcair)
unit <- rep("", length(nomcair))
unit[grep("production EXP_",nomcair)] <- "MWh"
unit[grep("NP Cost EXP_",nomcair)] <- "NP Cost - Euro"
unit[grep("NODU EXP_",nomcair)] <- "NODU"
nomcair <- gsub("production EXP_","",nomcair)
nomcair <- gsub("NP Cost EXP_","",nomcair)
nomcair <- gsub("NODU EXP_","",nomcair)
Stats <- rep("EXP", length(unit))
nameIndex <- ifelse(type == "weekly", "week", "index")
nomStruct[which(nomStruct == "timeId")] <- nameIndex
indexMin <- min(endClustctry$timeId)
indexMax <- max(endClustctry$timeId)
ncolFix <- length(nomStruct)
#write details txt
.writeFileOut(dta = endClustctry, timestep = type, fileType = "details",
ctry = ctry, opts = opts, folderType = "areas", nbvar = nbvar,
indexMin = indexMin, indexMax = indexMax, ncolFix = ncolFix,
nomcair = nomcair, unit = unit, nomStruct = nomStruct,Stats = Stats)
}), silent = TRUE)
.errorTest(detailWrite, verbose, "Detail write")
}
}
}
})
.addMessage(verbose, paste0("------- End Mc-all : ", type, " -------"))
}, verbose = verbose)
if(verbose>0)
{
try({
close(pb)
})
}
}
#' @title Extract value part of data
#'
#' @description Extract value part of data
#'
#' @param dta \code{data.table} of data load which antaresRead::readAntares
#' @param SDcolsStartareas \code{numeric} first column of data for areas
#' @param SDcolsStartClust \code{numeric} first column of data for details
#'
#' @return value {data.table} value selected
#'
#' @noRd
.giveValue <- function(dta, SDcolsStartareas, SDcolsStartClust)
{
value = list()
if(!is.null(dta$areas)){
value$areas <- dta$areas[,lapply(.SD, as.numeric), .SDcols = (SDcolsStartareas+1):ncol(dta$areas)]
}
if(!is.null(dta$links)){
value$links <- dta$links[,lapply(.SD, as.numeric), .SDcols = (SDcolsStartareas+1):ncol(dta$links)]
}
if(!is.null(dta$clusters)){
value$clusters <- dta$clusters[,lapply(.SD, as.numeric), .SDcols = (SDcolsStartClust+1):ncol(dta$clusters)]
}
value
}
#' @title Create stat file compute min, max sd and mean
#'
#' @description Create stat file compute min, max sd and mean
#'
#' @param X \code{data.table} data load which
#' antaresRead::readAntares and extract which .giveValue
#'
#' @return res {data.table} stats computed
#'
#' @noRd
#'
.creatStats <- function(X){
# res <- list(sum = X, min = X, max = X,
# sumC = data.table::data.table(sapply(X, function(Z) Z*Z)))
res <- list(sum = X, min = X, max = X, sumC = X*X)
names(res$sum) <- paste(names(X), "EXP")
names(res$min) <- paste(names(X), "min")
names(res$max) <- paste(names(X), "max")
names(res$sumC) <- paste(names(X), "std")
res
}
#' @title Update data min, max sd and mean
#'
#' @description Update data min, max sd and mean
#'
#' @param X \code{data.table} data init which .creatStats
#' @param Y \code{data.table} data load which
#' antaresRead::readAntares and extract which .giveValue
#'
#' @return X {data.table} stats updated
#'
#' @noRd
.updateStats <- function(X, Y){
X$sum <- X$sum + Y$sum
X$min <- pmin.fast(X$min , Y$min)
X$max <- pmax.fast(X$max , Y$max)
X$sumC <- X$sumC + Y$sumC
X
}
# fast pmin and pmax for two elements
pmin.fast <- function(k,x) (x+k - abs(x-k))/2
pmax.fast <- function(k,x) (x+k + abs(x-k))/2
#' @title Write mc-all files
#'
#' @description Write mc-all files
#'
#' @param dta \code{data.table} data
#' @param timestep \code{character} must be annual, monthly, weekly, daily or hourly
#' @param fileType \code{character} must be values or details
#' @param ctry \code{character} country.
#' @param opts \code{list} of simulation parameters returned by the function \link{setSimulationPath}
#' @param folderType \code{character} must be areas or links
#' @param nbvar \code{numeric} for header write, currently ncol(dta)
#' @param indexMin \code{numeric} for header write, depend of number of row write and calandar
#' @param indexMax \code{numeric} for header write, depend of number of row write and calandar
#' @param ncolFix \code{numeric} for header write
#' @param nomcair \code{character} for header write, names of variables
#' @param unit \code{character} for header write, unit of variables
#' @param nomStruct \code{character} for header write, depend of timestep
#' @param Stats \code{character} for header write, stats compute for eatch variables
#'
#'
#' @noRd
#'
.writeFileOut <- function(dta, timestep, fileType, ctry, opts, folderType, nbvar,
indexMin, indexMax, ncolFix, nomcair, unit, nomStruct, Stats){
# threads for fwrite
data.table::setDTthreads(2)
folderTypesansS <- substr(folderType, 1, nchar(folderType)-1)
abrtype <- substr(fileType, 1, 2)
if(timestep == "annual"){
nomStruct <- ""
dta$timeId <- "Annual"
}
if(folderType == "links"){
ctryDecomp <- strsplit(as.character(ctry), " - ")%>>%unlist
entete <- paste0(ctryDecomp[1], "\t",folderTypesansS,"\t",abrtype,
"\t",timestep,"\n",ctryDecomp[2] ,"\tVARIABLES\tBEGIN\tEND\n\t",
nbvar, "\t",indexMin, "\t",indexMax, "\n\n",
ctryDecomp[1], "\t", timestep, paste0(rep("\t", ncolFix), collapse = ""),
paste0(nomcair, collapse = "\t"),"\n",
paste0(rep("\t", ncolFix+1), collapse = ""),paste0(unit, collapse = "\t"),"\n",
"\t", paste0(nomStruct, collapse = "\t"), "\t", paste0(Stats, collapse = "\t"), "\n")
}else{
entete <- paste0(ctry, "\t",folderTypesansS,"\t",abrtype, "\t",timestep,"\n\tVARIABLES\tBEGIN\tEND\n\t",
nbvar, "\t",indexMin, "\t",indexMax, "\n\n",
ctry, "\t", timestep, paste0(rep("\t", ncolFix), collapse = ""),
paste0(nomcair, collapse = "\t"),"\n",
paste0(rep("\t", ncolFix+1), collapse = ""),paste0(unit, collapse = "\t"),"\n",
"\t", paste0(nomStruct, collapse = "\t"), "\t", paste0(Stats, collapse = "\t"), "\n")
}
dir.create(paste0(opts$simDataPath, "/mc-all", "/",folderType,"/", ctry),
recursive = TRUE, showWarnings = FALSE)
outputFile <- paste0(opts$simDataPath, "/mc-all", "/",folderType,"/", ctry, "/",
fileType, "-",timestep,".txt")
file <- file(outputFile, "wb")
write.table(entete,file , row.names = FALSE, eol = "",
quote = FALSE, col.names = FALSE)
# write.table(cbind(NA, dta), file,
# append = TRUE,
# row.names = FALSE,
# col.names =FALSE,
# quote = FALSE,sep = "\t",
# na = "")
close(file)
data.table::fwrite(cbind(NA, dta), outputFile,
append = TRUE,
row.names = FALSE,
quote = FALSE, sep = "\t",
eol = "\n", na = "N/A")
}
#' @title Edit info on output folder
#'
#' @description Edit info on output folder
#'
#' @param outData \code{character} out folder path
#' @param simulationName \code{character} simulation name
#' @param dateTim2 \code{datetime} simulation begin date time
#' @param dtTim \code{datetime} simulation end date time
#'
#' @noRd
.editOutputInfo <- function(outData, simulationName, dateTim2, dtTim)
{
#Edit infos output simulation
iniPath <- paste0(outData, "/info.antares-output")
infosIni <- readIniFile(iniPath)
infosIni$general$name <- substr(simulationName, 1, nchar(simulationName)-10)
dateTim2 <- gsub("-" , ".", dateTim2)
dateTim2 <- gsub(" " , " - ", dateTim2)
infosIni$general$date <- dateTim2
infosIni$general$title <- dateTim2
infosIni$general$timestamp <- round(as.numeric(difftime(dtTim,
as.POSIXct("1970-01-01 00:00:00"), units = "sec")), 0)
writeIni(infosIni, iniPath)
}
#' @title Progress bar
#'
#' @description Progress bar
#'
#' @param pb \code{progressbar} progress bar to update
#' @param timestep \code{character} must be annual, monthly, weekly, daily or hourly
#' @param timestep \code{character} must be annual, monthly, weekly, daily or hourly
#' @param mcALLNum \code{numeric} current mcYears position
#' @param nbmcallTOT \code{numeric} number of mcYear
#'
#' @return progress bar update
#'
#' @noRd
.progBar <- function(pb, timeStep, mcALLNum, nbmcallTOT)
{
usalTime <- data.frame(period = c("start","annual", "daily", "hourly", "monthly", "weekly"),
value = c(0, 20, 200, 600, 800, 1000))
per <- which(usalTime$period == timeStep)
dif <- usalTime$value[per] - usalTime$value[per - 1]
approxEnd <- mcALLNum/nbmcallTOT
i = (dif * approxEnd + usalTime$value[per - 1]) / usalTime$value[length( usalTime$value)]
setTxtProgressBar(pb, i)
}
.getAreasToAggregate <- function(opts, timeStep){
inputsAreas <- paste0(opts$studyPath, "/input/areas")
allAreas <- list.dirs(inputsAreas, full.names = FALSE)
allAreas <- allAreas[!allAreas == ""]
out <- sapply(allAreas, function(X){
Ini <- paste0(inputsAreas, "/", X, "/optimization.ini")
gsub(" ", "", unlist(strsplit(readIniFile(Ini)$filtering$`filter-synthesis`, ",")))
}, simplify = FALSE)
out <- lapply(out, function(X){
any(X == timeStep)
})
names(out)[which(unlist(out))]
}
.getLinksToAggregate <- function(opts, timeStep){
inputsLinks <- paste0(opts$studyPath, "/input/links")
allLinks <- list.dirs(inputsLinks, full.names = FALSE)
allLinks <- allLinks[!allLinks == ""]
out <- sapply(allLinks, function(X){
Ini <- paste0(inputsLinks, "/", X, "/properties.ini")
res <- lapply(readIniFile(Ini), function(X){X$`filter-synthesis`})
lapply(res, function(X)gsub(" ", "", unlist(strsplit(X, ","))))
})
out <- out[lapply(out, length)!=0]
out <- lapply(out, function(X){
lapply(X, function(Y){
any(Y == timeStep)
})
})
out <- lapply(out, unlist)
out <- lapply(out, function(X)X[X])
res <- list()
for(i in 1:length(out)){
res[[i]] <- paste(names(out)[i], names(out[[i]]), sep = " - ")
}
res <- unlist(res)
res
}
.recupeFilesUser <- function(opts){
if(dir.exists(paste0(opts$studyPath, "/user/tempfile/")))
{
tocp <- paste0(opts$studyPath, "/user/tempfile/", list.files(paste0(opts$studyPath, "/user/tempfile"), recursive = TRUE))
initialFile <- gsub("/user/tempfile/","/input/", tocp)
file.copy(tocp, initialFile, overwrite = TRUE)
unlink(paste0(opts$studyPath, "/user/tempfile"), recursive = TRUE)
}
}
#' @title error test
#'
#' @description error test
#'
#' @param tryReturn return from try
#' @param verbose \code{numeric} show log in console. Defaut to 1
#' @param msg \code{character} message to display if no error
#'
#' @noRd
.errorTest <- function(tryReturn, verbose, msg)
{
if("try-error" %in% class(tryReturn)){
stop(msg, " : ", tryReturn[1])
}else{
if(verbose == 2){
cat(paste0(msg, " : Ok\n"))
}
}
}
#' @title Display message on console
#'
#' @description Display message on console
#'
#' @param verbose \code{numeric} show log in console. Defaut to 1
#' @param valAf \code{numeric} show log in console if valAf == verbose.
#' @param msg \code{character} message to display if no error
#'
#' @noRd
.addMessage <- function(verbose, msg, valAf = 2){
if(verbose == valAf){
cat(paste0(msg, "\n"))
}
}