Optimal partitioning of similarity relations