簡體   English   中英

使用rpy2在python中進行R聚集

[英]R clump within python with rpy2

我的具體問題就是標題。 我在python中有一個大型的柵格處理腳本,並且需要執行我在gdal / python中找不到的叢集函數,也沒有想出如何自己“編寫”它。 我一直都在使用python不斷變得更好,但是正在為該任務學習R。 (已安裝R版本3.4.1(2017-06-30))

花一點時間學習R之后,我就能在python中安裝rpy2,並且通過Stackoverflow的幫助,我已經能夠執行rpy2的多個“測試”。 使rpy2響應最有用的信息是確定R在python會話或腳本中的位置。 從另一個堆棧答案。 如下:

import os
os.environ['PYTHONHOME'] = r'C:\Python27\ArcGIS10.3\Scripts\new_ve_folder\Scripts'
os.environ['PYTHONPATH'] = r'C:\Python27\ArcGIS10.3\Scripts\new_ve_folder\Lib\site-packages'
os.environ['R_HOME'] = r'C:\Program Files\R\R-3.4.1'
os.environ['R_USER'] = r'C:\Python27\ArcGIS10.3\Scripts\new_ve_folder\Lib\site-packages\rpy2'

但是,文檔http://rpy.sourceforge.net/rpy2/doc-2.1/html/overview.html中列出的主要測試我無法使用。

import rpy2.robjects.tests
import unittest

# the verbosity level can be increased if needed
tr = unittest.TextTestRunner(verbosity = 1)
suite = rpy2.robjects.tests.suite()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  AttributeError: 'module' object has no attribute 'suite'

然而:

import rpy2.robjects as robjects
pi = robjects.r['pi']
pi[0]

效果很好。 就像我發現的其他一些rpy2.robjects測試一樣。 我可以創建字符串='''f <-函數ect'''並從python調用它們。

如果我使用:

python -m 'rpy2.tests'

我收到以下錯誤。 r \\ Scripts> python -m'rpy2.tests'r \\ Scripts \\ python.exe:沒有名為'rpy2的模塊

文檔說明:在Python 2.6上,這應該返回所有測試均已成功。 我正在使用Python 2.7,並且也在Python 3.3中進行了嘗試。

我的叢集腳本如下所示:我不想每次運行腳本時都必須實際安裝軟件包名稱,因為它們已經安裝在R Home中。 如果可能,我想使用我的python變量。

我需要弄清楚為什么rpy2沒有按照文檔中的說明進行響應,或者為什么我會出錯。 然后,找出正確的方法來編寫我的python腳本的聚集部分。

packageNames = ('raster', 'rgdal')
if all(rpackages.isinstalled(x) for x in packageNames):
    have_packages = True
else:
   have_packages = False
if not have_packages:
    utils = rpackages.importr('utils')
    utils.chooseCRANmirror(ind=1)
    packnames_to_install = [x for x in packageNames if not     rpackages.isinstalled(x)]
    if len(packnames_to_install) > 0:
        utils.install_packages(StrVector(packnames_to_install))

from rpy2.robjects.packages import importr
import rpy2.robjects as robjects

我發現有幾種方法可以從R調用柵格和叢集選項,但是,如果我無法使rpy2正確響應,那么我將根本無法使它們起作用。但是由於其他一些測試有效,因此我並不滿意。

raster = robjects.r['raster'] 
raster = importr('raster')   
clump = raster.clump
clump = robjects.r.clump
type(raster.clump)

tempDIR = r"C:\Users\script_out\temp"
slope_recode = os.path.join(tempDIR, "step2b_input.img")
outfile = os.path.join(tempDIR, "Rclumpfile.img")

raster.clump(slope_recode, filename=outfile, direction=4, gaps=True, format='HFA', overwrite=True)

這會導致大量錯誤。

