pythonioscipy

How to read Abaqus .mtx file? Scipy.io.mmread gives 'not enough values to unpack' error


I'd like to read a .mtx file using Python. The .mtx file is generated by Abaqus and looks like this:

1,1, 1,1,  1.939258533333333e-02
1,2, 1,2,  1.939258533333333e-02
2,1, 2,1,  1.889629366666666e-02

It seems that scipy.io.mmread would work, but when I ran the following code:

import scipy.io

with open(abs_file_path) as mass_file:
    otpt = scipy.io.mmread(mass_file)

I got the following error:

Traceback (most recent call last):
  File "./test_read_mass_mtx.py", line 12, in <module>
    read_mass(file_path)
  File "/home/user/Desktop/Temp/python/data_functions/read_mass_mtx.py", line 6, in read_mass
    otpt = scipy.io.mmread(mass_file)
  File "/home/user/anaconda3/lib/python3.6/site-packages/scipy/io/mmio.py", line 76, in mmread
    return MMFile().read(source)
  File "/home/user/anaconda3/lib/python3.6/site-packages/scipy/io/mmio.py", line 414, in read
    self._parse_header(stream)
  File "/home/user/anaconda3/lib/python3.6/site-packages/scipy/io/mmio.py", line 478, in _parse_header
    self.__class__.info(stream)
  File "/home/user/anaconda3/lib/python3.6/site-packages/scipy/io/mmio.py", line 232, in info
    [asstr(part.strip()) for part in line.split()]
ValueError: not enough values to unpack (expected 5, got 3)

Thanks!


Solution

  • Abaqus and SciPy don't agree on what a Matrix Market file should look like.

    The first issue which causes your error is that SciPy expects whitespace between every column, hence your "expected 5, got 3" error. Changing your example input manually to contain whitespace:

    1, 1, 1, 1,  1.939258533333333e-02
    1, 2, 1, 2,  1.939258533333333e-02
    2, 1, 2, 1,  1.889629366666666e-02
    

    The error changes to

    ValueError: source is not in Matrix Market format
    

    This makes sense to me, because the docs of mmread says the return value is

    Dense or sparse matrix depending on the matrix format in the Matrix Market file.

    Which might mean that there's at least some metadata (headers?) missing from the file, making it non-standard. So either

    1. the file is not a proper .mtx file, or
    2. the given format is not supported by SciPy

    Either way you'll probably have to parse the file yourself. If you know what the first four columns mean you can probably easily parse it using numpy.loadtxt or something similar.