Created
March 28, 2014 10:49
-
-
Save samueljackson92/9830031 to your computer and use it in GitHub Desktop.
Script to compress linear sequences of numbers as a strings with repeating sections taking the form: start:width:stop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def findSequence(x, delta_x, start=0): | |
string = "" | |
if len(x) == 1: return str(x[0]) + ',' | |
if len(x) == 2: return str(x[0]) + ',' + str(x[1]) + ',' | |
while (start<delta_x.size-1): | |
end = start+1 | |
while(end < delta_x.size-1 and delta_x[end] == delta_x[end+1]): | |
end+=1 | |
if end-start > 2: | |
compressed = str(x[start]) + ":" + str(delta_x[end]) + ":" + str(x[end]) + "," | |
else: | |
compressed = str(x[start]) + ',' + str(x[end]) + "," | |
string += compressed | |
start=end+1 | |
return string | |
def xfrange(start, step, stop): | |
if start<stop: | |
while start <= stop: | |
yield start | |
start += step | |
else: | |
while start >= stop: | |
yield start | |
start += step | |
def uncompress(string): | |
tokens = string.split(',')[:-1] | |
x= [] | |
for token in tokens: | |
subtokens = token.split(':') | |
if len(subtokens) == 1: | |
x.append(float(subtokens[0])) | |
elif len(subtokens) == 3: | |
subtokens = map(float, subtokens) | |
for val in xfrange(*subtokens): | |
x.append(val) | |
return x | |
def computeDeltaX(x): | |
delta_x = x[1:] - x[:-1] | |
delta_x = np.concatenate(([0],delta_x)) | |
return delta_x | |
x = np.asarray([0.5,1,1.5,2,0.5,1,1.5,2,0.5,1,1.5,2,0.5,1,1.5,2]) | |
delta_x = computeDeltaX(x) | |
string = findSequence(x, delta_x) | |
print uncompress(string) | |
x = np.asarray([0,1,2,3,4,5,6,7,8,9,10]) | |
delta_x = computeDeltaX(x) | |
string = findSequence(x, delta_x) | |
print uncompress(string) | |
x = np.asarray([0,1,2,3,4,5,7,9,11,13,15,17]) | |
delta_x = computeDeltaX(x) | |
string = findSequence(x, delta_x) | |
print uncompress(string) | |
x = np.asarray([5,4,3,2,1,0,-1,-2,-3,-4,-5]) | |
delta_x = computeDeltaX(x) | |
string = findSequence(x, delta_x) | |
print uncompress(string) | |
x = np.asarray([5,10,3,7,8,4,1,2,3,4,5]) | |
delta_x = computeDeltaX(x) | |
string = findSequence(x, delta_x) | |
print uncompress(string) | |
x = np.asarray([0]) | |
delta_x = computeDeltaX(x) | |
string = findSequence(x, delta_x) | |
print uncompress(string) | |
x = np.asarray([0,1]) | |
delta_x = computeDeltaX(x) | |
string = findSequence(x, delta_x) | |
print uncompress(string) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment