将数组从 .npy 文件读入 Fortran 90

2024-05-10

我使用 Python 以二维数组(例如“X”)的形式生成一些初始数据,然后使用 Fortran 对它们进行一些计算。最初,当数组大小约为 10,000 x 10,000 时,np.savetxt 在速度方面表现良好。但是一旦我开始增加数组的维度,savetxt 的速度就会显着减慢。所以我尝试了 np.save ,这导致保存速度更快,但文件以 .npy 格式保存。我将如何在 Fortran 中读取这样的文件来重建原始数组?据我所知,二进制通常会带来最低的空间消耗和最快的速度。

在 Fortran 90 中,

open(10,file='/home/X.npy')

read(10,*)X

我收到以下错误:Fortran 运行时错误:列表输入的第 1 项中的实数错误

编辑 : 在Python中我这样做,

import numpy as np 
x = np.linspace(-50,50,10)
y = np.linspace(-50,50,10) 
X,Y = np.meshgrid(x,y) 
np.save('X',X) 

然后在 Fortran 中我这样做,

program read_unformatted_binary_from_python
    use iso_c_binding
    implicit none

    integer, parameter :: DPR = selected_real_kind(p=15)
    character(len=*), parameter :: filename = 'X.npy'

    integer, parameter :: N = 10
    real(DPR), allocatable, dimension(:, :) :: X

    allocate(X(N, N))


    open(40, file=filename, status='old', access='stream', form='unformatted')
    read(40) X
    close(40)

    write(*,*) X

end program read_unformatted_binary_from_python

输出以 1.8758506894003703E-309 1.1711999948023422E+171 5.2274167985502976E-037 8.4474009688929314E+252 2.6514123210345660E+1 开头80 9.9215260506210473E+247 2.1620996769994603E+233 7.5805790251297605E-096 3.4756671925988047E-152 6.5549091408576423E-260 - 50.000000000000000 -38.888888888888886 -27.777777777777779等等

使用 .bin 格式时不会发生此错误,仅在使用 np.save 生成​​ npy 时发生。


Vladimir F 是正确的,您希望在 Fortran 中“流”访问“原始二进制”文件。这是一个 MWE:

Python

import numpy as np
A = np.random.rand(10000, 10000)
print(A.sum())
A.tofile('data.bin')

Fortran

program read_unformatted_binary_from_python
    use iso_c_binding
    implicit none

    integer, parameter :: DPR = selected_real_kind(p=15)
    character(len=*), parameter :: filename = 'data.bin'

    integer, parameter :: N = 10000
    real(DPR), allocatable, dimension(:, :) :: dat

    allocate(dat(N, N))

    open(40, file=filename, status='old', access='stream', form='unformatted')
    read(40) dat
    close(40)

    write(*,*) sum(dat)

end program read_unformatted_binary_from_python

我的 Fortran 示例可能比必要的要长一些,因为我使用许多不同的系统和编译器套件,并且也讨厌大型静态数组(毕竟我是 Fortran 用户)。

我在 MacBook Pro 上使用 Homebrew GCC 6.3.0_1 中的 Python 2.7.x、Numpy 13.x 和 gfortran 快速编写了此代码,但这应该适用于所有系统。

更新: 这里需要特别注意数组的形状和大小。如果dat分配的大小大于文件中的大小,大于流的大小read应该尝试填充整个数组,点击EOF符号,并发出错误。在 Python 中,np.fromfile()方法将读取到EOF然后返回一个具有适当长度的一维数组,即使A原本是多维的。这是因为原始二进制文件没有元数据,只是 RAM 中的连续字节字符串。

结果,Python 中的以下几行生成相同的文件:

A = np.random.rand(10000, 10000)
A.tofile('file.whatever')
A.ravel().tofile('file.whatever')
A.reshape((100, 1000, 1000)).tofile('file.whatever')

该文件可以被读入并重塑为:

B = np.fromfile('file.whatever').reshape(A.shape)
B = np.fromfile('file.whatever').reshape((100, 1000, 100, 10))
# or something like
B = np.fromfile('file.whatever') # just a 1D array
B.resize(A.shape)  # resized in-place

在 Fortran 中,使用流访问很容易读取整个原始文件,而无需提前知道其大小,尽管您显然需要某种用户输入来重塑数据:

