/
io.py
executable file
·215 lines (183 loc) · 6.18 KB
/
io.py
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""
I/O functions for working with CmdStan executables.
"""
import re
import logging
import numpy as np
logger = logging.getLogger('cmdstanpy.io')
def _rdump_array(key, val):
c = 'c(' + ', '.join(map(str, val.T.flat)) + ')'
if (val.size, ) == val.shape:
return '{key} <- {c}'.format(key=key, c=c)
else:
dim = '.Dim = c{0}'.format(val.shape)
struct = '{key} <- structure({c}, {dim})'.format(key=key, c=c, dim=dim)
return struct
def rdump(fname, data):
"""Dump a dict of data to a R dump format file.
"""
with open(fname, 'w') as fd:
for key, val in data.items():
if isinstance(val, np.ndarray) and val.size > 1:
line = _rdump_array(key, val)
else:
try:
val = val.flat[0]
except:
pass
line = '%s <- %s' % (key, val)
fd.write(line)
fd.write('\n')
def rload(fname):
"""Load a dict of data from an R dump format file.
"""
with open(fname, 'r') as fd:
lines = fd.readlines()
data = {}
for line in lines:
lhs, rhs = [_.strip() for _ in line.split('<-')]
if rhs.startswith('structure'):
*_, vals, dim = rhs.replace('(', ' ').replace(')', ' ').split('c')
vals = [float(v) for v in vals.split(',')[:-1]]
dim = [int(v) for v in dim.split(',')]
val = np.array(vals).reshape(dim[::-1]).T
elif rhs.startswith('c'):
val = np.array([float(_) for _ in rhs[2:-1].split(',')])
else:
try:
val = int(rhs)
except:
try:
val = float(rhs)
except:
raise ValueError(rhs)
data[lhs] = val
return data
def merge_csv_data(*csvs, skip=0):
"""Merge multiple CSV dicts into a single dict.
"""
data_ = {}
for csv in csvs:
for key, val in csv.items():
# XXX do better
if key in 'loo loos ks'.split():
continue
val = val[skip:]
if key in data_:
data_[key] = np.concatenate((data_[key], val), axis=0)
else:
data_[key] = val
return data_
def parse_csv(fname, merge=True):
"""Parse samples from a Stan output CSV file.
"""
if '*' in fname:
import glob
return parse_csv(glob.glob(fname), merge=merge)
if isinstance(fname, (list, tuple)):
csv = []
for _ in fname:
try:
csv.append(parse_csv(_))
except Exception as e:
print('skipping ', fname, e)
if merge:
csv = merge_csv_data(*csv)
return csv
lines = []
with open(fname, 'r') as fd:
for line in fd.readlines():
if not line.startswith('#'):
lines.append(line.strip().split(','))
names = [field.split('.') for field in lines[0]]
data = np.array([[float(f) for f in line] for line in lines[1:]])
namemap = {}
maxdims = {}
for i, name in enumerate(names):
if name[0] not in namemap:
namemap[name[0]] = []
namemap[name[0]].append(i)
if len(name) > 1:
maxdims[name[0]] = name[1:]
for name in maxdims.keys():
dims = []
for dim in maxdims[name]:
dims.append(int(dim))
maxdims[name] = tuple(reversed(dims))
# data in linear order per Stan, e.g. mat is col maj
# TODO array is row maj, how to distinguish matrix v array[,]?
data_ = {}
for name, idx in namemap.items():
new_shape = (-1, ) + maxdims.get(name, ())
data_[name] = data[:, idx].reshape(new_shape)
return data_
def parse_summary_csv(fname):
"""Parse CSV output of the stansummary program.
"""
skeys = []
svals = []
niter = -1
with open(fname, 'r') as fd:
scols = fd.readline().strip().split(',')
for line in fd.readlines():
if 'iterations' in line:
niter_match = re.search(r'(\d+) iterations saved', line)
if niter_match:
niter = int(niter_match.group(1))
continue
if line.startswith('#') or '"' not in line:
continue
_, k, v = line.split('"')
skeys.append(k)
svals.append(np.array([float(_) for _ in v.split(',')[1:]]))
svals = np.array(svals)
sdat = {}
sdims = {}
for skey, sval in zip(skeys, svals):
if '[' in skey:
name, dim = skey.replace('[', ']').split(']')[:-1]
dim = tuple(int(i) for i in dim.split(','))
sdims[name] = dim
if name not in sdat:
sdat[name] = []
sdat[name].append(sval)
else:
sdat[skey] = sval
for key in [_ for _ in sdat.keys()]:
if key in sdims:
sdat[key] = np.array(sdat[key]).reshape(sdims[key] + (-1, ))
recs = {}
dt = [(k, 'f8') for k in scols[1:]]
for key, val in sdat.items():
recs[key] = np.rec.array(val, dtype=dt)
return niter, recs
# a TODO/nice-to-have: a background thread parses CSV samples
# while CmdStan is running to avoid parsing overhead at end of run.
# class OnlineCSVParser:
# # TODO following lines + col labels is sufficient to alloc arrays AOT
# # num_samples = 1000 (Default)
# # num_warmup = 1000 (Default)
# # save_warmup = 0 (Default)
# def __init__(self, csv_fname):
# self.csv_fname = csv_fname
# self.thread = Thread(target=self._run)
# self._line = ''
# self.read = True
# self.thread.start()
# def _run(self):
# while True:
# try:
# self._follow()
# except Exception as exc:
# print(exc)
# def _follow(self):
# with open(self.csv_fname, 'r') as fd:
# while True:
# line = fd.readline()
# if line:
# self.parse_line(line)
# else:
# # TODO adapt to avg time btw samples
# time.sleep(0.01)
# def parse_line(self, line):
# pass