7

How can I get Mathematica to export/save/write a text file with proper Fortan77 formatting, that is, 72 columns and a continuation marker on the sixth column?

I am using Mathematica to generate large and complex analytic expressions, which I then need to insert into pre-existing Fortran77 code. I have everything working correctly in the front end of Mathematica with FortranForm[] and

SetOptions[$Output, PageWidth -> 72]

However, I can't figure out how to get Mathematica to output correctly to a text file. I want something like this:

MM11 = mH1**2 + (g2**2*v1**2)/2. - 
     -  (g2**2*(v1**2/2. - 
     -       ((v2*Cos(phi2) - (0,1)*v2*Sin(phi2))*
     -          (v2*Cos(phi2) + (0,1)*v2*Sin(phi2)))/2.))/2.
...

but get either this:

MM11 = FortranForm[mH1^2 + (g2^2*v1^2)/2 - ...

or this:

MM11 = mH1**2 + (g2**2*v1**2)/2. - (g2**2*
 (v1**2/2. - ((v2*Cos(phi2) - (0,1)*v2*Sin(phi2))*
...
Ellie Kesselman
  • 899
  • 1
  • 17
  • 34
Timo
  • 4,246
  • 6
  • 29
  • 42
  • I changed the title of the question to be more general, since the answer solves the more general problem of custom output formatting in Mathematica. – Timo Nov 08 '09 at 10:11

1 Answers1

8

This is a job for the surprisingly little-known Splice function. First, you make a template file, with the extension ".mf", like so:

file = "test.mf";

out = OpenWrite[file];

WriteString[out, "MH1 = <* form *>"];

Close[out];

Now when you use Splice, Mathematica will automatically replace everything between the <* and *> delimiters with its evaluated form. So if you set

form = 4 + b9^2 + c1^5 + c4^5 + h10^4 + j2 + k10^4 + p10^4 + q5^5 + 
       q8 + s3^3 + s7^2 + t6^3 + u3^2 + u9^3 + x8^4 + z2^3;

and call

Splice["test.mf", PageWidth -> 72];

which will automatically infer you want FortranForm output from the file extension, and which allows you to set PageWidth as an option, you will get a pretty decent result in the automatically generated file "test.f" (note the new extension):

MH1 =         4 + b9**2 + c1**5 + c4**5 + h10**4 + j2 + k10**4 + p10**4 + 
    -  q5**5 + q8 + s3**3 + s7**2 + t6**3 + u3**2 + u9**3 + x8**4 + 
    -  z2**3

Look at the docs for Splice for more options (changing the name of the output file and the like).

Pillsy
  • 9,781
  • 1
  • 43
  • 70
  • Thanks a bunch! I hadn't thought of trying out Splice. Now I just need to do some dynamic generation of the test.mf file (as e.g. in the Splice help page) and I'm done. – Timo Nov 07 '09 at 10:50
  • Pillsy, I've used `Splice` to generate exhaustive test cases for some mathematical s/w I was writing. Very useful, but occasionally tricky to get Mathematica to produce correct output. – rcollyer Apr 20 '11 at 20:15