program read_unformatted_binary_from_python
    use iso_c_binding
    implicit none

    integer, parameter :: DPR = selected_real_kind(p=15)
    character(len=*), parameter :: filename = 'data.bin'
    integer :: N = 10000, bytes, reals, M
    real(DPR), allocatable :: A(:,:), D(:, :), zeros(:)
    real(DPR), allocatable, target :: B(:)
    real(DPR), pointer :: C(:, :)

    allocate(A(N, N))

    open(40, file=filename, status='old', access='stream', form='unformatted')

    read(40) A
    write(*,*) 'sum of A', sum(A)

    inquire(unit=40, size=bytes)
    reals = bytes/8
    allocate(B(reals))

    read(40, pos=1) B
    write(*,*) 'sum of B', sum(B)

    ! now reshape B in-place assuming the user wants the first dimension 
    ! (which would be the outer dimension in Python) to be length 100
    N = 100
    if(mod(reals, N) == 0) then
         M = reals/N
         call C_F_POINTER (C_LOC(B), C, [N, M])
         write(*, *) 'sum of C', sum(C)
         write(*, *) 'shape of C', shape(C)
    else
         write(*,*) 'file size is not divisible by N!, did not point C to B'
    end if

    ! now reshape B out-of-place with first dimension length 9900, and
    ! pad the result so that there is no size mismatch error  
    N = 9900
    M = reals/N
    if(mod(reals, N) > 0) M=M+1

    allocate(D(N, M))
    allocate(zeros(N), source=real(0.0, DPR))
    D = reshape(B, [N, M], pad=zeros)

    write(*,*) 'sum of D', sum(D)
    write(*,*) 'shape of D', shape(D)

    ! obviously you can also work with shape(A) in fortran the same way you
    ! would use A.shape() in Python, if you already knew that A was the
    ! correct shape of the data
    deallocate(D)
    allocate(D, mold=A)
    D = reshape(B, shape(A))
    write(*,*) 'sum of D', sum(D)
    write(*,*) 'shape of D', shape(D)

    ! or, just directly read it in, skipping the whole reshape B part
    read(40, pos=1) D
    write(*,*) 'sum of D', sum(D)

    close(40)

