outer_procedure.r 20.6 KB
Newer Older
carstennh's avatar
carstennh committed
1
2
3
#' Perform Habitat Sampling and Probability Mapping
#'
#'This is the main function that performs everything: specify the input imagery, select model type, initiate sampling and model building, generates interactive maps and produce final probability raster output
4
#'
carstennh's avatar
carstennh committed
5
6
7
8
9
10
#' @param in.raster satellite time series stack (rasterBrickObject) or just any type of image (*rasterObject)
#' @param init.samples starting number of spatial locations
#' @param sample_type distribution of spatial locations c("random","regular")
#' @param nb_models number of models (independent classifiers) to collect
#' @param nb_it number of iterations for model accuracy
#' @param buffer distance (in m) for new sample collection around initial samples (depends on pixel size)
11
12
#' @param reference reference spectra as a data.frame with (lines = classes, column = predictors)
#' @param model which machine learning classifier to use c("rf", "svm") for random forest or support vector machine implementation
carstennh's avatar
carstennh committed
13
#' @param mtry number of predictor used at random forest splitting nodes (mtry << n predictors)
14
#' @param mod.error threshold for model error until which iteration is being executed
carstennh's avatar
carstennh committed
15
#' @param last only true for one class classifier c("FALSE", TRUE")
16
#' @param seed set seed for reproducible results
carstennh's avatar
carstennh committed
17
18
19
#' @param init.seed "sample" for new or use run1@seeds to reproduce previous steps
#' @param outPath output path for saving results
#' @param step at which step should the procedure start, e.g. use step = 2 if the first habitat is already extracted
20
#' @param classNames character vector with class names in the order of reference spectra
carstennh's avatar
carstennh committed
21
22
#' @param n_classes total number of classes (habitat types) to be separated
#' @param multiTest number of test runs to compare different probability outputs
23
#' @param RGB rgb channel numbers for image plot
24
25
#' @param in.memory boolean for raster processing (memory = "TRUE", from disk = "FALSE")
#' @param color single colors for continuous color palette interpolation
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
26
#' @param overwrite overwrite the KML and raster files from previous runs (default TRUE)
27
#' @param save_runs an Habitat object is saved into disk for each run (default TRUE)
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
28
29
#' @param parallel_mode run loops using all available cores (default FALSE)
#' @param max_num_cores maximum number of cores for parallelism (default 5)
30
#' @param plot_on_browser plot on the browser or inline in a notebook (default TRUE)
carstennh's avatar
carstennh committed
31
#'
32
#' @return 4 files per step:
33
#' 1) Habitat type probability map as geocoded *.kmz file (with a *.kml layer and *.png image output), and *.tif raster file 
34
#' 2) A Habitat object (only if save_runs is set to TRUE) consisting of 7 slots: \cr
35
#' run1@models - list of selected classifiers \cr
36
37
38
39
40
41
42
#' run1@ref_samples - list of SpatialPointsDataFrames with same length as run1@models holding reference labels [1,2] for each selected model \cr
#' run1@switch - vector of lenght run1@models indicating if target class equals 2, if not NA the labels need to be switched \cr
#' run1@layer - raster map of habitat type probability \cr
#' run1@mod_all - list of all classifiers (equals nb_models) \cr
#' run1@class_ind - vector of predictive distance measure for all habitats \cr
#' run1@seeds - vector of seeds for random sampling \cr
#' all files are saved with step number, the *.tif file is additionally saved with class names
carstennh's avatar
carstennh committed
43
#'
carstennh's avatar
carstennh committed
44
45
46
47
48
#' @examples
#' ###################
#' library(HaSa)
#' raster::plotRGB(Sentinel_Stack_2018, r = 19, g = 20, b = 21, stretch = "lin", axes = T)
#' sp::plot(Example_Reference_Points, pch = 21, bg = "red", col = "yellow", cex = 1.9, lwd = 2.5, add = T)
carstennh's avatar
carstennh committed
49
#' #specify a valid output path e.g.  "C:/Users/.../"
50
51
52
#' multi_Class_Sampling(in.raster = Sentinel_Stack_2018, init.samples = 30, sample_type = "regular", nb_models = 200, nb_it = 10, buffer = 15,
#' reference = Example_Reference_Points, model = "rf", mtry = 10, last = F, seed = 3, init.seed = "sample", outPath="C:/User/", step = 1,
#' classNames = c("deciduous", "coniferous", "heath_young", "heath_old", "heath_shrub", "bare_ground", "xeric_grass"), n_classes = 7,
carstennh's avatar
carstennh committed
53
54
#' multiTest = 1, RGB = c(19, 20, 21))
#' ###################
carstennh's avatar
carstennh committed
55
#' for threshold evaluation an interactive map is plotted in the web browser
carstennh's avatar
carstennh committed
56
57
#'
#' next steps start automatically, after command line input of:
carstennh's avatar
carstennh committed
58
#' 1) number of the apropriate map if multiTest > 1
59
#' 2) probability threshold for habitat type extraction
carstennh's avatar
carstennh committed
60
61
62
#' 3) decision to sample again y/n
#' 4) adjust starting number of samples and number of models
#'
63
64
65
66
67
68
#'
#'
#' if convergence fails / no models can be selected / init.samples are to little / or another error occurs, restart next step with:
#' in.raster = out.raster
#' reference = out.reference
#' step = specify next step number
carstennh's avatar
carstennh committed
69
70
71
#' classNames = out.names
#'
#' @export
72
73
74
75
76
77
78
79
80
multi_Class_Sampling <- function(in.raster,
                                 init.samples = 30,
                                 sample_type = "regular",
                                 nb_models = 200,
                                 nb_it = 10,
                                 buffer,
                                 reference,
                                 model = "rf",
                                 mtry = 10,
Carsten Neumann's avatar
Carsten Neumann committed
81
                                 mod.error=0.02,
82
83
84
85
86
87
88
89
                                 last = F,
                                 seed = 3,
                                 init.seed = "sample",
                                 outPath,
                                 step = 1,
                                 classNames,
                                 n_classes,
                                 multiTest = 1,
90
                                 RGB = c(19, 20, 21),
Carsten Neumann's avatar
Carsten Neumann committed
91
                                 in.memory = TRUE,
92
                                 color = c("lightgrey", "orange", "yellow", "limegreen", "forestgreen"),
93
                                 overwrite = TRUE,
94
                                 save_runs = TRUE,
95
                                 parallel_mode = FALSE,
96
                                 max_num_cores = 5,
97
                                 plot_on_browser = TRUE) {
98

99
  # Checks if its a new or a resumed run and asks the user to remove all step_*.tif 
100
  # files from the results folder in case of a new run.
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
101
  if (step == 1) {
102
103
    if (length(list.files(
        outPath,
104
        pattern = "step_(.*).tif",
105
106
107
108
        all.files = FALSE,
        include.dirs = TRUE,
        no.. = TRUE
    )) != 0) {
109
      message("Remove all step_*.tif files from the Results directory! Don't forget to save them and the other files.
110
111
112
113
              All other files will be overwriten when a new sampling is started.")
      return(NULL)
    }
  }
114
115
116
117
  ###first steps: data preparation
  if (class(reference) == "SpatialPointsDataFrame") {
    reference <- as.data.frame(raster::extract(in.raster, reference))
  }
carstennh's avatar
carstennh committed
118

119
  input_raster <- in.raster
120
121
122
123
124
  col <- colorRampPalette(c("lightgrey",
                            "orange",
                            "yellow",
                            "limegreen",
                            "forestgreen"))
carstennh's avatar
carstennh committed
125

126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
  ##############################################################################
  r <- n_classes
  if (names(in.raster)[1] != colnames(reference)[1]) {
    colnames(reference) <- names(in.raster)
  }
  if (step != 1) {
    if (step < 11) {
      load(paste(outPath,
                 paste("threshold_step_0", step - 1, sep = ""),
                 sep = ""))
    } else{
      load(paste(outPath,
                 paste("threshold_step_", step - 1, sep = ""),
                 sep = ""))
    }
  }
carstennh's avatar
carstennh committed
142

143
144
145
146
  for (i in step:r) {
    if (i == r) {
      last = T
    }
carstennh's avatar
carstennh committed
147

148
149
150
151
152
153
154
155
156
157
    if (multiTest > 1) {
      test <- list()
      maFo <- list()
      new.names <- list()
      new.acc <- list()
      decision = "0"
      ##########################################################################
      while (decision == "0") {
        for (rs in 1:multiTest) {
          ########################
158
159
160
161
162
163
164
165
166
167
168
169
170
          returns <- 1
          while (returns != 0) {
            decision3 <- ""
            maFo_rf <- sample_nb(
              raster = in.raster,
              nb_samples = seq(init.samples, init.samples, init.samples),
              sample_type = sample_type,
              nb_mean = nb_models,
              nb_it = nb_it,
              buffer = buffer,
              reference = reference,
              model = model,
              mtry = mtry,
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
171
              mod.error = mod.error,
172
173
              last = last,
              seed = seed,
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
174
              in.memory = in.memory,
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
              init.seed = init.seed,
              save_runs = save_runs,
              parallel_mode = parallel_mode,
              max_num_cores = max_num_cores
            )
            returns <- maFo_rf$returns
            index <- maFo_rf$index
            num_models <- maFo_rf$num_models
            acc <- maFo_rf$acc
            maFo_rf <- maFo_rf$obj
            if (returns == 1) {
              decision3 <-
                readline(
                  paste(
                    "No Models - Adjust init.samples (actual: ",
                    init.samples,
                    "), abort (0) or auto (1) [.. or 0 or 1]:  ",
                    sep = ""
                  )
                )
              if (decision3 == "0") {
                print("User decided to abort the classification.")
                return(NULL)
              } else if (decision3 == "1") {
                init.samples <- init.samples + 50
              } else {
                init.samples <- as.numeric(decision3)
              }
            } else if (returns == 2) {
              decision3 <-
                readline(
                  paste(
                    "No optimal classifier - Adjust init.samples/nb.models (actual ",
                    init.samples,
                    "/",
                    nb_models,
                    "), abort (0) or auto (1) [../.. or 0 or 1]:  ",
                    sep = ""
                  )
                )
              if (decision3 == "0") {
                print("User decided to abort the classification.")
                return(NULL)
              } else if (decision3 == "1") {
                init.samples <- init.samples + 50
                nb_models <- nb_models + 15
              } else {
                init.samples <- as.numeric(strsplit(decision3, split = "/")[[1]][1])
                nb_models <-
                  as.numeric(strsplit(decision3, split = "/")[[1]][2])
              }
            }
          }
228
229
230
231
232
233
          ########################
          maFo[[rs]] <- maFo_rf
          test[[rs]] <- maFo_rf@layer[[1]]
          new.names[[rs]] <- index
          new.acc[[rs]] <- acc
          if (rs == multiTest) {
234
235
236
237
238
239
240
241
242
243
244
245
246
            if (plot_on_browser == TRUE) {
              if (.Platform$OS.type == "unix") {
                grDevices::x11()
              } else {
                grDevices::windows()
              }
              attach(mtcars)
              if (multiTest < 4) {
                par(mfrow = c(multiTest, 1))  
              } else {
                par(mfrow = c(round(multiTest/4), multiTest %% 4))
              }
            }
247
248
            par(mar = c(2, 2, 2, 3), mfrow = n2mfrow(multiTest))
            for (rr in 1:length(test)) {
249
250
251
              if (plot_on_browser == FALSE) {
                png(file = paste(outPath, 'multi_', rr, '.png', sep = ""), width = 600, height = 500, res = 72)
              }
252
              raster::plot(
253
254
255
256
257
                test[[rr]],
                col = col(200),
                main = "",
                legend.shrink = 1)
              mtext(side = 3,
258
                    paste('Test ', rr, '- class ', classNames[new.names[[rr]]], sep = " "),
259
                    font = 2)
260
261
262
263
              if (plot_on_browser == FALSE) {
                dev.off()
                IRdisplay::display_png(file = paste(outPath, 'multi_', rr, '.png', sep = ""))
              }
264
265
266
267
            }
          }
        }
        decision <-
268
          readline("Which distribution is acceptable or sample again (0) [.. or 0]:  ")
269
270
271
272
273
274
275
276
277
        if (plot_on_browser == FALSE) {
          for (rr in 1:length(test)) {
            fn <- paste(outPath, 'multi_', rr, '.png', sep = "")
            if (file.exists(fn)) {
              #Delete file if it exists
              file.remove(fn)
            }
          }
        }
278
279
280
281
      }
      maFo_rf <- maFo[[as.numeric(decision)]]
      index <- new.names[[as.numeric(decision)]]
      acc <- new.acc[[as.numeric(decision)]]
282
283
284
      remove(maFo)
      remove(new.names)
      remove(new.acc)
285
286
287
      ##########################################################################
    } else{
      ########################
288
289
290
291
292
293
294
295
296
297
298
299
300
      returns <- 1
      while (returns != 0) {
        decision3 <- ""
        maFo_rf <- sample_nb(
          raster = in.raster,
          nb_samples = seq(init.samples, init.samples, init.samples),
          sample_type = sample_type,
          nb_mean = nb_models,
          nb_it = nb_it,
          buffer = buffer,
          reference = reference,
          model = model,
          mtry = mtry,
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
301
          mod.error = mod.error,
302
303
304
          last = last,
          seed = seed,
          init.seed = init.seed,
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
305
          in.memory = in.memory,
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
          save_runs = save_runs,
          parallel_mode = parallel_mode,
          max_num_cores = max_num_cores
        )
        returns <- maFo_rf$returns
        index <- maFo_rf$index
        num_models <- maFo_rf$num_models
        acc <- maFo_rf$acc
        maFo_rf <- maFo_rf$obj
        if (returns == 1) {
          decision3 <-
            readline(
              paste(
                "No Models - Adjust init.samples (actual: ",
                init.samples,
                "), abort (0) or auto (1) [.. or 0 or 1]:  ",
                sep = ""
              )
            )
          if (decision3 == "0") {
            print("User decided to abort the classification.")
            return(NULL)
          } else if (decision3 == "1") {
            init.samples <- init.samples + 50
          } else {
            init.samples <- as.numeric(decision3)
          }
        } else if (returns == 2) {
          decision3 <-
            readline(
              paste(
                "No optimal classifier - Adjust init.samples/nb.models (actual ",
                init.samples,
                "/",
                nb_models,
                "), abort (0) or auto (1) [../.. or 0 or 1]:  ",
                sep = ""
              )
            )
          if (decision3 == "0") {
            print("User decided to abort the classification.")
            return(NULL)
          } else if (decision3 == "1") {
            init.samples <- init.samples + 50
            nb_models <- nb_models + 15
          } else {
            init.samples <- as.numeric(strsplit(decision3, split = "/")[[1]][1])
            nb_models <-
              as.numeric(strsplit(decision3, split = "/")[[1]][2])
          }
        }
      }
358
359
360
361
    }
    dummy <- maFo_rf@layer[[1]]
    iplot(
      x = dummy,
362
      y = input_raster,
363
364
365
366
      HaTy = classNames[index],
      r = RGB[1],
      g = RGB[2],
      b = RGB[3],
367
      num_models = num_models,
368
      nb_models = nb_models,
369
      acc = acc,
370
      color = color,
371
372
      outPath = outPath,
      plot_on_browser = plot_on_browser
373
374
375
    )

    decision <-
376
      readline("Threshold for Habitat Extraction or Sample Again (0) [.. or 0]:  ")
377
378
379
380

    sample2 <- init.samples
    models2 <- nb_models
    while (decision == "0") {
381
      remove(maFo_rf)
382
383
384
385
386
387
388
389
390
391
392
393
394
395
      decision2 <- readline(paste("Adjust init.samples/nb.models (actual ",
                                  sample2,
                                  "/",
                                  models2,
                                  "), auto (0), or same (1) [../.. or 0 or 1]:  ",
                                  sep = ""))
      if (decision2 != "1") {
        if (decision2 == "0") {
          sample2 <- sample2 + 50
          models2 <- models2 + 15
        } else {
          sample2 <- as.numeric(strsplit(decision2, split = "/")[[1]][1])
          models2 <- as.numeric(strsplit(decision2, split = "/")[[1]][2])
        }
396
      }
397
398
399
400
401
402
403
404
405
406
407
408
409
      returns <- 1
      while (returns != 0) {
        decision3 <- ""
        maFo_rf <- sample_nb(
          raster = in.raster,
          nb_samples = seq(sample2, sample2, sample2),
          sample_type = sample_type,
          nb_mean = models2,
          nb_it = nb_it,
          buffer = buffer,
          reference = reference,
          model = model,
          mtry = mtry,
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
410
          mod.error = mod.error,
411
412
413
          last = last,
          seed = seed,
          init.seed = init.seed,
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
414
          in.memory = in.memory,
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
          save_runs = save_runs,
          parallel_mode = parallel_mode,
          max_num_cores = max_num_cores
        )
        returns <- maFo_rf$returns
        index <- maFo_rf$index
        num_models <- maFo_rf$num_models
        acc <- maFo_rf$acc
        maFo_rf <- maFo_rf$obj
        if (returns == 1) {
          decision3 <-
            readline(
              paste(
                "No Models - Adjust init.samples (actual: ",
                init.samples,
                "), abort (0) or auto (1) [.. or 0 or 1]:  ",
                sep = ""
              )
            )
          if (decision3 == "0") {
            print("User decided to abort the classification.")
            return(NULL)
          } else if (decision3 == "1") {
            sample2 <- sample2 + 50
          } else {
            sample2 <- as.numeric(decision3)
          }
        } else if (returns == 2) {
          decision3 <-
            readline(
              paste(
                "No optimal classifier - Adjust init.samples/nb.models (actual ",
                sample2,
                "/",
                models2,
                "), abort (0) or auto (1) [../.. or 0 or 1]:  ",
                sep = ""
              )
            )
          if (decision3 == "0") {
            print("User decided to abort the classification.")
            return(NULL)
          } else if (decision3 == "1") {
            sample2 <- sample2 + 50
            models2 <- models2 + 15
          } else {
            sample2 <- as.numeric(strsplit(decision3, split = "/")[[1]][1])
            models2 <-
              as.numeric(strsplit(decision3, split = "/")[[1]][2])
          }
        }
466
467
468
469
      }
      dummy <- maFo_rf@layer[[1]]
      iplot(
        x = dummy,
470
        y = input_raster,
471
472
473
474
        HaTy = classNames[index],
        r = RGB[1],
        g = RGB[2],
        b = RGB[3],
475
        num_models = num_models,
476
        nb_models = nb_models,
477
        acc = acc,
478
        color = color,
479
480
        outPath = outPath,
        plot_on_browser = plot_on_browser
481
482
483
      )

      decision <-
484
        readline("Threshold for Habitat Extraction or Sample Again (0) [.. or 0]:  ")
carstennh's avatar
carstennh committed
485
    }
486
487
488
489
490
491

    if (i < 10) {
      ni <- paste("0", i, sep = "")
    } else{
      ni <- i
    }
492
493
494

    if ( save_runs == TRUE) {
      run1 <- maFo_rf
495
      save_run(outPath = outPath, step = ni, run1 = run1)
496
497
      remove(run1)
    }
498
 
499
500
501
502
503
504
    save_class_tiff(outPath,
                    ni,
                    classNames,
                    index,
                    dummy,
                    overwrite)
505

506
507
508
509
    save_kml(outPath,
             ni,
             dummy,
             overwrite)
510
511

    thres <- as.numeric(decision)
512
    thres <- thres + num_models
513
514
    dummy[dummy < thres] <- 1
    dummy[dummy >= thres] <- NA
515
    in.raster <- in.raster * dummy
516
517
    reference <- reference[-index,]
    classNames <- classNames[-index]
518
519
520
    out.reference <<- reference
    out.names <<- classNames
    out.raster <<- in.raster
521
    remove(dummy)
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
522
    remove(maFo_rf)
523
    
524
525
526
527
528
529
530
    print(paste(paste("Habitat", i), "Done"))

    colnames(reference)  <-  names(in.raster)
    if (i == 1) {
      threshold  <- thres
      save(threshold,
           file = paste(outPath,
531
                        paste("threshold_step_", ni, sep = ""),
532
533
534
535
536
537
538
539
                        sep = ""))
    } else {
      threshold <- append(threshold, thres)
      save(threshold,
           file = paste(outPath,
                        paste("threshold_step_", ni, sep = ""),
                        sep = ""))
    }
540
    # Release memory
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
541
    gc(full = TRUE)
542

543
544
545
546
547
    if (i == r) {
      print("Congratulation - you finally made it towards the last habitat")
      break()
    }

548
549
550
551
552
553
554
555
556
    num_habitat <- i + 1
    print(paste("Habitat", num_habitat, "Starting", sep = " "))
    flush(stdout())
    decision2 <- readline(paste("Adjust init.samples/nb.models (actual ",
                                init.samples,
                                "/",
                                nb_models,
                                "), auto (0), or same (1) [../.. or 0 or 1]:  ",
                                sep = ""))
557

558
559
560
561
562
563
564
565
    if (decision2 != "1") {
      if (decision2 == "0") {
        init.samples <- init.samples + 50
        nb_models <- nb_models + 15
      } else {
        init.samples <- as.numeric(strsplit(decision2, split = "/")[[1]][1])
        nb_models <- as.numeric(strsplit(decision2, split = "/")[[1]][2])
      }
566
567
    }
  }
carstennh's avatar
carstennh committed
568
}