outer_procedure.r 20.4 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
14
#' @param mtry number of predictor used at random forest splitting nodes (mtry << n predictors)
#' @param last only true for one class classifier c("FALSE", TRUE")
15
#' @param seed set seed for reproducible results
carstennh's avatar
carstennh committed
16
17
18
#' @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
19
#' @param classNames character vector with class names in the order of reference spectra
carstennh's avatar
carstennh committed
20
21
#' @param n_classes total number of classes (habitat types) to be separated
#' @param multiTest number of test runs to compare different probability outputs
22
#' @param RGB rgb channel numbers for image plot
23
#' @param color color pallet
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
24
#' @param overwrite overwrite the KML and raster files from previous runs (default TRUE)
25
#' @param save_runs an Habitat object is saved into disk for each run (default TRUE)
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
26
27
#' @param parallel_mode run loops using all available cores (default FALSE)
#' @param max_num_cores maximum number of cores for parallelism (default 5)
28
#' @param plot_on_browser plot on the browser or inline in a notebook (default TRUE)
carstennh's avatar
carstennh committed
29
#'
30
#' @return 4 files per step:
Romulo Pereira Goncalves's avatar
Romulo Pereira Goncalves committed
31
#' 1) Habitat type probability map as geocoded *.kmz (with a *.kml layer and *.png image output), and *.tif raster file 
32
#' 2) A Habitat object (only if save_runs is set to TRUE) consisting of 7 slots: \cr
33
34
35
36
37
38
39
40
#' run1@models - list of selcted classifiers \cr
#' 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
41
#'
carstennh's avatar
carstennh committed
42
43
44
45
46
#' @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
47
#' #specify a valid output path e.g.  "C:/Users/.../"
48
49
50
#' 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
51
52
#' multiTest = 1, RGB = c(19, 20, 21))
#' ###################
carstennh's avatar
carstennh committed
53
#' for threshold evaluation an interactive map is plotted in the web browser
carstennh's avatar
carstennh committed
54
55
#'
#' next steps start automatically, after command line input of:
carstennh's avatar
carstennh committed
56
#' 1) number of the apropriate map if multiTest > 1
57
#' 2) probability threshold for habitat type extraction
carstennh's avatar
carstennh committed
58
59
60
#' 3) decision to sample again y/n
#' 4) adjust starting number of samples and number of models
#'
61
62
63
64
65
66
#'
#'
#' 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
67
68
69
#' classNames = out.names
#'
#' @export
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
multi_Class_Sampling <- function(in.raster,
                                 init.samples = 30,
                                 sample_type = "regular",
                                 nb_models = 200,
                                 nb_it = 10,
                                 buffer,
                                 reference,
                                 model = "rf",
                                 mtry = 10,
                                 last = F,
                                 seed = 3,
                                 init.seed = "sample",
                                 outPath,
                                 step = 1,
                                 classNames,
                                 n_classes,
                                 multiTest = 1,
87
                                 RGB = c(19, 20, 21),
88
                                 color = c("lightgrey", "orange", "yellow", "limegreen", "forestgreen"),
89
                                 overwrite = TRUE,
90
                                 save_runs = TRUE,
91
                                 parallel_mode = FALSE,
92
                                 max_num_cores = 5,
93
                                 plot_on_browser = TRUE) {
94

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

115
  input_raster <- in.raster
116
117
  area <- as(raster::extent(in.raster), 'SpatialPolygons')
  area <- sp::SpatialPolygonsDataFrame(area, data.frame(ID = 1:length(area)))
118
  #sp::proj4string(area) <- sp::proj4string(in.raster)
119
  raster::crs(area) <- raster::crs(in.raster)
carstennh's avatar
carstennh committed
120

121
122
123
124
125
  col <- colorRampPalette(c("lightgrey",
                            "orange",
                            "yellow",
                            "limegreen",
                            "forestgreen"))
carstennh's avatar
carstennh committed
126

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
  ##############################################################################
  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
143

144
  print(paste(paste("Habitat", 0), "Starting"))
145
146
147
148
  for (i in step:r) {
    if (i == r) {
      last = T
    }
carstennh's avatar
carstennh committed
149

150
151
152
153
154
155
156
157
158
159
    if (multiTest > 1) {
      test <- list()
      maFo <- list()
      new.names <- list()
      new.acc <- list()
      decision = "0"
      ##########################################################################
      while (decision == "0") {
        for (rs in 1:multiTest) {
          ########################
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
          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,
              area = area,
              mtry = mtry,
              last = last,
              seed = seed,
              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])
              }
            }
          }