end program read_unformatted_binary_from_python
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将数组从 .npy 文件读入 Fortran 90 的相关文章

  • 将 saxon 与 python 结合使用

    我需要使用 python 处理 XSLT 目前我正在使用仅支持 XSLT 1 的 lxml 现在我需要处理 XSLT 2 有没有办法将 saxon XSLT 处理器与 python 一起使用 有两种可能的方法 设置一个 HTTP 服务 接受
  • 将数据从 python pandas 数据框导出或写入 MS Access 表

    我正在尝试将数据从 python pandas 数据框导出到现有的 MS Access 表 我想用已更新的数据替换 MS Access 表 在 python 中 我尝试使用 pandas to sql 但收到错误消息 我觉得很奇怪 使用 p
  • OpenCV Python cv2.mixChannels()

    我试图将其从 C 转换为 Python 但它给出了不同的色调结果 In C Transform it to HSV cvtColor src hsv CV BGR2HSV Use only the Hue value hue create
  • 为 Anaconda Python 安装 psycopg2

    我有 Anaconda Python 3 4 但是每当我运行旧代码时 我都会通过输入 source activate python2 切换到 Anaconda Python 2 7 我的问题是我为 Anaconda Python 3 4 安
  • Django:按钮链接

    我是一名 Django 新手用户 尝试创建一个按钮 单击该按钮会链接到我网站中的另一个页面 我尝试了一些不同的例子 但似乎没有一个对我有用 举个例子 为什么这不起作用
  • 使用 matplotlib 绘制时间序列数据并仅在年初显示年份

    rcParams date autoformatter month b n Y 我正在使用 matpltolib 来绘制时间序列 如果我按上述方式设置 rcParams 则生成的图会在每个刻度处标记月份名称和年份 我怎样才能将其设置为仅在每
  • 从字符串中删除识别的日期

    作为输入 我有几个包含不同格式日期的字符串 例如 彼得在16 45 我的生日是1990年7月8日 On 7 月 11 日星期六我会回家 I use dateutil parser parse识别字符串中的日期 在下一步中 我想从字符串中删除
  • JavaScript 中的埃拉托斯特尼筛法对大量数据无限运行

    我一直在尝试写埃拉托斯特尼筛法 http en wikipedia org wiki Sieve of EratosthenesJavaScript 中的算法 基本上我只是按照以下步骤操作 创建从 2 到 n 1 的连续整数列表 令第一个素
  • 基于代理的模拟:性能问题:Python vs NetLogo & Repast

    我正在 Python 3 中复制一小段 Sugarscape 代理模拟模型 我发现我的代码的性能比 NetLogo 慢约 3 倍 这可能是我的代码的问题 还是Python的固有限制 显然 这只是代码的一个片段 但 Python 却花费了三分
  • 以编程方式停止Python脚本的执行? [复制]

    这个问题在这里已经有答案了 是否可以使用命令在任意行停止执行 python 脚本 Like some code quit quit at this point some more code that s not executed sys e
  • 如何加速Python中的N维区间树?

    考虑以下问题 给定一组n间隔和一组m浮点数 对于每个浮点数 确定包含该浮点数的区间子集 这个问题已经通过构建一个解决区间树 https en wikipedia org wiki Interval tree 或称为范围树或线段树 已经针对一
  • 绘制方程

    我正在尝试创建一个函数 它将绘制我告诉它的任何公式 import numpy as np import matplotlib pyplot as plt def graph formula x range x np array x rang
  • 从 Laravel 4 输入生成新数组

    我使用 Input all 从动态生成的表单中获取一些输入 我使用 jQuery 来允许用户添加字段 字段名称为 first names last names 和 emails input 变量现在看起来像这样 array size 4 t
  • 如何使用Python创建历史时间线

    So I ve seen a few answers on here that helped a bit but my dataset is larger than the ones that have been answered prev
  • python获取上传/下载速度

    我想在我的计算机上监控上传和下载速度 一个名为 conky 的程序已经在 conky conf 中执行了以下操作 Connection quality alignr wireless link qual perc wlan0 downspe
  • Jupyter Notebook 内核一直很忙

    我已经安装了 anaconda 并且 python 在 Spyder IPython 等中工作正常 但是我无法运行 python 笔记本 内核被创建 它也连接 但它始终显示黑圈忙碌符号 防火墙或防病毒软件没有问题 我尝试过禁用两者 我也无法
  • 对年龄列进行分组/分类

    我有一个数据框说df有一个柱子 Ages gt gt gt df Age 0 22 1 38 2 26 3 35 4 35 5 1 6 54 我想对这个年龄段进行分组并创建一个像这样的新专栏 If age gt 0 age lt 2 the
  • 如何计算 3D 坐标的线性索引,反之亦然?

    如果我有一个点 x y z 如何找到该点的线性索引 i 我的编号方案是 0 0 0 是 0 1 0 0 是 1 0 1 0 是最大 x 维度 另外 如果我有一个线性坐标 i 我如何找到 x y z 我似乎无法在谷歌上找到这个 所有结果都充满
  • 从列表指向字典变量

    假设你有一个清单 a 3 4 1 我想用这些信息来指向字典 b 3 4 1 现在 我需要的是一个常规 看到该值后 在 b 的位置内读写一个值 我不喜欢复制变量 我想直接改变变量b的内容 假设b是一个嵌套字典 你可以这样做 reduce di
  • Python Selenium:如何在文本文件中打印网站上的值?

    我正在尝试编写一个脚本 该脚本将从 tulsaspca org 网站获取以下 6 个值并将其打印在 txt 文件中 最终输出应该是 905 4896 7105 23194 1004 42000 放置的动物 的 HTML span class

