Skip to content

stream_dataframe

Streaming columnar data writer/reader with sorted scan support.

This module provides :class:StreamDataWriter and :class:StreamDataReader for writing and reading named, typed tensor streams, plus :class:StreamSortedScan for scanning data in sorted order by a key field with slice-based caching.

StreamDataWriter

Write named, typed columns to a tensor stream file.

Example
import os
import tempfile

import numpy as np

from py_misc_utils import stream_dataframe as sdf

spath = os.path.join(tempfile.mkdtemp(), 'records.ts')
w = sdf.StreamDataWriter('id=i, value=f', spath)

for i in range(3):
  w.write(id=np.array([i]), value=np.array([10.0 * i]))

w.flush()
Source code in py_misc_utils/stream_dataframe.py
 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
class StreamDataWriter:
  """Write named, typed columns to a tensor stream file.

  Example:
    import os
    import tempfile

    import numpy as np

    from py_misc_utils import stream_dataframe as sdf

    spath = os.path.join(tempfile.mkdtemp(), 'records.ts')
    w = sdf.StreamDataWriter('id=i, value=f', spath)

    for i in range(3):
      w.write(id=np.array([i]), value=np.array([10.0 * i]))

    w.flush()
  """

  def __init__(self, fields, path):
    """Initialize the writer with field definitions and an output path.

    Args:
      fields: A comma-separated string of 'name=dtype' pairs, or a sequence
        of (name, dtype) tuples.
      path: Filesystem path to write the stream to.
    """
    self._writer = ts.Writer(path)
    self._fields = collections.OrderedDict()
    if isinstance(fields, str):
      sfields = tuple(tuple(ut.resplit(x, '=')) for x in ut.comma_split(fields))
    else:
      sfields = fields

    for field, dtype in sfields:
      self._fields[field] = WriteField(dtype=np.dtype(dtype))

  # Note that the tensors handed over to the write() API will become owned by
  # the StreamDataWriter obect, and cannot be written over after the write operation.
  def write(self, **kwargs):
    """Write one row of field data to the stream.

    The tensors handed over become owned by the StreamDataWriter object and
    cannot be modified after the write operation.

    Args:
      **kwargs: Field name to value/numpy array mappings. All fields must be
        provided.
    """
    args = []
    for field, wfield in self._fields.items():
      data = kwargs.get(field)
      tas.check_is_not_none(data, msg=f'Missing "{field}" data in write operation')

      if isinstance(data, np.ndarray):
        if data.dtype != wfield.dtype:
          data = data.astype(wfield.dtype)
      else:
        data = np.array(data, dtype=wfield.dtype)

      args.append(data)

    self._writer.write(*args)

  def write_dataframe(self, df):
    """Write all rows of a DataFrame to the stream.

    Args:
      df: A pandas DataFrame whose columns match the writer's fields.
    """
    wargs = collections.OrderedDict()
    for field in self._fields:
      wargs[field] = df[field].to_numpy()

    self.write(**wargs)

  def flush(self):
    """Flush pending writes and persist field metadata to the stream."""
    state = dict(fields=self._fields)

    self._writer.flush(state=state)

write(**kwargs)

Write one row of field data to the stream.

The tensors handed over become owned by the StreamDataWriter object and cannot be modified after the write operation.

Parameters:

Name Type Description Default
**kwargs

Field name to value/numpy array mappings. All fields must be provided.

{}
Source code in py_misc_utils/stream_dataframe.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def write(self, **kwargs):
  """Write one row of field data to the stream.

  The tensors handed over become owned by the StreamDataWriter object and
  cannot be modified after the write operation.

  Args:
    **kwargs: Field name to value/numpy array mappings. All fields must be
      provided.
  """
  args = []
  for field, wfield in self._fields.items():
    data = kwargs.get(field)
    tas.check_is_not_none(data, msg=f'Missing "{field}" data in write operation')

    if isinstance(data, np.ndarray):
      if data.dtype != wfield.dtype:
        data = data.astype(wfield.dtype)
    else:
      data = np.array(data, dtype=wfield.dtype)

    args.append(data)

  self._writer.write(*args)

write_dataframe(df)

Write all rows of a DataFrame to the stream.

Parameters:

Name Type Description Default
df

A pandas DataFrame whose columns match the writer's fields.

required
Source code in py_misc_utils/stream_dataframe.py
87
88
89
90
91
92
93
94
95
96
97
def write_dataframe(self, df):
  """Write all rows of a DataFrame to the stream.

  Args:
    df: A pandas DataFrame whose columns match the writer's fields.
  """
  wargs = collections.OrderedDict()
  for field in self._fields:
    wargs[field] = df[field].to_numpy()

  self.write(**wargs)

