def auto_correlation(seq, start=0, end=None): avg = Analysis.avg(seq, start=start, end=end) var = Analysis.var(seq, start=start, end=end) res = OrderedDict() y = seq.y if not end: end = len(seq._seq) for shift in range(start, end): res[shift - start] = sum([(y[x] - avg) * (y[x + shift] - avg) for x in range(0, end - shift)]) / var return Sequence.from_dict( OrderedDict(zip(seq.x[start:end], res.values())))
def cross_correlation(first, second): if (len(first) != len(second)): raise ValueError("Sequences are not the same size") first_avg = Analysis.avg(first) second_avg = Analysis.avg(second) div = math.sqrt(Analysis.var(first) + Analysis.var(second)) res = [] f_y = first.y s_y = second.y for shift in range(len(first)): res.append( sum([(f_y[k] - first_avg) * (s_y[k + shift] - second_avg) for k in range(len(first) - shift)]) / div) return Sequence.from_dict(OrderedDict(zip(first.x, res)))
def dtf(seq): n = len(seq) y_tmp = seq.y res = [] for k in range(n): Re = 0 Im = 0 for t in range(n): angle = 2 * math.pi * t * k / n Re += y_tmp[t] * math.cos(angle) Im += y_tmp[t] * math.sin(angle) res.append(math.sqrt((Re / n)**2 + (Im / n)**2)) return Sequence.from_dict( OrderedDict(zip(seq.x[:n // 2:], res[:n // 2])))
def dtf(seq): n = len(seq) y_tmp = seq.y x_tmp = seq.x res = [] for k in range(n): Re = 0 Im = 0 for t in range(n): angle = 2 * math.pi * t * k / n Re += y_tmp[t] * math.cos(angle) Im += y_tmp[t] * math.sin(angle) res.append(math.sqrt((Re / n)**2 + (Im / n)**2)) freq_top = 1 / (2 * (x_tmp[1] - x_tmp[0])) freq_delta = 2 * freq_top / n x_tmp = [freq_delta * x for x in range(len(seq.x[:n // 2]))] return Sequence.from_dict(OrderedDict(zip(x_tmp, res[:n // 2])))
def untrend(seq, window_size=5): res = OrderedDict() for idx, x in enumerate(seq.x): res[x] = Analysis.avg(seq, max(0, idx - window_size), min(len(seq) - 1, idx + window_size)) return seq - Sequence.from_dict(res)