Problem with Dot and FortranForm

I am trying to convert some set of equations to a form that will be easy for Python to evaluate numerically, hence I am using Mathematica's FortranForm

My problem is that

FortranForm[np.diag]

gives

Dot(np,diag)

whereas I want

np.diag

I do not want

FortranForm["np.diag"]

which results in

"np.diag"

What I want is to be able to cast the DiagonalMatrix[equations] part of my expressions to the equivalent in Python - np.diag(equations), where I have imported numpy as np

Solution, but not the desired one

I found a way round my problem, though it is not what I want, but I will post it for people that my just care about the end result.

Use FortranForm["np.diag"] and then export the result to a text file. Then in Python one can read the file and rewrite it line by line, while stripping all the quotes using this piece of code

def fromMathematica(func):
"""" string -> string

Imports a file, created by Mathematica and reads it, so that it can be evaluated for specific values
"""
file = open('path' + func + .txt' , 'r+')
file.seek(0)
file.truncate()
for line in lines:
line = line.replace('"', '').strip()
file.write(line)
file.seek(0)
return m

• You have to do some transformations manually. In this case, you might want to use StringReplace. – Sumit Dec 15 '16 at 10:34
• I am not sure I see your point. My problem is that if it is a string, FortranForm will return it surrounded by quotes, which is what I want to avoid – ThunderBiggi Dec 15 '16 at 11:58
• I think you are taking an ill-concieved approach trying to use mathematics dot product function to produce a name-scoping construct in python. Suggest name the function something like npdotdiag in mathematica and do a stringreplace on the result. (You should not need to do anything by hand! ) – george2079 Dec 15 '16 at 12:58

Probably I don't understand your problem correctly, still giving it a try ..

ff = FortranForm[p + DiagonalMatrix[a + b]]


p + DiagonalMatrix(a + b)

StringReplace[ToString[ff], "DiagonalMatrix" -> "np.diag"]


p + np.diag(a + b)

• This exactly solves my problem for the moment. I didn't think of replacing stuff after using FortranForm. I will see what happens when I try that approach on my pages long equations :) – ThunderBiggi Dec 15 '16 at 14:15

I would give DiagonalMatrix a custom FortranForm:

Unprotect[DiagonalMatrix];
Format[DiagonalMatrix,FortranForm]=Format["np.diag", OutputForm];
Protect[DiagonalMatrix];


Then:

ToString[p + DiagonalMatrix[a + b], FortranForm]


"p + np.diag(a + b)"