flush()

Flush pending writes and persist field metadata to the stream.

Source code in py_misc_utils/stream_dataframe.py
 99
100
101
102
103
def flush(self):
  """Flush pending writes and persist field metadata to the stream."""
  state = dict(fields=self._fields)

  self._writer.flush(state=state)

StreamDataReader

Read named, typed columns from a tensor stream file.

Example
import os
import tempfile

import numpy as np

from py_misc_utils import stream_dataframe as sdf

spath = os.path.join(tempfile.mkdtemp(), 'records.ts')
w = sdf.StreamDataWriter('id=i, value=f', spath)
w.write(id=np.array([0]), value=np.array([0.0]))
w.write(id=np.array([1]), value=np.array([10.0]))
w.flush()

r = sdf.StreamDataReader(spath)

print(len(r))  # 2
print(r.fields())  # ('id', 'value')

sl = r.get_slice(0, 2)

print(sl['id'].tolist())  # [0, 1]
print(sl['value'].tolist())  # [0.0, 10.0]
Source code in py_misc_utils/stream_dataframe.py
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
216
217
218
219
220
221
222
223
224
225
226
class StreamDataReader:
  """Read named, typed columns from a tensor stream file.

  Example:
    import os
    import tempfile

    import numpy as np

    from py_misc_utils import stream_dataframe as sdf

    spath = os.path.join(tempfile.mkdtemp(), 'records.ts')
    w = sdf.StreamDataWriter('id=i, value=f', spath)
    w.write(id=np.array([0]), value=np.array([0.0]))
    w.write(id=np.array([1]), value=np.array([10.0]))
    w.flush()

    r = sdf.StreamDataReader(spath)

    print(len(r))  # 2
    print(r.fields())  # ('id', 'value')

    sl = r.get_slice(0, 2)

    print(sl['id'].tolist())  # [0, 1]
    print(sl['value'].tolist())  # [0.0, 10.0]
  """

  def __init__(self, path):
    """Initialize the reader from a tensor stream file path.

    Args:
      path: Filesystem path of the stream to read.
    """
    self._reader = ts.Reader(path)
    self._fields = self._reader.state['fields']
    self._fields_id = {field: i for i, field in enumerate(self._fields.keys())}

  def __len__(self):
    """Return the number of records in the stream.

    Returns:
      The total record count.
    """
    return len(self._reader)

  def fields(self):
    """Return the field names in the stream.

    Returns:
      A tuple of field names.
    """
    return tuple(self._fields.keys())

  @property
  def dtype(self):
    """Return the field dtypes in the stream.

    Returns:
      A tuple of numpy dtypes, one per field.
    """
    return tuple(wfield.dtype for wfield in self._fields.values())

  def get_slice(self, start, size=None):
    """Read a slice of records from the stream.

    Args:
      start: The starting record index.
      size: Optional number of records to read; defaults to all remaining.

    Returns:
      An ordered dict mapping field names to numpy arrays.
    """
    data = collections.OrderedDict()
    for i, field in enumerate(self._fields.keys()):
      data[field] = self._reader.get_slice(i, start, size=size)

    return data

  def get_field_slice(self, field, start, size=None):
    """Read a slice of a single field from the stream.

    Args:
      field: The field name to read.
      start: The starting record index.
      size: Optional number of records to read.

    Returns:
      A numpy array (or list) of the field's values.
    """
    fid = self._fields_id[field]

    return self._reader.get_slice(fid, start, size=size)

  def typed_fields(self):
    """Return the fields with their dtypes.

    Returns:
      A tuple of (field_name, dtype) pairs.
    """
    return tuple((field, wfield.dtype) for field, wfield in self._fields.items())

  def empty_array(self, size):
    """Create empty arrays for all fields.

    Numeric fields are allocated as numpy arrays; non-numeric fields as lists.

    Args:
      size: The number of elements to allocate.

    Returns:
      An ordered dict mapping field names to empty containers.
    """
    rdata = collections.OrderedDict()
    for field, dtype in self.typed_fields():
      if npu.is_numeric(dtype):
        rdata[field] = np.empty(size, dtype=dtype)
      else:
        rdata[field] = [None] * size

    return rdata

dtype property

Return the field dtypes in the stream.

Returns:

Type Description

A tuple of numpy dtypes, one per field.

fields()

Return the field names in the stream.

Returns:

Type Description

A tuple of field names.

Source code in py_misc_utils/stream_dataframe.py
152
153
154
155
156
157
158
def fields(self):
  """Return the field names in the stream.

  Returns:
    A tuple of field names.
  """
  return tuple(self._fields.keys())

