PreprocessorHelper.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package de.jplag.clustering;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.List;
  5. import java.util.stream.Collectors;
  6. import java.util.stream.DoubleStream;
  7. import org.apache.commons.math3.linear.Array2DRowRealMatrix;
  8. import org.apache.commons.math3.linear.RealMatrix;
  9. /**
  10. * Implements removal of zero rows / columns and calculation of original indices for classes implementing
  11. * {@link ClusteringPreprocessor}.
  12. */
  13. public class PreprocessorHelper {
  14. private IntegerMapping<Integer> mapping;
  15. /**
  16. * Removes disconnected edges from the input matrix.
  17. * @param connections similarity matrix
  18. * @return similarity matrix without zero rows / cols
  19. */
  20. public double[][] removeDisconnectedEntries(double[][] connections) {
  21. List<Integer> rowList = new ArrayList<>();
  22. mapping = new IntegerMapping<>(connections.length);
  23. RealMatrix similarity = new Array2DRowRealMatrix(connections, true);
  24. for (int i = 0; i < similarity.getRowDimension(); i++) {
  25. if (DoubleStream.of(similarity.getRow(i)).filter(x -> x > 0).findAny().isPresent()) {
  26. rowList.add(i);
  27. mapping.map(i);
  28. }
  29. }
  30. int[] preservedRows = rowList.stream().mapToInt(Integer::intValue).toArray();
  31. if (preservedRows.length == 0) {
  32. return new double[0][];
  33. }
  34. similarity = similarity.getSubMatrix(preservedRows, preservedRows);
  35. return similarity.getData();
  36. }
  37. /**
  38. * Implements the logic for {@link ClusteringPreprocessor#postProcessResult(Collection)}
  39. * @param result clustering result gained from preprocessed similarities
  40. * @return post processed clustering result
  41. */
  42. public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
  43. return result.stream().map(cluster -> cluster.stream().map(mapping::unmap).collect(Collectors.toList())).collect(Collectors.toList());
  44. }
  45. }