File size: 3,985 Bytes
aa0469e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""Minimal loader for the solve-anywhere linear-system dataset (numpy + scipy only).

    from load import catalog, runs, systems, load

    for run in runs(problem="ex16p", max_n=1e6):        # filter the catalog
        for rec in systems(run, "heat"):                 # index records of one stream
            A, b, x = load(run, "heat", rec["sys"])      # scipy CSR, numpy arrays (x may be None)

Command line:
    python load.py                       summary of the catalog
    python load.py <run> <stream> <i>    print one system's metadata and shapes
    python load.py --mtx <run> <stream> <i> <out_prefix>   write <out_prefix>.mtx / _b.mtx (Matrix Market)
"""
import json
import os
import sys

import numpy as np
import scipy.io
import scipy.sparse as sp

ROOT = os.path.dirname(os.path.abspath(__file__))


def catalog():
    """Latest catalog entry per run (a re-run replaces an earlier entry)."""
    latest = {}
    with open(os.path.join(ROOT, "catalog.jsonl")) as f:
        for line in f:
            c = json.loads(line)
            latest[c["path"]] = c
    return list(latest.values())


def runs(source=None, problem=None, min_n=0, max_n=float("inf"), ok_only=True):
    """Run directories (absolute) matching the filters."""
    out = []
    for c in catalog():
        if source and c["source"] != source or problem and c["problem"] != problem:
            continue
        if ok_only and c["exit"] != 0:
            continue
        ns = [n for s in c["streams"].values() for n in s["n"]]
        if ns and min_n <= max(ns) <= max_n:
            out.append(os.path.join(ROOT, c["path"]))
    return out


def meta(run):
    with open(os.path.join(run, "meta.json")) as f:
        return json.load(f)


def systems(run, stream):
    """Per-system metadata (one dict per saved system, in order)."""
    with open(os.path.join(run, stream, "index.jsonl")) as f:
        return [json.loads(line) for line in f]


def load(run, stream, i, with_extra=False):
    """(A, b, x) of system i; x is None if not saved. with_extra=True also returns
    a dict of the other saved vectors (x0, contact_dofs, block_id, ...)."""
    rec = systems(run, stream)[i]
    A = sp.load_npz(os.path.join(run, stream, f"A_{rec['A']:04d}.npz"))
    v = np.load(os.path.join(run, stream, f"sys_{i:05d}.npz"))
    x = v["x"] if "x" in v.files else None
    if with_extra:
        return A, v["b"], x, {k: v[k] for k in v.files if k not in ("b", "x")}
    return A, v["b"], x


def to_matrix_market(run, stream, i, prefix):
    A, b, x = load(run, stream, i)
    scipy.io.mmwrite(prefix + ".mtx", A, precision=17)
    scipy.io.mmwrite(prefix + "_b.mtx", b.reshape(-1, 1), precision=17)
    if x is not None:
        scipy.io.mmwrite(prefix + "_x.mtx", x.reshape(-1, 1), precision=17)


if __name__ == "__main__":
    if len(sys.argv) >= 6 and sys.argv[1] == "--mtx":
        to_matrix_market(os.path.abspath(sys.argv[2]), sys.argv[3], int(sys.argv[4]), sys.argv[5])
    elif len(sys.argv) == 4:
        run, stream, i = os.path.abspath(sys.argv[1]), sys.argv[2], int(sys.argv[3])
        A, b, x, extra = load(run, stream, i, with_extra=True)
        print(json.dumps(systems(run, stream)[i], indent=2))
        print("A", A.shape, A.nnz, "| b", b.shape, "| x", None if x is None else x.shape, "| extra", list(extra))
    else:
        by = {}
        for c in catalog():
            k = (c["source"], c["problem"])
            nsys = sum(s["systems"] for s in c["streams"].values())
            nmax = max([n for s in c["streams"].values() for n in s["n"]] or [0])
            r, s_, b_, m, f = by.get(k, (0, 0, 0, 0, 0))
            by[k] = (r + 1, s_ + nsys, b_ + c["bytes"], max(m, nmax), f + (c["exit"] != 0))
        print(f"{'source':8s} {'problem':18s} {'runs':>5s} {'failed':>6s} {'systems':>8s} {'GB':>7s} {'largest n':>10s}")
        for (src, prob), (r, s_, b_, m, f) in sorted(by.items()):
            print(f"{src:8s} {prob:18s} {r:5d} {f:6d} {s_:8d} {b_ / 1e9:7.2f} {m:10d}")