get_slice(start, size=None)

Read a slice of records from the stream.

Parameters:

Name Type Description Default
start

The starting record index.

required
size

Optional number of records to read; defaults to all remaining.

None

Returns:

Type Description

An ordered dict mapping field names to numpy arrays.

Source code in py_misc_utils/stream_dataframe.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def get_slice(self, start, size=None):
  """Read a slice of records from the stream.

  Args:
    start: The starting record index.
    size: Optional number of records to read; defaults to all remaining.

  Returns:
    An ordered dict mapping field names to numpy arrays.
  """
  data = collections.OrderedDict()
  for i, field in enumerate(self._fields.keys()):
    data[field] = self._reader.get_slice(i, start, size=size)

  return data

get_field_slice(field, start, size=None)

Read a slice of a single field from the stream.

Parameters:

Name Type Description Default
field

The field name to read.

required
start

The starting record index.

required
size

Optional number of records to read.

None

Returns:

Type Description

A numpy array (or list) of the field's values.

Source code in py_misc_utils/stream_dataframe.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def get_field_slice(self, field, start, size=None):
  """Read a slice of a single field from the stream.

  Args:
    field: The field name to read.
    start: The starting record index.
    size: Optional number of records to read.

  Returns:
    A numpy array (or list) of the field's values.
  """
  fid = self._fields_id[field]

  return self._reader.get_slice(fid, start, size=size)

typed_fields()

Return the fields with their dtypes.

Returns:

Type Description

A tuple of (field_name, dtype) pairs.

Source code in py_misc_utils/stream_dataframe.py
200
201
202
203
204
205
206
def typed_fields(self):
  """Return the fields with their dtypes.

  Returns:
    A tuple of (field_name, dtype) pairs.
  """
  return tuple((field, wfield.dtype) for field, wfield in self._fields.items())

empty_array(size)

Create empty arrays for all fields.

Numeric fields are allocated as numpy arrays; non-numeric fields as lists.

Parameters:

Name Type Description Default
size

The number of elements to allocate.

required

Returns:

Type Description

An ordered dict mapping field names to empty containers.

Source code in py_misc_utils/stream_dataframe.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def empty_array(self, size):
  """Create empty arrays for all fields.

  Numeric fields are allocated as numpy arrays; non-numeric fields as lists.

  Args:
    size: The number of elements to allocate.

  Returns:
    An ordered dict mapping field names to empty containers.
  """
  rdata = collections.OrderedDict()
  for field, dtype in self.typed_fields():
    if npu.is_numeric(dtype):
      rdata[field] = np.empty(size, dtype=dtype)
    else:
      rdata[field] = [None] * size

  return rdata

StreamSortedScan

Scan records of a stream in sorted order by a key field.

Uses an LRU cache of slices for efficient repeated access.