Traceback (most recent call last):
  File "C:/Python27/ArcGIS10.3/Scripts/new_ve_folder/Scripts/rpy2_practice.py", line 97, in <module>
      raster.clump(slope_recode, filename=outfile, direction=4, gaps=True, format='HFA', overwrite=True)
  File "C:\Python27\ArcGIS10.3\Scripts\new_ve_folder\lib\site-packages\rpy2\robjects\functions.py", line 178, in __call__
      return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "C:\Python27\ArcGIS10.3\Scripts\new_ve_folder\lib\site-packages\rpy2\robjects\functions.py", line 106, in __call__
      res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in (function (classes, fdef, mtable)  : 
      unable to find an inherited method for function 'clump' for signature '"character"'

問題:在命令行和腳本中測試rpy2(都會產生錯誤,但是我仍然能夠使用基本的rpy2

導入R軟件包,以免每次都安裝它們

終於讓我的叢集腳本正確調用了

如果我錯過了一些基本的知識,請指出正確的方向。 謝謝大家

對於第一個問題,將suite = rpy2.robjects.tests.suite()替換為suite = rpy2.tests.suite()

對於你的第三個問題(讓clump正常工作),你需要創建一個RasterLayer使用圖像中的R對象。 我對raster包不熟悉,因此無法給您確切的步驟。

我將指出arcpy模塊不是 “ pythonic”的。 通常,文件名字符串只是Python中的字符串。 使用純字符串表示諸如地圖圖層之類的對象時, arcpy很奇怪。

在您的示例中, slope_recode只是一個字符串。 這就是為什么出現錯誤, unable to find an inherited method for function 'clump' for signature '"character"' 這意味着slope_recode傳遞給R作為一個字符值(它是),並且clump函數需要RasterLayer對象。 它不知道如何處理字符值。

我將所有這些都與下面的代碼一起使用。

    import warnings
    os.environ['PATH'] =       os.path.join(scriptPath, 'path\\my_VE\\R\\R-3.4.2\\bin\\x64')
    os.environ['PYTHONHOME'] = os.path.join(scriptPath, 'path\\my_VE\\Scripts\\64bit')
    os.environ['PYTHONPATH'] = os.path.join(scriptPath, 'path\\my_VE\\Lib\\site-packages')
    os.environ['R_HOME'] =     os.path.join(scriptPath, 'path\\my_VE\\R\\R-3.4.2')
    os.environ['R_USER'] =     os.path.join(scriptPath, 'path\\my_VE\\Scripts\\new_ve_folder\\Scripts\\rpy2')
    #
    import platform
    z = platform.architecture()
    print(z)
    ## above will confirm you are working on 64 bit
    gc.collect()
    ## this code snippit will tell you which library is being Read
    command = 'Rscript'
    cmd = [command, '-e', ".libPaths()"]
    print(cmd)
    x = subprocess.Popen(cmd, shell=True)
    x.wait()

    import rpy2.robjects.packages as rpackages
    import rpy2.robjects as robjects
    from rpy2.robjects import r
    import rpy2.interactive.packages
    from rpy2.robjects import lib
    from rpy2.robjects.lib import grid
    # # grab r packages
    print("loading packages from R")
    ## fails at this point with the following error
    ##  Error: cannot allocate vector of size 232.6 Mb when working with large rasters
    rpy2.robjects.packages.importr('raster')
    rpy2.robjects.packages.importr('rgdal')
    rpy2.robjects.packages.importr('sp')
    rpy2.robjects.packages.importr('utils')
    # rpy2.robjects.packages.importr('memory')
    # rpy2.robjects.packages.importr('dplyr')
    rpy2.robjects.packages.importr('data.table')
    grid.activate()
    # set python variables for R code names
    raster = robjects.r['raster']
    writeRaster = robjects.r['writeRaster']
    # setwd = robjects.r['setwd']
    clump = robjects.r['clump']
    # head = robjects.r['head']
    crs = robjects.r['crs']
    dim = robjects.r['dim']
    projInfo = robjects.r['projInfo']
    slope_recode = os.path.join(tempDIR, "_lope_recode.img")
    outfile = os.path.join(tempDIR, "Rclumpfile.img")
    recode = raster(slope_recode)  # this is taking the image and                            reading it into R raster package
    ## https://stackoverflow.com/questions/47399682/clear-r-memory-using-rpy2
    gc.collect()  # No noticeable effect on memory usage
    time.sleep(2)
    gc.collect()  # Finally, memory usage drops
    R = robjects.r
    R('memory.limit()')
    R('memory.limit(size = 65535)')
    R('memory.limit()')

    print"starting Clump with rpy2"
    clump(recode, filename=outfile, direction=4, gaps="True", format="HFA")

    final = raster(outfile)
            final = crs("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0,-0,-0,-0,0 +no_defs")

    print ("clump file created, CRS accurate, next step")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM