将数组从 .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 的相关文章

  • Python模块可以访问英语词典,包括单词的定义[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我正在寻找一个 python 模块 它可以帮助我从英语词典中获取单词的定义 当然有enchant 这可以帮助我检查该单词是否存在于英语中
  • 如何迭代按值排序的 Python 字典?

    我有一本字典 比如 a 6 b 1 c 2 我想迭代一下by value 不是通过键 换句话说 b 1 c 2 a 6 最直接的方法是什么 sorted dictionary items key lambda x x 1 对于那些讨厌 la
  • 使用 MacLaurin 展开的 Fortran Sine 函数的微小差异

    我正在用 Fortran 创建一个程序 它接受以弧度表示的 sin x 的 x 然后是要计算的项数 这是我的程序 Sine value using MacLaurin series program SineApprox implicit n
  • 如何使用 Plotly 中的直方图将所有离群值分入一个分箱?

    所以问题是 我可以在 Plotly 中绘制直方图 其中所有大于某个阈值的值都将被分组到一个箱中吗 所需的输出 但使用标准情节Histogram类我只能得到这个输出 import pandas as pd from plotly import
  • Django 模型在模板中不可迭代

    我试图迭代模型以获取列表中的第一个图像 但它给了我错误 即模型不可迭代 以下是我的模型和模板的代码 我只需要获取与单个产品相关的列表中的第一个图像 模型 py class Product models Model title models
  • Pandas 中允许重复列

    我将一个大的 CSV 包含股票财务数据 文件分割成更小的块 CSV 文件的格式不同 像 Excel 数据透视表之类的东西 第一列的前几行包含一些标题 公司名称 ID 等在以下列中重复 因为一家公司有多个属性 而不是一家公司只有一栏 在前几行
  • 忽略 Mercurial hook 中的某些 Mercurial 命令

    我有一个像这样的善变钩子 hooks pretxncommit myhook python path to file myhook 代码如下所示 def myhook ui repo kwargs do some stuff 但在我的例子中
  • 以同步方式使用 FastAPI,如何获取 POST 请求的原始正文?

    在中使用 FastAPIsync not async模式 我希望能够接收 POST 请求的原始 未更改的正文 我能找到的所有例子都显示async代码 当我以正常同步方式尝试时 request body 显示为协程对象 当我通过发布一些内容来
  • 更改 `base_compiledir` 以将编译后的文件保存在另一个目录中

    theano base compiledir指编译后的文件存放的目录 有没有办法可以永久设置theano base compiledir到不同的位置 也许通过修改一些内部 Theano 文件的内容 http deeplearning net
  • python suds SOAP 请求中的名称空间前缀错误

    我使用 python suds 来实现客户端 并且在发送的 SOAP 标头中得到了错误的命名空间前缀 用于定义由element ref 在 wsdl 中 wsdl 正在引用数据类型 xsd 文件 请参见下文 问题出在函数上GetRecord
  • 在 angular2 中过滤数组

    我正在研究如何在 Angular2 中过滤数据数组 我研究过使用自定义管道 但我觉得这不是我想要的 因为它似乎更适合简单的表示转换 而不是过滤大量数据 数组排列如下 getLogs Array
  • 按元组分隔符拆分列表

    我有清单 print L I WW am XX newbie YY ZZ You WW are XX cool YY ZZ 我想用分隔符将列表拆分为子列表 ZZ print new L I WW am XX newbie YY ZZ You
  • 在 pytube3 中获取 youtube 视频的标题?

    我正在尝试构建一个应用程序来使用 python 下载 YouTube 视频pytube3 但我无法检索视频的标题 这是我的代码 from pytube import YouTube yt YouTube link print yt titl
  • 无法在 osx-arm64 上安装 Python 3.7

    我正在尝试使用 Conda 创建一个带有 Python 3 7 的新环境 例如 conda create n qnn python 3 7 我收到以下错误 Collecting package metadata current repoda
  • 如何在 OSX 上安装 numpy 和 scipy?

    我是 Mac 新手 请耐心等待 我现在使用的是雪豹 10 6 4 我想安装numpy和scipy 所以我从他们的官方网站下载了python2 6 numpy和scipy dmg文件 但是 我在导入 numpy 时遇到问题 Library F
  • 限制 django 应用程序模型中的单个记录?

    我想使用模型来保存 django 应用程序的系统设置 因此 我想限制该模型 使其只能有一条记录 极限怎么办 尝试这个 class MyModel models Model onefield models CharField The fiel
  • Elastic Beanstalk 中的 enum34 问题

    我正在尝试在 Elastic Beanstalk 中设置 django 环境 当我尝试通过requirements txt 文件安装时 我遇到了python3 6 问题 File opt python run venv bin pip li
  • 从 Twitter API 2.0 获取 user.fields 时出现问题

    我想从 Twitter API 2 0 端点加载推文 并尝试获取标准字段 作者 文本 和一些扩展字段 尤其是 用户 字段 端点和参数的定义工作没有错误 在生成的 json 中 我只找到标准字段 但没有找到所需的 user fields 用户
  • gfortran 支持尾调用消除吗?

    我编写了这个小程序来测试 gfortran 是否执行尾调用消除 program tailrec implicit none print tailrecsum 5 0 contains recursive function tailrecsu
  • Scrapy Spider不存储状态(持久状态)

    您好 有一个基本的蜘蛛 可以运行以获取给定域上的所有链接 我想确保它保持其状态 以便它可以从离开的位置恢复 我已按照给定的网址进行操作http doc scrapy org en latest topics jobs html http d

随机推荐

  • 打印绘图时 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 在速度方面表现良好 但是一旦我开始增加数组的维