Source code in py_misc_utils/stream_dataframe.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
class StreamSortedScan:
  """Scan records of a stream in sorted order by a key field.

  Uses an LRU cache of slices for efficient repeated access.
  """

  def __init__(self,
               reader,
               field,
               start=None,
               end=None,
               slice_size=None,
               max_slices=None,
               reverse=False):
    """Initialize the sorted scan.

    Args:
      reader: A StreamDataReader instance.
      field: The field name to sort by.
      start: Optional start value of the filter range.
      end: Optional end value of the filter range.
      slice_size: Optional number of records per cached slice.
      max_slices: Optional maximum number of cached slices.
      reverse: If True, scan in descending order.
    """
    self._slice_size = slice_size or 100000
    self._max_slices = max_slices or 16
    self._reader = reader
    self._slices = collections.OrderedDict()
    self._indices = _compute_indices(reader,
                                     field,
                                     start=start,
                                     end=end,
                                     reverse=reverse)

  def _get_slice(self, idx):
    """Fetch the cached slice containing record idx, loading it if needed.

    Args:
      idx: The record index to locate.

    Returns:
      The tuple (slice_start, slice_data).
    """
    sidx = (idx // self._slice_size) * self._slice_size
    data = self._slices.get(sidx)
    if data is None:
      if len(self._slices) >= self._max_slices:
        self._slices.popitem(last=False)

      slice_size = min(self._slice_size, len(self._indices) - sidx)

      data = self._reader.get_slice(sidx, size=slice_size)
      self._slices[sidx] = data
    else:
      self._slices.move_to_end(sidx)

    return data, idx - sidx

  def _as_numpy(self, rdata):
    """Convert field containers to numpy arrays.

    Args:
      rdata: An ordered dict mapping field names to arrays/lists.

    Returns:
      A dict mapping field names to numpy arrays.
    """
    return {field: np.array(data) for field, data in rdata.items()}

  def scan(self):
    """Yield records in sorted order in batches.

    An empty array can contain fields which are Python lists, so _as_numpy()
    is used when returning data to the caller.

    Yields:
      Tuples of (count, data) where count is the number of records in the
      batch and data is a dict of field name to numpy array.

    Example:
      import os
      import tempfile

      import numpy as np

      from py_misc_utils import stream_dataframe as sdf

      spath = os.path.join(tempfile.mkdtemp(), 'records.ts')
      w = sdf.StreamDataWriter('id=i, value=f', spath)
      for i in [3, 1, 2, 5, 4, 0]:
        w.write(id=np.array([i]), value=np.array([float(i)]))
      w.flush()

      r = sdf.StreamDataReader(spath)
      scan = sdf.StreamSortedScan(r, field='id', slice_size=2)

      for count, data in scan.scan():
        print(count, data['id'].tolist(), data['value'].tolist())

      # 2 `[0, 1]` `[0.0, 1.0]`
      # 2 `[2, 3]` `[2.0, 3.0]`
      # 2 `[4, 5]` `[4.0, 5.0]`
    """
    # An ampty array can contain fields which are Python lists, so _as_numpy() is
    # used when returning data to the caller.
    rdata = self._reader.empty_array(self._slice_size)
    widx = 0
    for idx in self._indices:
      if widx == self._slice_size:
        yield widx, self._as_numpy(rdata)
        widx = 0

      sdata, sidx = self._get_slice(idx)
      for field, data in rdata.items():
        data[widx] = sdata[field][sidx]

      widx += 1

    if widx:
      frdata = collections.OrderedDict()
      for field, data in rdata.items():
        frdata[field] = data[:widx]

      yield widx, self._as_numpy(frdata)

scan()

Yield records in sorted order in batches.

An empty array can contain fields which are Python lists, so _as_numpy() is used when returning data to the caller.

Yields:

Type Description

Tuples of (count, data) where count is the number of records in the

batch and data is a dict of field name to numpy array.

Example
import os
import tempfile

import numpy as np

from py_misc_utils import stream_dataframe as sdf

spath = os.path.join(tempfile.mkdtemp(), 'records.ts')
w = sdf.StreamDataWriter('id=i, value=f', spath)
for i in [3, 1, 2, 5, 4, 0]:
  w.write(id=np.array([i]), value=np.array([float(i)]))
w.flush()

r = sdf.StreamDataReader(spath)
scan = sdf.StreamSortedScan(r, field='id', slice_size=2)

for count, data in scan.scan():
  print(count, data['id'].tolist(), data['value'].tolist())

# 2 `[0, 1]` `[0.0, 1.0]`
# 2 `[2, 3]` `[2.0, 3.0]`
# 2 `[4, 5]` `[4.0, 5.0]`
Source code in py_misc_utils/stream_dataframe.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def scan(self):
  """Yield records in sorted order in batches.

  An empty array can contain fields which are Python lists, so _as_numpy()
  is used when returning data to the caller.

  Yields:
    Tuples of (count, data) where count is the number of records in the
    batch and data is a dict of field name to numpy array.

  Example:
    import os
    import tempfile

    import numpy as np

    from py_misc_utils import stream_dataframe as sdf

    spath = os.path.join(tempfile.mkdtemp(), 'records.ts')
    w = sdf.StreamDataWriter('id=i, value=f', spath)
    for i in [3, 1, 2, 5, 4, 0]:
      w.write(id=np.array([i]), value=np.array([float(i)]))
    w.flush()

    r = sdf.StreamDataReader(spath)
    scan = sdf.StreamSortedScan(r, field='id', slice_size=2)

    for count, data in scan.scan():
      print(count, data['id'].tolist(), data['value'].tolist())

    # 2 `[0, 1]` `[0.0, 1.0]`
    # 2 `[2, 3]` `[2.0, 3.0]`
    # 2 `[4, 5]` `[4.0, 5.0]`
  """
  # An ampty array can contain fields which are Python lists, so _as_numpy() is
  # used when returning data to the caller.
  rdata = self._reader.empty_array(self._slice_size)
  widx = 0
  for idx in self._indices:
    if widx == self._slice_size:
      yield widx, self._as_numpy(rdata)
      widx = 0

    sdata, sidx = self._get_slice(idx)
    for field, data in rdata.items():
      data[widx] = sdata[field][sidx]

    widx += 1

  if widx:
    frdata = collections.OrderedDict()
    for field, data in rdata.items():
      frdata[field] = data[:widx]

    yield widx, self._as_numpy(frdata)