压缩正弦波表

Poo*_*zer 5 python compression trigonometry run-length-encoding

我有一个包含1024个条目的大型数组,其中包含7位值 range(14, 86)

这意味着有多个索引范围具有相同的值.

例如,

consider the index range 741 to 795. It maps to 14
consider the index range 721 to 740. It maps to 15
consider the index range 796 to 815. It maps to 15
Run Code Online (Sandbox Code Playgroud)

我想将这个地图提供给一个python程序,该程序会显示以下内容:

if((index >= 741) and (index <= 795)) return 14;
if((index >= 721) and (index <= 740)) return 15;
if((index >= 796) and (index <= 815)) return 15;
Run Code Online (Sandbox Code Playgroud)

groupby映射值的一些代码已经准备就绪,但我使用编码表达式时遇到了困难pairwise.

以前有人做过类似的事吗?

我已经以两种形式上传了数据集:

通常,按索引排序.

按映射值分组.

smc*_*mci 2

关闭后,我迟来地找到了这个解决方案“What's the most Pythonic way to recognize Continuous duplicates in a list?”


注意:对于像sine这样的周期性 fn ,您可以只存储表的四分之一(即 256 个值)或一半,然后在查找时对索引执行一些(定点)算术。正如我所评论的,如果您进一步不存储 +50 的偏移量,则需要少一位,代价是在查找时间后增加一个整数。因此,79% 的压缩率很容易实现。RLE 会给你更多。即使 fn 有噪音,您仍然可以通过这种通用方法获得不错的压缩效果。

正如 agf 指出的,你的f(n) = 50 + 36*sin(72*pi*n/1024)= 50 + g(n),比如说。

g(n) = 36*sin(72*pi*n/1024)因此,仅针对 n=0..255 的范围,将 的 256 个值制成表格

然后 f(n) 很容易计算为:

if 0 <= n < 256, f(n) = 50 + g(n)
if 256 <= n < 512, f(n) = 50 + g(511-n)
if 512 <= n < 768, f(n) = 50 - g(n-512)
if 768 <= n < 1024, f(n) = 50 - g(1023-n)
Run Code Online (Sandbox Code Playgroud)

无论如何,这是一个通用的表压缩器解决方案,它将生成(istart,iend,value)三元组。

我绞尽脑汁如何使用列表推导式和 itertools.takewhile() 更 Python 地做到这一点;需要抛光。

#import itertools

table_="""
    0       50
    1       50
    ...
    1021    49
    1022    50
    1023    50""".split()

# Convert values to int. Throw away the indices - will recover them with enumerate()
table = [int(x) for x in table_[1::2]]

compressed_table = []
istart = 0
for i,v in enumerate(table):
    if v != table[i-1]:
        iend = i-1
        compressed_table.append((istart,iend,table[i-1]))
        istart = i
    else:
        continue # skip identical values
# Slightly ugly: append the last value, when the iterator was exhausted
compressed_table.append((istart,i,table[i]))
Run Code Online (Sandbox Code Playgroud)

(注意,在 agf 改变他的方法之前,我开始使用表压缩器方法......试图获得 itertools 或列表理解解决方案)