Transpiler from Python to Fortran

Using Codex and Claude Code I have created a Python, NumPy, pandas, and (partial) SciPy to Fortran transpiler. It is intended for numerical Python programs that use a Fortran-friendly subset of Python. It can infer many scalar, array, string, and pandas DataFrame cases, emit Fortran source, optionally compile it with gfortran, and compare Python and Fortran output for regression testing. I have tested it on the Python programs of John Burkardt, and some of the Fortran translations are 10-100 times faster, with a geometric mean speed up of 2x. The translation of

"""Count primes up to n"""

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    d = 3
    while d * d <= n:
        if n % d == 0:
            return False
        d += 2
    return True

limit = 10**6
nprime = 0
max_prime = None

for n in range(2, limit + 1):
    if is_prime(n):
        nprime += 1
        max_prime = n

print("number of primes =", nprime)
print("largest prime    =", max_prime)

to Fortran

module xprime_proc_mod
   use, intrinsic :: iso_fortran_env, only: real64
   implicit none
   private
   integer, parameter :: dp = real64
   public :: dp, is_prime
contains

pure elemental function is_prime(n) result(func_res)
   integer, intent(in) :: n
   logical :: func_res
   integer :: d
   
   if (n < 2) then
      func_res = .false.
      return
   end if
   if (n == 2) then
      func_res = .true.
      return
   end if
   if (modulo(n, 2) == 0) then
      func_res = .false.
      return
   end if
   d = 3
   do while (d * d <= n)
      if (modulo(n, d) == 0) then
         func_res = .false.
         return
      end if
      d = d + 2
   end do
   func_res = .true.
end function is_prime

end module xprime_proc_mod

program xprime
   use xprime_proc_mod, only: is_prime
   implicit none
   integer, parameter :: limit = 10 ** 6 ! constant from python source
   integer :: max_prime, n, nprime
   
   nprime = 0
   max_prime = -1
   do n = 2, limit
      if (is_prime(n)) then
         nprime = nprime + 1
         max_prime = n
      end if
   end do
   print *, "number of primes =", nprime
   print *, "largest prime    =", max_prime
end program xprime

is about 20 times faster. It translates the NumPy examples from Python Fortran Rosetta Stone — Fortran Programming Language. xp2f_fpm.py can package several drivers with a shared stateless Python module into an FPM project.

9 Likes