Created
February 9, 2018 00:38
-
-
Save JasonKessler/1b6791e8593aa767118e6900ade0a3fb to your computer and use it in GitHub Desktop.
Pure Python ECDF With Linear Interpolation
This file contains hidden or 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 bisect | |
class ECDFPurePy(object): | |
''' | |
ECDF with linear interpolation | |
''' | |
def __init__(self, raw_list, min_possible, max_possible, resolution=1000): | |
''' | |
raw: sorted list or generator of numbers | |
''' | |
self.resolution_ = resolution | |
self.min_possible_ = min_possible | |
self.max_possible_ = max_possible | |
if raw_list[0] < self.min_possible_: | |
raise Exception("First value of raw_list is less than min_possible") | |
if raw_list[-1] > self.max_possible_: | |
raise Exception("Last value of raw_list is bigger than max_possible") | |
if resolution > len(raw_list): | |
raw_ar = raw_list | |
else: | |
raw_ar = (raw_list[i] for i in range(0, len(raw_list), len(raw_list)/resolution)) | |
self.ar_ = [] | |
self.idx_ = [] | |
last_val = None | |
self.last_idx_ = None | |
for i, v in enumerate(raw_ar): | |
self.last_idx_ = i | |
if i == 0 or v != last_val: | |
self.ar_.append(v) | |
self.idx_.append(i) | |
last_val = v | |
def get(self, x): | |
if x <= self.min_possible_: | |
to_ret = 0 | |
elif x >= self.max_possible_: | |
to_ret = 1 | |
else: | |
raw_idx = bisect.bisect_left(self.ar_, x) | |
try: | |
i = self.idx_[raw_idx] | |
except: | |
i = self.last_idx_ | |
if i == 0: | |
val = self.ar_[0] | |
adjustment = (x - self.min_possible_)*1./(val - self.min_possible_) | |
effective_index = adjustment | |
elif i == self.last_idx_: | |
last_val = self.ar_[-1] | |
adjustment = (x - last_val)*1./(self.max_possible_ - last_val) | |
effective_index = i + adjustment | |
else: | |
val = self.ar_[raw_idx] | |
effective_index = i + 1 | |
if x < val: | |
effective_index -= 1 | |
if i > 0: | |
prev_val = self.ar_[raw_idx - 1] | |
adjustment = (x - prev_val)*1./(val - prev_val) | |
effective_index += adjustment | |
to_ret = (effective_index)*1./(self.last_idx_ + 2) | |
return to_ret | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment