【问题标题】:How to show the progress bar in raster calc function?如何在光栅计算功能中显示进度条?
【发布时间】:2016-10-28 03:08:04
【问题描述】:

如何在为用于 calc raster 函数而编写的函数中使用像 this example 这样的进度条?

我有一个庞大的数据集要处理,我希望使用进度条来控制处理的持续时间。我试着像这样使用,(进程的)功能完美地工作,但是,不显示进度条。

# PROGRESS BAR IN CALC RASTER EXAMPLE
# create data
r <- raster(nrow=10, ncol=10) 
dataset <- list() 
for (i in 1:20) { 
    dataset[i] <- setValues(r, rnorm(ncell(r), i, 3) ) 
} 
dataset <- stack(dataset)

## function to apply
pixel <-getValuesBlock(s1, row=1, nrows=1, col=1, ncols=1, lyrs=1:nlayers(s1))
CropAnalysis <- function (pixel, ...){
 gc()
 pb <- txtProgressBar(...)
 # test : if is No data the return is 
 if (identical(x = is.na(pixel), y = rep(TRUE,length(pixel)))) {NA}else{
 averageOfhigher <- mean(pixel[pixel > 10], na.rm=T)
 averageOflower <- mean(pixel[pixel < 10], na.rm=T)
 return(c(averageOfhigher, averageOflower))
 }
 setTxtProgressBar(pb)}

 # applying calc finction
 data_process<-calc(x=dataset, fun=CropAnalysis, forcefun=TRUE, forceapply=TRUE)

【问题讨论】:

    标签: r progress-bar r-raster calc


    【解决方案1】:

    您可以使用progress 参数,该参数内置于raster 包中的大多数函数中。只有分块写入时才会显示(因为数据集很大)。

    # example data
    library(raster)
    r <- raster(nrow=10, ncol=10) 
    d <- stack(lapply(1:20, function(i) setValues(r, rnorm(ncell(r), i, 3) )) )
    
    f  <- function(pixel, ...){
         if (all(is.na(pixel))) {
            c(NA, NA) # note the two NAs to match the other case 
         } else {
            averageOfhigher <- mean(pixel[pixel > 10], na.rm=TRUE)
            averageOflower <- mean(pixel[pixel < 10], na.rm=TRUE)
            c(averageOfhigher, averageOflower)
         }
      }
    

    不要在脚本中使用下面的行。只需要在这个 玩具示例触发分块写入,以便出现进度条

    rasterOptions(todisk=TRUE)  
    

    但请务必使用progress 参数(“文本”或“窗口”)

    r <- calc(d, fun=f, progress='text')
    

    【讨论】:

    • 嗨@RobertH,我采纳了你的建议,没有进度条,只有进度的开始和结束。如何解决这个问题?
    • 表示数据不多。您可以在 rasterOptions 中设置较小的块大小以获得更多步骤(但这可能会减慢速度)
    • 当我使用 progress="text" 时,控制台始终只显示“| |0%”,但是,当我应用 progress="window" 时,会显示来自 tcltk 包的窗口作为进度。
    【解决方案2】:

    一个简单的解决方案
    您可以使用 raster 包中内置的 rasterOptions 函数。
    举个例子 rasterOptions(progress = 'text',timer=TRUE) 将向您显示进度,如您展示的示例,以及光栅包中每个使用的功能的时间。
    查看此链接以获取更多高级选项: https://rdrr.io/cran/raster/man/rasterOptions.html

    【讨论】:

      猜你喜欢
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多