Export custom formatted expressions from Mathematica
Asked Answered
S

1

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))*
...
Steelworks answered 6/11, 2009 at 13:48 Comment(1)
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.Steelworks
S
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).

Schlegel answered 6/11, 2009 at 15:51 Comment(2)
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.Steelworks
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.Gan

© 2022 - 2024 — McMap. All rights reserved.