def overlapintervals(i1, i2): """ Calculate intersection of two lists of intervals. :param i1: list of intervals :param i2: list of intervals :return: list of intervals with overlap of both intervals only """ ollist = [] for i in i1: for j in i2: if j[0] < i[0]+i[1] and j[0]+j[1] > i[0]: ollist += [[max(i[0], j[0]), min(i[0]+i[1], j[0]+j[1])-max(i[0], j[0])]] return ollist def calcPrecisionRecall(detection, groundtruth, setlength): """ Calculated precision and recall for intervals in time series :param detection: array with detected intervals :param groundtruth: array with ground truth :param setlength: length of time series :return: precision, recall """ import numpy as np if len(groundtruth) == 0 and len(detection) == 0: precision = 1 recall = 1 else: # Turn detection into array detArray = IntervalsToBinary(detection, setlength) gtArray = IntervalsToBinary(groundtruth, setlength) if np.sum(gtArray) == 0: gtArray = -1 * (gtArray - 1) detArray = -1*(detArray-1) unique, counts = np.unique(detArray+gtArray, return_counts=True) countvalues = dict(zip(unique, counts)) tp = countvalues[2] if 2 in countvalues else 0 tn = countvalues[0] if 0 in countvalues else 0 unique, counts = np.unique(detArray-gtArray, return_counts=True) countvalues = dict(zip(unique, counts)) fp = countvalues[1] if 1 in countvalues else 0 unique, counts = np.unique(gtArray-detArray, return_counts=True) countvalues = dict(zip(unique, counts)) fn = countvalues[1] if 1 in countvalues else 0 precision = tp / (tp + fp) if tp + fp > 0 else 0 recall = tp / (fn + tp) if tp + fn > 0 else 0 #print(detection, groundtruth, precision, recall) return precision, recall