tags:

views:

238

answers:

1

How can I get Mathematica to export/save/write out a text file with proper Fortan77 formatting, i.e., 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 can get everything working correctly in the front end of Mathematica with FortranForm[] and SetOptions[$Output, PageWidth -> 72]. However, I just can't figure out how to get Mathematica to output correctly into a text file. I want to get 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 end up getting 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))*
...
+3  A: 

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
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