Skip to content

Instantly share code, notes, and snippets.

@eigenhombre
Created October 16, 2012 16:24
Show Gist options
  • Select an option

  • Save eigenhombre/3900348 to your computer and use it in GitHub Desktop.

Select an option

Save eigenhombre/3900348 to your computer and use it in GitHub Desktop.
import itertools
# live.util.misc:
def collapse_seq(coll):
"""
Compress an interable of integers into a list of pair tuples
(a, b) where a, a+1, ... b were in the original sequence; e.g.,
1, 2, 3, 5, 7, 8, 9 -> (1, 3), (5, 5), (7, 9)
"""
ret = []
for x in sorted(coll):
if not ret:
ret = [(x, x)]
else:
if x == 1 + ret[-1][1]:
ret[-1] = (ret[-1][0], x)
else:
ret.append((x, x))
return ret
def uncollapse_seq(pairs):
return list(apply(itertools.chain,
map(lambda p: range(p[0], p[1]+1), pairs)))
## Test:
import live.util.misc as misc
class TestCollapseSeq(unittest.TestCase):
def test(self):
assert [] == misc.collapse_seq([])
assert [] == misc.collapse_seq(())
assert [(1, 1)] == misc.collapse_seq([1])
assert [(1, 2)] == misc.collapse_seq([1, 2])
assert [(0, 9)] == misc.collapse_seq(range(10))
assert [(3, 3)] == misc.collapse_seq([3])
assert [(3, 3), (5, 5)] == misc.collapse_seq((3, 5))
assert [(1, 3), (5, 5), (7, 9)] == misc.collapse_seq([1, 2, 3, 5, 7, 8, 9])
assert [(0, 100), (102, 102)] == misc.collapse_seq(range(101) + [102])
assert [(3, 3), (5, 666)] == misc.collapse_seq([3] + range(5, 667))
assert [(1, 3), (5, 5), (7, 9)] == misc.collapse_seq((9, 8, 7, 5, 3, 2, 1))
def test_uncollapse(self):
assert [] == misc.uncollapse_seq([])
assert [1, 2, 3] == misc.uncollapse_seq([(1, 3)])
assert [1, 2, 3, 5, 7, 8, 9] == misc.uncollapse_seq([(1, 3), (5, 5), (7, 9)])
## Usage inside DAQ simulation:
import live.util.misc as misc
def sim_config(name, strings=86, doms_per_str=64, domfrac=1.0):
return {'config': name,
'strings': [{'str': s + 1,
'doms': misc.collapse_seq(
[d + 1
for d in range(doms_per_str)
if random.random() < domfrac])}
for s in range(strings)]}
## Example usage:
>>> import live.sim.daq as daq
>>> config = daq.sim_config('testconfig', strings=2)
>>> config
{'config': 'testconfig', 'strings': [{'doms': [(1, 64)], 'str': 1}, {'doms': [(1, 64)], 'str': 2}]}
## Example including compression (what DAQ should send to Live, as a 'config' moni variable):
>>> import json, bz2, binascii
>>> binascii.hexlify(bz2.compress(json.dumps(config)))
'425a6839314159265359b02c029d00002e9b8050043510000a0fa39c0a2000543451a604c0d34d048a46d403d401a516098d393b3c5f280d8c722d254919515c5141245a13e0506a2cc039428813046a16cccab9ca32745dc914e14242c0b00a74'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment