Skip to content

Commit

Permalink
Merge pull request #62 from microprediction/master
Browse files Browse the repository at this point in the history
from_dict
  • Loading branch information
CamDavidsonPilon authored Oct 12, 2022
2 parents bf90fb1 + 4cd9d32 commit e35cfd7
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def read(fname):


setup(name='tdigest',
version='0.5.2.2',
version='0.6.0.1',
description='T-Digest data structure',
author='Cam Davidson-pilon',
author_email='[email protected]',
Expand Down
11 changes: 11 additions & 0 deletions tdigest/tdigest.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,17 @@ def to_dict(self):
"""
return {'n':self.n, 'delta':self.delta, 'K':self.K, 'centroids':self.centroids_to_list()}

@classmethod
def from_dict(cls, d:dict):
t = TDigest()
for c in d['centroids']:
ci = Centroid(c['m'],c['c'])
t.C.insert(c['m'], ci)
t.K = d['K']
t.delta = d['delta']
t.n = d['n']
return t

def update_from_dict(self, dict_values):
"""
Updates TDigest object with dictionary values.
Expand Down
16 changes: 16 additions & 0 deletions tests/test_tdigest.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,22 @@ def test_to_dict(self, empty_tdigest, sample_dict):
td.update(3)
assert td.to_dict() == sample_dict

def test_from_dict(self, empty_tdigest, sample_dict):
td0 = TDigest().update_from_dict(sample_dict)
td1 = TDigest.from_dict(sample_dict)
for val in [-2,4,17]:
assert abs(td0.cdf(val)-td1.cdf(val))<0.0001

def test_from_dict_random(self, example_random_data):
import numpy as np
t = TDigest()
t.batch_update(example_random_data)
td = t.to_dict()
td0 = TDigest().update_from_dict(td)
td1 = TDigest.from_dict(td)
for val in [0.2,0.5,1.4]:
assert abs(td0.cdf(val)-td1.cdf(val))<0.0001

def test_centroids_to_list(self, empty_tdigest, sample_centroid_list):
td = empty_tdigest
td.update(1)
Expand Down

0 comments on commit e35cfd7

Please sign in to comment.