| import os |
| import argparse |
| from pathlib import Path |
| import scipy as sp |
|
|
| def print_matinfos(matrix: sp.sparse.coo_matrix) -> None: |
| print(f" - Size of the matrix: {matrix.shape}") |
| print(f" - Number of non-zero elements: {matrix.nnz}") |
| print(f" - Data type of the matrix: {matrix.dtype}") |
|
|
|
|
| def load_matrixmarket(path_input: Path) -> sp.sparse.coo_matrix: |
| """ |
| Load a Matrix Market file and return it as scipy.sparse.coo_matrix. |
| """ |
| print(f" - Loaded Matrix Market file from: {path_input}") |
| matrix = sp.io.mmread(path_input) |
| print_matinfos(matrix) |
| return matrix |
|
|
| def save_matrixmarket(matrix: sp.sparse.coo_matrix, path_output: Path) -> None: |
| """ |
| Save a scipy.sparse.coo_matrix to a Matrix Market file. |
| """ |
| print(f" - Saving Matrix Market file to: {path_output}") |
| sp.io.mmwrite( |
| path_output, |
| matrix, |
| ) |
| print(" - Successfully saved Matrix Market file.") |
|
|
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser(description="Matrix Market utilities") |
| parser.add_argument("command", choices=["mm2npz", "npz2mm"], help="Command to execute") |
| parser.add_argument("input_file", help="Input file path") |
| parser.add_argument("output_file", help="Output file path") |
|
|
| args = parser.parse_args() |
|
|
| print("args:", args) |
|
|
| if args.command == "mm2npz": |
| print("Converting Matrix Market to NPZ format:") |
| matrix_coo = load_matrixmarket(args.input_file) |
| input_matrix_name = os.path.splitext(os.path.basename(args.input_file))[0] |
| output_matrix_name = Path.joinpath( |
| Path(args.output_file), f"{input_matrix_name}.npz" |
| ) |
| print(f" - Saving to NPZ format: {output_matrix_name}") |
| sp.sparse.save_npz(output_matrix_name, matrix_coo) |
| elif args.command == "npz2mm": |
| print("Converting NPZ to Matrix Market format:") |
| matrix_coo = sp.sparse.load_npz(args.input_file).tocoo() |
| print(f" - Loaded NPZ file from: {args.input_file}") |
| print_matinfos(matrix_coo) |
| input_matrix_name = os.path.splitext(os.path.basename(args.input_file))[0] |
| output_matrix_name = Path.joinpath( |
| Path(args.output_file), f"{input_matrix_name}.mtx" |
| ) |
| print(f" - Saving to Matrix Market format: {output_matrix_name}") |
| save_matrixmarket(matrix_coo, output_matrix_name) |