随机推荐

  • 打印绘图时 Octave 崩溃

    Solution 根据用户 Andy 在评论中的建议 最新版本的 Octave 目前 octave 4 0 1 rc4 的更新解决了该问题 并且绘图可以另存为 PNG 我有大量数据在 Octave 中绘制 但是当我尝试保存图像时 程序崩溃了
  • 这个记忆的斐波那契函数是如何工作的?

    在我正在做的函数式编程课程的当前练习作业中 我们必须制作给定函数的记忆版本 为了解释记忆化 给出以下示例 fiblist fibm x x lt 0 fibm 0 0 fibm 1 1 fibm n fiblist n 1 fiblist
  • NPM 全局标志在 Windows 上似乎不一致

    从控制台运行 gt npm root g 或者以编程方式 var npm require npm npm load null function err npm npm config set global true npm root 我在 W
  • 如何在android中获取当前一周的所有天数?

    我想在字符串数组中获取本周的所有日期 我怎样才能做到这一点 提前致谢 I think你想要这样的东西 假设你总是想要从星期一开始的几周 以及 MM dd yyyy 的日期格式 DateFormat format new SimpleDate
  • Django - 缺少 1 个必需的位置参数:'request'

    我收到错误 get indiceComercioVarejista 缺少 1 个必需的位置参数 要求 当尝试访问 get indiceComercioVarejista 方法时 我不知道这是怎么回事 views from django ht
  • MySQL REPLACE 在自动递增行中

    假设我有一个 MySQL 表 其中包含三列 id a and b和名为id is an AUTO INCREMENT场地 如果我将如下查询传递给 MySQL 它将正常工作 REPLACE INTO table id a b VALUES 1
  • REST 资源 url 中的查询字符串

    今天 我与一位同事讨论了在 REST URL 中使用查询字符串的问题 举这两个例子 1 http localhost findbyproductcode 4xxheua 2 http localhost findbyproductcode
  • 作为动画的八度情节点

    我有以下八度脚本 TOTAL POINTS 100 figure 1 for i 1 TOTAL POINTS randX rand 1 randY rand 1 scatter randX randY hold on endfor 当我运
  • 将记录转换为序列化表单数据以通过 HTTP 发送

    有没有办法转换此记录 TError record code Word message String end TState record caption String address Cardinal counters TArray
  • Cordova 上的 ClearCookiesAsync()

    我正在尝试使用 wp8 cordova 中的插件来清除 WebBrowser cookie 我已经让它与 JavaScript 进行通信 并且我的 c 文件中有类似这样的内容 using WPCordovaClassLib Cordova
  • bool() 和operator.truth() 有什么区别?

    bool https docs python org 3 library functions html bool and operator truth https docs python org 3 library operator htm
  • 在 Sublime Text 2 状态栏中显示有关当前字符的信息

    我缺少其他文本编辑器经常提供的一项有用功能 在底部状态栏中 它们显示当前字符的 ASCII 和 UTF 代码 当前位置之前或之后的字符 现在不确定 我找不到执行此操作的包或执行此操作的本机功能 感谢您的帮助 我为此制作了一个插件 创建一个a
  • 在 Angular 4 中处理来自 Api 的过期令牌

    我需要帮助来处理我的角度应用程序中的过期令牌 我的 api 已过期 但我的问题是当我忘记注销我的角度应用程序时 一段时间后 我仍然可以访问主页但没有数据 我能做点什么吗 有没有可以处理这个问题的库 或者有什么我可以安装的吗 更好 如果我什么
  • 类型错误:无法读取未定义的属性“长度” - 使用安全帽部署时

    我在尝试在安全帽开发链上部署模拟合约时收到以下错误 我正在关注 使用 JavaScript 学习区块链 Solidity 和全栈 Web3 开发 Patrick Collins 在 FreeCodeCamp YT 频道上的 32 小时课程
  • R Leaflet:添加多边形时传递 popupOptions。

    Within addPolygons 有一个popup参数就像addPopups 功能 区别 我认为 是当弹出窗口创建时addPolygons 可以单击多边形内的任意位置来触发弹出窗口 但是如果addPopups 被使用 单个lng and
  • Java 9 中紧凑字符串和压缩字符串的区别

    有什么优点紧凑的字符串 http openjdk java net jeps 254JDK9 中的压缩字符串 压缩字符串 Java 6 和紧凑字符串 Java 9 都有相同的动机 字符串通常实际上是 Latin 1 因此浪费了一半的空间 和
  • CSS 未使用 req.params 或其他内容加载

    我对节点 表达等非常陌生 我制作了一个博客应用程序 但遇到了问题 我正在使用 mongoose node express 和 ejs 当我打电话时 router get posts function req res Post find fu
  • jQuery - 动画CSS背景大小?

    我正在尝试对背景图像的大小进行动画处理 但它不起作用 从以下代码中知道为什么吗 this animate opacity 1 background size 70px 48px right 39 top 45 250 注意 所有其他属性都可
  • 如何将 Pandas Dataframe 中的字符串转换为字符列表或数组?

    我有一个名为的数据框data 其中一列包含字符串 我想从字符串中提取字符 因为我的目标是对它们进行一次性编码并使之可用于分类 包含字符串的列存储在预测因子如下 predictors pd DataFrame data columns Seq
  • 将数组从 .npy 文件读入 Fortran 90

    我使用 Python 以二维数组 例如 X 的形式生成一些初始数据 然后使用 Fortran 对它们进行一些计算 最初 当数组大小约为 10 000 x 10 000 时 np savetxt 在速度方面表现良好 但是一旦我开始增加数组的维