def calculate_IOU(anomalies, label_window):
    """
    Calculates Intersection over Union (IoU) for anomalous windows detected by the algorithm. Since a single window can contain multiple       
    true anomalous windows, anomaly_region keeps track of how many true windows each detected window intersects. This information is           
    required in the calculation of recall.
    :param anomalies (type: list): anomaly windows generated by the algorithm, each item is a tuple with start and end index
    :param label_window (type: list): true anomalous windows on the data, each item is a tuple with start and end index
    :return iou (type: list): intersection over union if the anomaly windows overlap with actual labels else 0
    :return anomaly_region (type: list): list of labels associated with each anomaly window since there could be multiple
    """
    
    iou = []
    anomaly_region = []
   
    #IoU calculation for each anomaly window intersection with all other true windows
    for i in range(len(anomalies)):
        iou_i = 0
        region = []
        start = anomalies[i][0]
        end   = anomalies[i][1]
        for j in range(len(label_window)):

            if start <= label_window[j][0] and end >= label_window[j][0]:
                overlap = 1 + min(label_window[j][1], end) - label_window[j][0]
                union   = 1 + max(label_window[j][1], end)- start
                iou_i += (float(overlap)/union)
                region.append(j)

            elif start >= label_window[j][0] and end <= label_window[j][1]:
                overlap = 1 + (end - start)
                union   = 1 + (label_window[j][1]- label_window[j][0]) 
                iou_i += (float(overlap)/union)
                region.append(j)
                
            elif start <= label_window[j][1] and end >= label_window[j][1]:
                overlap = 1 + (label_window[j][1] - start)
                union   = 1 + (end - label_window[j][0]) 
                iou_i += (float(overlap)/union)
                region.append(j)
                
        anomaly_region.append(region)
        iou.append(iou_i)  
    
    return iou, anomaly_region