Search code examples
pythonarraysfortranf2py

Passing Arrays from Python to Fortran (and back)


Background:
My program currently assembles arrays in Python. These arrays are connected to a front-end UI and as such have interactive elements (i.e. user specified values in array elements). These arrays are then saved to .txt files (depending on their later use). The user must then leave the Python program and run a separate Fortran script which simulates a system based on the Python output files. While this only takes a couple of minutes at most, I would ideally like to automate the process without having to leave my Python UI.

Assemble Arrays (Python) -> Edit Arrays (Python) -> Export to File (Python)
-> Import File (Fortran) -> Run Simulation (Fortran) -> Export Results to File (Fortran)
-> Import File to UI, Display Graph (Python)

Question:
Is this possible? What are my options for automating this process? Can I completely remove the repeated export/import of files altogether?

Edit: I should also mention that the fortran script uses Lapack, I don't know if that makes a difference.


Solution

  • You do not have to pass arrays to Fortran code using text files. If you create an entry point to the Fortran code as a subroutine, you can pass all the numpy arrays using f2py. You should be aware of that if you added the f2py tag yourself. Just use any of the numerous tutorials, for example https://github.com/thehackerwithin/PyTrieste/wiki/F2Py or http://www.engr.ucsb.edu/~shell/che210d/f2py.pdf .

    The way back is the same, the Fortran code just fills any of the intent(out) or intent(inout) arrays and variables with the results.