将 accelerate 的 A 数组表示转换为 repa 的 U 数组表示

Converting accelerate's A array representation to repa's U array representation

我想将加速数组转换为 repa 数组,然后使用 repa-io 中的 writeImageToBMP 将数组写入 BMP 文件。忽略accelerate-io中存在这样一个函数的事实,我只是用它作为问题的例子。取:

{-# LANGUAGE ScopedTypeVariables #-}
import qualified Data.Array.Accelerate.Interpreter as A (run)
import Data.Array.Accelerate
import qualified Data.Array.Accelerate as A
import qualified Data.Array.Accelerate.IO as A
import qualified Data.Array.Repa as Repa
import qualified Data.Array.Repa.IO.BMP as Repa
import GHC.Word

main :: IO ()
main = do
  let accelArr = A.fromList
                 (Z :. (2::Int) :. (1::Int))
                 ([(1,2,3),(4,5,6)] :: [(Word8,Word8,Word8)])
      computation :: A.Acc (A.Array A.DIM2 (Word8,Word8,Word8))
      computation = A.map
       (\triple ->
           let (r',g',b') = unlift triple :: (Exp Word8,Exp Word8,Exp Word8)
           in lift (constant 0,g',b')) (use accelArr)
      repaArr :: Repa.Array A.A Repa.DIM2 (Word8,Word8,Word8)
      repaArr = A.toRepa (A.run computation)
  Repa.writeImageToBMP "out_repa.bmp" repaArr

编译此代码需要包 accelerate、accelerate-io、repa 和 repa-io。

这不会编译,因为 repa-io 中 writeImageToBmp 的类型是:

writeImageToBMP
  :: FilePath
  -> Repa.Array Repa.U Repa.DIM2 (Word8, Word8, Word8)
  -> IO ()

其中U表示repa中的清单数组。 GHC 错误是:

Couldn't match type ‘A.A’ with ‘Repa.U’
Expected type: Repa.Array Repa.U Repa.DIM2 (Word8, Word8, Word8)
  Actual type: Repa.Array A.A Repa.DIM2 (Word8, Word8, Word8)
In the second argument of ‘Repa.writeImageToBMP’, namely ‘repaArr’
In a stmt of a 'do' block:
  Repa.writeImageToBMP "out_repa.bmp" repaArr

repaArr的类型是:

Repa.Array A.A Repa.DIM2 (Word8,Word8,Word8)

这就是为什么 GHC 抱怨它是 writeImageToBMP 的论点。

问题:如何将加速数组表示A转换为repa清单数组表示U,以便调用writeImageToBMP 就可以了吗?

请注意函数 computeScomputePcopyS Data.Array.Repa 中的 copyP 有这种签名:

...constraints... => Array r1 sh e -> m (Array r2 sh e)

因此它们是允许您在不同 Repa 表示之间进行转换的函数(即转换 r1 -> r2)。

考虑到这一点,我得到了这段代码来进行类型检查:

main :: IO ()
main = do
  let accelArr = A.fromList
                 (Z :. (2::Int) :. (1::Int))
                 ([(1,2,3),(4,5,6)] :: [(Word8,Word8,Word8)])
      computation :: A.Acc (A.Array A.DIM2 (Word8,Word8,Word8))
      computation = A.map
       (\triple ->
           let (r',g',b') = unlift triple :: (Exp Word8,Exp Word8,Exp Word8)
           in lift (constant 0,g',b')) (use accelArr)
      repaArr :: Repa.Array A.A Repa.DIM2 (Word8,Word8,Word8)
      repaArr = A.toRepa (A.run computation)
  zzz <- Repa.copyP repaArr
  Repa.writeImageToBMP "out_repa.bmp" zzz

你也可以在这里使用Repa.copyS