0
$\begingroup$

A question related to a previous question. The answer in the previous question works well for simple complex arrays but not when considering arrays with exponential float coefficients as in the following example:enter image description here

When using the method as recommended in the previous accepted answer:

Export["C:\bar.csv", StringReplace[ExportString[data, "CSV"], "*I" -> "j"], "Text"]

I obtain CSV output for the diagonal entries with respective '7.092443560888918^-9+0.j*' and '0.+2.356367867779361^-6j*'. There seems to be more significant figures in the CSV file entries than in Mathematica. Python is unable to effectively process the diagonal elements (when I import using Numpy as recommended in the linked previous question). Can anyone advise on how to adapt the code to deal with sending these types of complex arrays from Mathematica to Python?

Thanks for any assistance.

$\endgroup$
2
  • 1
    $\begingroup$ You can define ExternalFunction, pass your data to it, convert with numpy.array and save data with numpy.savetxt $\endgroup$
    – I.M.
    Commented Jun 22, 2021 at 13:33
  • $\begingroup$ @I.M. I'm not following how that would work, could you provide more detail? $\endgroup$
    – John Doe
    Commented Jun 22, 2021 at 13:43

1 Answer 1

2
$\begingroup$

Start session and define external function:

session = StartExternalSession["Python"] ;
export = ExternalFunction[
session,
"def export(data):\n
    import numpy\n
    numpy.save('test.npy', numpy.array(data))\n
    return 1"
] ;

Generate and export test data:

data = RandomComplex[{0, 1+I}, 10]*10^10 
export[data]

Check data:

ExternalEvaluate[session,
"import numpy\n
data = numpy.load('test.npy')\n
for z in data:\n
    print(z)"
]

Close session:

DeleteObject[session]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.