229
230
231
232
233
234
          ########################
          maFo[[rs]] <- maFo_rf
          test[[rs]] <- maFo_rf@layer[[1]]
          new.names[[rs]] <- index
          new.acc[[rs]] <- acc
          if (rs == multiTest) {
235
236
237
238
239
240
241
242
243
244
245
246
247
            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))
              }
            }
248
249
            par(mar = c(2, 2, 2, 3), mfrow = n2mfrow(multiTest))
            for (rr in 1:length(test)) {
250
251
252
              if (plot_on_browser == FALSE) {
                png(file = paste(outPath, 'multi_', rr, '.png', sep = ""), width = 600, height = 500, res = 72)
              }
253
              raster::plot(
254
255
256
257
258
                test[[rr]],
                col = col(200),
                main = "",
                legend.shrink = 1)
              mtext(side = 3,
259
                    paste('Test ', rr, '- class ', classNames[new.names[[rr]]], sep = " "),
260
                    font = 2)
261
262
263
264
              if (plot_on_browser == FALSE) {
                dev.off()
                IRdisplay::display_png(file = paste(outPath, 'multi_', rr, '.png', sep = ""))
              }
265
266
267
268
            }
          }
        }
        decision <-
269
          readline("Which distribution is acceptable or sample again (0) [.. or 0]:  ")
270
271
272
273
274
275
276
277
278
        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)
            }
          }
        }
279
280
281
282
      }
      maFo_rf <- maFo[[as.numeric(decision)]]
      index <- new.names[[as.numeric(decision)]]
      acc <- new.acc[[as.numeric(decision)]]
283
284
285
      remove(maFo)
      remove(new.names)
      remove(new.acc)
286
287
288
      ##########################################################################
    } else{
      ########################
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
      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,
          area = area,
          mtry = mtry,
          last = last,
          seed = seed,
          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])
          }
        }
      }
358
    }
carstennh's avatar
carstennh committed
359

360
361
362
    dummy <- maFo_rf@layer[[1]]
    iplot(
      x = dummy,
363
      y = input_raster,
364
365
366
367
      HaTy = classNames[index],
      r = RGB[1],
      g = RGB[2],
      b = RGB[3],
368
      num_models = num_models,
369
      nb_models = nb_models,
370
      acc = acc,
371
      color = color,
372
373
      outPath = outPath,
      plot_on_browser = plot_on_browser
374
375
376
    )

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

    sample2 <- init.samples
    models2 <- nb_models
    while (decision == "0") {
382
      remove(maFo_rf)
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
      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])
        }
      }
      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,
          area = area,
          mtry = mtry,
          last = last,
          seed = seed,
          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") {
            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
      }
carstennh's avatar
carstennh committed
467

468
469
470
      dummy <- maFo_rf@layer[[1]]
      iplot(
        x = dummy,
471
        y = input_raster,
472
473
474
475
        HaTy = classNames[index],
        r = RGB[1],
        g = RGB[2],
        b = RGB[3],
476
        num_models = num_models,
477
        nb_models = nb_models,
478
        acc = acc,
479
        color = color,
480
481
        outPath = outPath,
        plot_on_browser = plot_on_browser
482
483
484
      )

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

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

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

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

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

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

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

549
550
551
552
553
554
555
556
557
    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 = ""))
558

559
560
561
562
563
564
565
566
    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])
      }
567
568
    }
  }
carstennh's avatar
carstennh committed
569
}