deduplicate-lib 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. deduplicate_lib-0.0.1/LICENSE +21 -0
  2. deduplicate_lib-0.0.1/PKG-INFO +59 -0
  3. deduplicate_lib-0.0.1/README.md +43 -0
  4. deduplicate_lib-0.0.1/pyproject.toml +28 -0
  5. deduplicate_lib-0.0.1/setup.cfg +4 -0
  6. deduplicate_lib-0.0.1/src/deduplicate_lib/__init__.py +1 -0
  7. deduplicate_lib-0.0.1/src/deduplicate_lib/core/__init__.py +0 -0
  8. deduplicate_lib-0.0.1/src/deduplicate_lib/core/duplicate_detection_algorithm.py +98 -0
  9. deduplicate_lib-0.0.1/src/deduplicate_lib/core/plugin_registry.py +30 -0
  10. deduplicate_lib-0.0.1/src/deduplicate_lib/core/tolerance_calculator.py +144 -0
  11. deduplicate_lib-0.0.1/src/deduplicate_lib/plugins/__init__.py +0 -0
  12. deduplicate_lib-0.0.1/src/deduplicate_lib/plugins/duplicate_detection_algorithms/__init__.py +0 -0
  13. deduplicate_lib-0.0.1/src/deduplicate_lib/plugins/duplicate_detection_algorithms/distance_matrix.py +50 -0
  14. deduplicate_lib-0.0.1/src/deduplicate_lib/plugins/duplicate_detection_algorithms/multi_hashing.py +129 -0
  15. deduplicate_lib-0.0.1/src/deduplicate_lib/plugins/tolerance_calculators/__init__.py +0 -0
  16. deduplicate_lib-0.0.1/src/deduplicate_lib/plugins/tolerance_calculators/natural_tolerance_plateau_probe.py +97 -0
  17. deduplicate_lib-0.0.1/src/deduplicate_lib/plugins/tolerance_calculators/perturbed_dataset_reclustering.py +26 -0
  18. deduplicate_lib-0.0.1/src/deduplicate_lib.egg-info/PKG-INFO +59 -0
  19. deduplicate_lib-0.0.1/src/deduplicate_lib.egg-info/SOURCES.txt +20 -0
  20. deduplicate_lib-0.0.1/src/deduplicate_lib.egg-info/dependency_links.txt +1 -0
  21. deduplicate_lib-0.0.1/src/deduplicate_lib.egg-info/requires.txt +7 -0
  22. deduplicate_lib-0.0.1/src/deduplicate_lib.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Julian Holland
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: deduplicate_lib
3
+ Version: 0.0.1
4
+ Summary: A Python package for deduplicating data.
5
+ Author-email: Julian Holland <holland@fhi.mpg.de>
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: numpy
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest; extra == "dev"
12
+ Requires-Dist: pytest-mock; extra == "dev"
13
+ Requires-Dist: coverage; extra == "dev"
14
+ Requires-Dist: ruff; extra == "dev"
15
+ Dynamic: license-file
16
+
17
+ <div align="center">
18
+ <h1><code>deduplicate_lib</code></h1>
19
+ <p><i>deduplication algorithms in python</i></p>
20
+ </div>
21
+
22
+ ***
23
+ ## Key Features
24
+
25
+
26
+ - Easy to use deduplication algorithms for any vector array
27
+ - Suite of tolerance tuning algorithms to help you find the right tolerance value for your system
28
+ - Suite of benchmarking tools to ensure rigor, accuracy, and speed (not yet implemented)
29
+ - Factory Plugin architecture, for easy extensibility and modification
30
+
31
+ ***
32
+ ## Implemented Algorithms
33
+
34
+ - Distance Matrix (Simple, accurate, expensive): Computes the distance matrix for all vectors and determines duplicates by finding those that fall below a given distance
35
+ - Multi Hashing (Fast): Smears and rounds the vectors using a normal distribution and computes the hashes for each which are then used to determine duplicates by proportion of hash clashes.
36
+ <!-- - Locality Sensitive Hashing (Fast, Accurate) -->
37
+
38
+ ## Quick Start
39
+ install using pip
40
+ ```bash
41
+ pip install deduplicate_lib
42
+ ```
43
+
44
+ load your data into python
45
+
46
+ ```python
47
+ from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
48
+
49
+ # define your paramerters in the MultiHash object
50
+ dda=MultiHash(
51
+ tolerance=0.01,
52
+ dataset_array: your_data_array,
53
+ perturbations: int = 200,
54
+ )
55
+
56
+ print(dda.get_dataset_unique_structures())
57
+ ```
58
+
59
+ A more detailed example can be seen in the `examples` directory
@@ -0,0 +1,43 @@
1
+ <div align="center">
2
+ <h1><code>deduplicate_lib</code></h1>
3
+ <p><i>deduplication algorithms in python</i></p>
4
+ </div>
5
+
6
+ ***
7
+ ## Key Features
8
+
9
+
10
+ - Easy to use deduplication algorithms for any vector array
11
+ - Suite of tolerance tuning algorithms to help you find the right tolerance value for your system
12
+ - Suite of benchmarking tools to ensure rigor, accuracy, and speed (not yet implemented)
13
+ - Factory Plugin architecture, for easy extensibility and modification
14
+
15
+ ***
16
+ ## Implemented Algorithms
17
+
18
+ - Distance Matrix (Simple, accurate, expensive): Computes the distance matrix for all vectors and determines duplicates by finding those that fall below a given distance
19
+ - Multi Hashing (Fast): Smears and rounds the vectors using a normal distribution and computes the hashes for each which are then used to determine duplicates by proportion of hash clashes.
20
+ <!-- - Locality Sensitive Hashing (Fast, Accurate) -->
21
+
22
+ ## Quick Start
23
+ install using pip
24
+ ```bash
25
+ pip install deduplicate_lib
26
+ ```
27
+
28
+ load your data into python
29
+
30
+ ```python
31
+ from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
32
+
33
+ # define your paramerters in the MultiHash object
34
+ dda=MultiHash(
35
+ tolerance=0.01,
36
+ dataset_array: your_data_array,
37
+ perturbations: int = 200,
38
+ )
39
+
40
+ print(dda.get_dataset_unique_structures())
41
+ ```
42
+
43
+ A more detailed example can be seen in the `examples` directory
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "deduplicate_lib"
3
+ dynamic = ["version"]
4
+ description = "A Python package for deduplicating data."
5
+ authors = [
6
+ { name="Julian Holland", email="holland@fhi.mpg.de" }
7
+ ]
8
+ readme = "README.md"
9
+ requires-python = ">=3.8"
10
+ dependencies = [
11
+ "numpy",
12
+ ]
13
+
14
+ [tool.setuptools]
15
+ package-dir = {"" = "src"}
16
+
17
+ [tool.setuptools.dynamic]
18
+ version = {attr = "deduplicate_lib.__version__"}
19
+
20
+ [project.optional-dependencies]
21
+ dev = ["pytest", "pytest-mock", "coverage", "ruff"]
22
+
23
+ [tool.pytest.ini_options]
24
+ testpaths = ["tests"]
25
+
26
+ [build-system]
27
+ requires = ["setuptools>=61.0"]
28
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
@@ -0,0 +1,98 @@
1
+ import numpy as np
2
+ from abc import ABC, abstractmethod
3
+
4
+ def euclidean_distance(v1, v2):
5
+ return float(np.linalg.norm(v1 - v2))
6
+
7
+ def manhattan_distance(v1, v2):
8
+ return np.sum(np.abs(v1 - v2))
9
+
10
+ def cosine_distance(v1, v2):
11
+ return 1 - np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
12
+
13
+ def hamming_distance(v1, v2):
14
+ return np.sum(v1 != v2)
15
+
16
+ DISTANCE_FUNCTIONS = {
17
+ "euclidean": euclidean_distance,
18
+ "manhattan": manhattan_distance,
19
+ "cosine": cosine_distance,
20
+ "hamming": hamming_distance,
21
+ }
22
+ class DuplicateDetectionAlgorithm(ABC):
23
+ ALLOWED_DISTANCES = DISTANCE_FUNCTIONS
24
+ def __init__(
25
+ self,
26
+ tolerance: float,
27
+ input_vector: np.ndarray = np.array([]),
28
+ dataset_array: np.ndarray = np.array([]),
29
+ distance_matrix: np.ndarray = np.array([]),
30
+ distance_metric: str = "euclidean",
31
+ ) -> None:
32
+ self.tolerance = tolerance
33
+ self.input_vector = input_vector
34
+ self.dataset_array = dataset_array
35
+ self.distance_matrix = distance_matrix
36
+ self.distance_metric = distance_metric
37
+
38
+ # In DuplicateDetectionAlgorithm
39
+
40
+ @property
41
+ def distance_metric(self):
42
+ return self._distance_metric
43
+
44
+ @distance_metric.setter
45
+ def distance_metric(self, value):
46
+ if value not in self.ALLOWED_DISTANCES:
47
+ raise ValueError(
48
+ f"Unsupported distance metric: {value}, "
49
+ f"supported metrics are: {list(self.ALLOWED_DISTANCES.keys())}"
50
+ )
51
+ self._distance_metric = value
52
+ self.distance_function = self.ALLOWED_DISTANCES[value]
53
+
54
+ def calculate_distance(self, vector1: np.ndarray, vector2: np.ndarray) -> float:
55
+ return self.distance_function(vector1, vector2)
56
+
57
+ def compute_distance_matrix(self, vector_array: np.ndarray) -> None:
58
+ """Compute the distance matrix for the dataset from scratch."""
59
+ num_samples = vector_array.shape[0]
60
+ self.distance_matrix = np.zeros((num_samples, num_samples))
61
+ for i in range(num_samples):
62
+ for j in range(i + 1, num_samples):
63
+ distance = self.calculate_distance(
64
+ vector_array[i], vector_array[j]
65
+ )
66
+ self.distance_matrix[i, j] = distance
67
+ self.distance_matrix[j, i] = distance
68
+
69
+ def get_new_distance_matrix_column(self, vector_array: np.ndarray) -> np.ndarray:
70
+ """Calculates the distance matrix for the distances of a new input vector.
71
+
72
+ Returns:
73
+ np.ndarray: A 1D array containing the distances from the input vector to each vector in the dataset.
74
+ """
75
+ num_samples = vector_array.shape[0]
76
+ new_distances = np.zeros(num_samples)
77
+ for i in range(num_samples):
78
+ new_distances[i] = self.calculate_distance(
79
+ self.input_vector, vector_array[i]
80
+ )
81
+ return new_distances
82
+
83
+ def add_new_vector_to_distance_matrix(self, vector_array: np.ndarray) -> None:
84
+ """Add a new input vector to the distance matrix."""
85
+ new_distances = self.get_new_distance_matrix_column(vector_array)
86
+ self.distance_matrix = np.hstack(
87
+ (self.distance_matrix, new_distances[:, np.newaxis])
88
+ )
89
+ new_row = np.append(new_distances, 0) # Distance to itself is 0
90
+ self.distance_matrix = np.vstack((self.distance_matrix, new_row))
91
+
92
+ @abstractmethod
93
+ def duplicate_check(self) -> bool:
94
+ pass
95
+
96
+ @abstractmethod
97
+ def get_dataset_unique_structures(self) -> int:
98
+ pass
@@ -0,0 +1,30 @@
1
+ # core/plugin_registry.py
2
+ from typing import Dict, Type
3
+
4
+ _REGISTRY: Dict[str, Dict[str, Type]] = {
5
+ "duplicate_detection_algorithm": {},
6
+ "tolerance_calculator": {},
7
+ "benchmark": {},
8
+ }
9
+
10
+
11
+ def register_plugin(kind: str, name: str):
12
+ def decorator(cls):
13
+ if kind not in _REGISTRY:
14
+ raise ValueError(f"Unknown plugin kind: {kind}")
15
+ _REGISTRY[kind][name] = cls
16
+ return cls
17
+
18
+ return decorator
19
+
20
+
21
+ def get_plugin_class(kind: str, name: str):
22
+ try:
23
+ return _REGISTRY[kind][name]
24
+ except KeyError as e:
25
+ raise KeyError(f"No plugin '{name}' registered for kind '{kind}'") from e
26
+
27
+
28
+ def create_plugin(kind: str, name: str, **kwargs):
29
+ cls = get_plugin_class(kind, name)
30
+ return cls(**kwargs)
@@ -0,0 +1,144 @@
1
+ import numpy as np
2
+ from abc import ABC, abstractmethod
3
+ from deduplicate_lib.core.duplicate_detection_algorithm import DuplicateDetectionAlgorithm
4
+ from contextlib import contextmanager
5
+ import warnings
6
+
7
+
8
+ class ToleranceCalculator(ABC):
9
+ def __init__(
10
+ self,
11
+ duplicate_detection_algorithm_object: DuplicateDetectionAlgorithm,
12
+ tolerance_dataset_array: np.ndarray = np.array([]),
13
+ perturbations_per_vector: int = 1,
14
+ perturbation_scale: float = 0.1,
15
+ binary_search_steps: int = 20,
16
+ ) -> None:
17
+ self.tolerance_dataset_array = tolerance_dataset_array
18
+ self.duplicate_detection_algorithm_object = duplicate_detection_algorithm_object
19
+ self.perturbations_per_vector = perturbations_per_vector
20
+ self.perturbation_scale = perturbation_scale
21
+ self.binary_search_steps = binary_search_steps
22
+
23
+ @contextmanager
24
+ def temp_attr(self, obj, attr, value):
25
+ original = getattr(obj, attr)
26
+ setattr(obj, attr, value)
27
+ try:
28
+ yield
29
+ finally:
30
+ setattr(obj, attr, original)
31
+
32
+ def binary_search_tolerance(
33
+ self,
34
+ target_unique_vectors: int,
35
+ find_largest_tolerance_for_target: bool = True,
36
+ ) -> float:
37
+ """
38
+ Binary search to find the tolerance that yields the target number of unique structures.
39
+ """
40
+ best_min = 0.0
41
+ # to ensure that our original best max value is above the tolerance value that yields all structures as the same, we tie it to the relative standard deviation of the dataset array. A more diverse dataset will have a higher standard deviation and thus require a higher tolerance to yield all structures as the same, while a more homogenous dataset will have a lower standard deviation and thus require a lower tolerance to yield all structures as the same.
42
+ ptp=np.ptp(self.tolerance_dataset_array)
43
+ abs_std=np.mean(np.std(self.tolerance_dataset_array, axis=0))
44
+ best_max = (ptp + abs_std) * self.duplicate_detection_algorithm_object.dataset_array.shape[1]
45
+ tolerance = best_max
46
+
47
+ exact_list = []
48
+ all_diff_dict = {}
49
+
50
+ if self.binary_search_steps <= 0:
51
+ warnings.warn(f"Binary search called with {self.binary_search_steps} steps. No binary search performed.\n Returning tolerance of half the range of the perturbed dataset: {tolerance}.")
52
+ return tolerance
53
+
54
+ # temporarily set the dataset_array to the tolerance_dataset_array for the duration of the search
55
+ print(self.duplicate_detection_algorithm_object.distance_matrix.shape)
56
+ with self.temp_attr(
57
+ self.duplicate_detection_algorithm_object,
58
+ "dataset_array",
59
+ self.tolerance_dataset_array,
60
+ ):
61
+ for _ in range(self.binary_search_steps):
62
+ # temporarily set the tolerance for the duration of this iteration of the search
63
+ with self.temp_attr(
64
+ self.duplicate_detection_algorithm_object, "tolerance", tolerance
65
+ ):
66
+
67
+ unique_vectors = self.duplicate_detection_algorithm_object.get_dataset_unique_structures()
68
+ all_diff_dict[tolerance] = unique_vectors
69
+ if unique_vectors < target_unique_vectors: # loosen tolerance
70
+ best_max = tolerance
71
+ elif unique_vectors > target_unique_vectors: # tighten tolerance
72
+ best_min = tolerance
73
+
74
+ else:
75
+ exact_list.append(tolerance)
76
+ if (
77
+ target_unique_vectors
78
+ == len(
79
+ self.duplicate_detection_algorithm_object.dataset_array
80
+ )
81
+ or find_largest_tolerance_for_target
82
+ ):
83
+ best_min = tolerance
84
+ else:
85
+ best_max = tolerance
86
+
87
+ tolerance = (best_min + best_max) / 2
88
+ # Find the best exact value if it exists, otherwise find the closest value
89
+ if len(exact_list) > 0:
90
+ if find_largest_tolerance_for_target:
91
+ tolerance = max(exact_list)
92
+ else:
93
+ tolerance = min(exact_list)
94
+ else:
95
+
96
+ tolerance = [
97
+ tol
98
+ for tol, diff in all_diff_dict.items()
99
+ if diff == min(all_diff_dict.values())
100
+ ][0]
101
+ warnings.warn(f"No exact tolerance found for target of {target_unique_vectors} unique vectors during binary search.\n Returning closest tolerance found: {tolerance} with {all_diff_dict[tolerance]} unique vectors.")
102
+ print(all_diff_dict)
103
+ return tolerance
104
+
105
+ def create_perturbed_dataset(self, seed: int = 803):
106
+ """
107
+ Create a perturbed dataset by adding random noise to the original dataset. The original dataset is included as the first vector for each original vector, followed by the perturbed versions of that vector.
108
+ """
109
+ rng=np.random.default_rng(seed)
110
+ self.tolerance_dataset_array = np.zeros(
111
+ (
112
+ len(self.duplicate_detection_algorithm_object.dataset_array)
113
+ * self.perturbations_per_vector,
114
+ self.duplicate_detection_algorithm_object.dataset_array.shape[1],
115
+ )
116
+ )
117
+
118
+ for i, vector in enumerate(self.duplicate_detection_algorithm_object.dataset_array):
119
+ self.tolerance_dataset_array[i * self.perturbations_per_vector] = (
120
+ self.duplicate_detection_algorithm_object.dataset_array[i]
121
+ )
122
+ for j in range(1, self.perturbations_per_vector):
123
+ perturbation = rng.normal(
124
+ loc=0.0, scale=self.perturbation_scale, size=vector.shape
125
+ )
126
+ perturbed_vector = vector + perturbation
127
+ self.tolerance_dataset_array[i * self.perturbations_per_vector + j] = (
128
+ perturbed_vector
129
+ )
130
+
131
+ def _ensure_perturbed_dataset(self):
132
+ if (
133
+ self.tolerance_dataset_array.shape[0]
134
+ != len(self.duplicate_detection_algorithm_object.dataset_array)
135
+ * self.perturbations_per_vector
136
+ ):
137
+ warnings.warn(
138
+ "Perturbed dataset is not properly initialized. Recreating it.\nEnsure a perturbed dataset is set prior finding tolerance."
139
+ )
140
+ self.create_perturbed_dataset()
141
+
142
+ @abstractmethod
143
+ def calculate_tolerance(self) -> float:
144
+ pass
@@ -0,0 +1,50 @@
1
+ from deduplicate_lib.core.duplicate_detection_algorithm import DuplicateDetectionAlgorithm
2
+ from deduplicate_lib.core.plugin_registry import register_plugin
3
+ import numpy as np
4
+
5
+
6
+ @register_plugin(kind="duplicate_detection_algorithm", name="distance_matrix")
7
+ class DistanceMatrix(DuplicateDetectionAlgorithm):
8
+ def __init__(
9
+ self,
10
+ tolerance: float,
11
+ input_vector: np.ndarray,
12
+ dataset_array: np.ndarray,
13
+ distance_matrix: np.ndarray = np.array([]),
14
+ distance_metric: str = "euclidean",
15
+ ) -> None:
16
+ super().__init__(
17
+ tolerance, input_vector, dataset_array, distance_matrix, distance_metric
18
+ )
19
+
20
+ def __str__(self) -> str:
21
+ return f"DistanceMatrix(tolerance={self.tolerance}, distance_metric={self.distance_metric})"
22
+
23
+ def _ensure_distance_matrix(self):
24
+ if self.distance_matrix.shape[0] != self.dataset_array.shape[0]:
25
+ # warnings.warn(f"Distance matrix shape does not match dataset; recomputing.{self.dataset_array.shape[0]}, {self.distance_matrix.shape[0]}")
26
+ # self.compute_distance_matrix(self.dataset_array)
27
+ print(self.dataset_array.shape, self.distance_matrix.shape)
28
+ raise ValueError("Distance matrix shape does not match dataset; recomputing is currently disabled to avoid long computations during testing. Please compute the distance matrix manually and assign it to the duplicate detection algorithm object before duplication checks.")
29
+
30
+ def duplicate_check(self) -> bool:
31
+ return bool(
32
+ np.any(
33
+ self.get_new_distance_matrix_column(self.dataset_array) < self.tolerance
34
+ )
35
+ )
36
+
37
+ def get_dataset_unique_structures(self) -> int:
38
+ self._ensure_distance_matrix()
39
+ unique_structures = 1
40
+
41
+ for i in range(1, self.distance_matrix.shape[0]):
42
+ imask = np.arange(self.distance_matrix.shape[0]) != i
43
+ if np.all(self.distance_matrix[i][imask] >= self.tolerance):
44
+ unique_structures += 1
45
+ return unique_structures
46
+
47
+ def pre_dda_processing(self, input_dataset_array: np.ndarray | None = None, *args, **kwargs) -> None:
48
+ if input_dataset_array is None:
49
+ input_dataset_array = self.dataset_array
50
+ self.compute_distance_matrix(input_dataset_array)
@@ -0,0 +1,129 @@
1
+ from deduplicate_lib.core.duplicate_detection_algorithm import (
2
+ DuplicateDetectionAlgorithm,
3
+ hamming_distance,
4
+ )
5
+ from deduplicate_lib.core.plugin_registry import register_plugin
6
+
7
+ import numpy as np
8
+ import warnings
9
+
10
+
11
+ @register_plugin(kind="duplicate_detection_algorithm", name="multi_hashing")
12
+ class MultiHashing(DuplicateDetectionAlgorithm):
13
+ ALLOWED_DISTANCES = {"hamming": hamming_distance}
14
+
15
+ def __init__(
16
+ self,
17
+ tolerance: float,
18
+ input_vector: np.ndarray,
19
+ dataset_array: np.ndarray,
20
+ perturbations: int = 200,
21
+ seed: int = 803,
22
+ pertrubation_array: np.ndarray = np.array([]),
23
+ acceptance_threshold: float = 0.5,
24
+ distance_metric: str = "hamming",
25
+ distance_matrix: np.ndarray = np.array([]),
26
+ hash_vector_array: np.ndarray = np.array([]),
27
+ ) -> None:
28
+ super().__init__(
29
+ tolerance=tolerance,
30
+ input_vector=input_vector,
31
+ dataset_array=dataset_array,
32
+ distance_metric=distance_metric,
33
+ distance_matrix=distance_matrix,
34
+ )
35
+ self.seed = seed
36
+ self.acceptance_threshold = acceptance_threshold
37
+ self.perturbations = perturbations
38
+ self.hash_vector_array = hash_vector_array
39
+ self.perturbation_array = pertrubation_array
40
+
41
+ def __str__(self) -> str:
42
+ return f"MultiHashing(tolerance={self.tolerance}, perturbations={self.perturbations}, acceptance_threshold={self.acceptance_threshold})"
43
+
44
+ def set_perturbation_array(self) -> None:
45
+ rng = np.random.default_rng(self.seed)
46
+ self.perturbation_array = np.abs(
47
+ rng.normal(loc=0.0, scale=1.0, size=self.perturbations)
48
+ )
49
+
50
+ def _ensure_perturbation_array(self):
51
+ if self.perturbation_array.shape[0] != self.perturbations:
52
+ warnings.warn(
53
+ "Perturbation array shape does not match expected number of perturbations; recomputing. \nAssign the perturbation array prior duplication checks to avoid this warning."
54
+ )
55
+ self.set_perturbation_array()
56
+
57
+ def round_to_tolerance(self) -> np.ndarray:
58
+ rounded_vector = np.round(self.input_vector / self.tolerance) * self.tolerance
59
+ return rounded_vector
60
+
61
+ def create_hash_vector(self) -> np.ndarray:
62
+ self._ensure_perturbation_array()
63
+ hash_vector = np.zeros(self.perturbations)
64
+ for i in range(self.perturbations):
65
+ hash_vector[i] = hash(
66
+ (self.round_to_tolerance() * self.perturbation_array[i]).tobytes()
67
+ )
68
+ return hash_vector
69
+
70
+ def create_hash_vector_array(self) -> np.ndarray:
71
+ """Creates the hash vector array for the dataset. Only unique hash values are stored for each perturbation.
72
+
73
+ Returns:
74
+ np.ndarray: A 2D array containing the hash values for each vector in the dataset for each perturbation.
75
+ """
76
+ self.hash_vector_array = np.zeros(
77
+ (self.dataset_array.shape[0], self.perturbations), dtype=int
78
+ )
79
+ self._ensure_perturbation_array()
80
+ for i in range(self.dataset_array.shape[0]):
81
+ self.input_vector = self.dataset_array[i]
82
+ hash_vector = self.create_hash_vector()
83
+ for j in range(self.perturbations):
84
+ if hash_vector[j] not in self.hash_vector_array[:, j]:
85
+ self.hash_vector_array[i, j] = hash_vector[j]
86
+ return self.hash_vector_array
87
+
88
+ def _ensure_hash_vector_array(self):
89
+ if self.hash_vector_array.shape[0] != self.dataset_array.shape[0]:
90
+ warnings.warn(
91
+ "Hash vector array shape does not match dataset; recomputing."
92
+ )
93
+ self.create_hash_vector_array()
94
+
95
+ def duplicate_check(self) -> bool:
96
+ """duplicate check against dataset using multi-hashing approach.
97
+
98
+ Returns:
99
+ bool: True if a duplicate is detected, False otherwise.
100
+ """
101
+ self._ensure_hash_vector_array()
102
+ hash_vector = self.create_hash_vector()
103
+
104
+ clash_vector = np.zeros(self.perturbations, dtype=bool)
105
+ for hash_index, hash_value in enumerate(hash_vector):
106
+ if hash_value in self.hash_vector_array[:, hash_index]:
107
+ clash_vector[hash_index] = True
108
+ duplicate_vote_array = np.sum(clash_vector) / self.perturbations
109
+
110
+ duplicate_structure = duplicate_vote_array >= self.acceptance_threshold
111
+
112
+ return bool(duplicate_structure)
113
+
114
+ def get_dataset_unique_structures(self) -> int:
115
+ """Counts the number of unique structures in the dataset by checking for hash value clashes across the dataset for each perturbation.
116
+
117
+ Returns:
118
+ int: The number of unique structures in the dataset.
119
+ """
120
+ self.create_hash_vector_array()
121
+ clash_array = np.zeros((self.hash_vector_array.shape), dtype=bool)
122
+ clash_array[np.nonzero(self.hash_vector_array)] = True
123
+ return np.sum(
124
+ np.sum(clash_array, axis=1) / self.perturbations
125
+ >= self.acceptance_threshold
126
+ )
127
+
128
+ def pre_dda_processing(self, *args, **kwargs) -> None:
129
+ self.set_perturbation_array()
@@ -0,0 +1,97 @@
1
+
2
+ from deduplicate_lib.core.tolerance_calculator import ToleranceCalculator
3
+ from deduplicate_lib.core.duplicate_detection_algorithm import DuplicateDetectionAlgorithm
4
+ from deduplicate_lib.core.plugin_registry import register_plugin
5
+ import numpy as np
6
+ import warnings
7
+
8
+
9
+ @register_plugin("tolerance_calculator", "natural_tolerance_plateau_probe")
10
+ class NaturalTolerancePlateauProbe(ToleranceCalculator):
11
+ def __init__(
12
+ self,
13
+ duplicate_detection_algorithm_object: DuplicateDetectionAlgorithm,
14
+ tolerance_dataset_array: np.ndarray = np.array([]),
15
+ perturbations_per_vector: int = 1,
16
+ perturbation_scale: float = 0.1,
17
+ binary_search_steps: int = 50,
18
+ probe_steps: int = 100,
19
+ ) -> None:
20
+ super().__init__(
21
+ duplicate_detection_algorithm_object=duplicate_detection_algorithm_object,
22
+ tolerance_dataset_array=tolerance_dataset_array,
23
+ perturbations_per_vector=perturbations_per_vector,
24
+ perturbation_scale=perturbation_scale,
25
+ binary_search_steps=binary_search_steps,
26
+ )
27
+ self.probe_steps = probe_steps
28
+
29
+ def __str__(self) -> str:
30
+ return f"NaturalTolerancePlateauProbe(perturbations_per_vector={self.perturbations_per_vector}, perturbation_scale={self.perturbation_scale}, dda={str(self.duplicate_detection_algorithm_object).split('(')[0]})"
31
+
32
+ def tolerance_probe(
33
+ self, lower_tolerance: float, upper_tolerance: float, tolerance_steps: float
34
+ ) -> dict:
35
+ tolerance_results = {}
36
+ with self.temp_attr(
37
+ self.duplicate_detection_algorithm_object,
38
+ "dataset_array",
39
+ self.tolerance_dataset_array,
40
+ ):
41
+ for tol in np.linspace(lower_tolerance, upper_tolerance, tolerance_steps):
42
+ with self.temp_attr(
43
+ self.duplicate_detection_algorithm_object, "tolerance", tol
44
+ ):
45
+ self.duplicate_detection_algorithm_object.tolerance = tol
46
+ unique_structures = self.duplicate_detection_algorithm_object.get_dataset_unique_structures()
47
+ tolerance_results[tol] = unique_structures
48
+ return tolerance_results
49
+
50
+ def find_plateaus(self, tolerance_results: dict, datapoints_to_calculate_gradient: int = 3, plateau_threshold: float = 1e-3) -> tuple:
51
+ sorted_tols = sorted(tolerance_results.keys())
52
+ unique_counts = [tolerance_results[tol] for tol in sorted_tols]
53
+
54
+ # detect plateaus by calculating the gradient of unique_counts with respect to tolerance and finding where it is close to zero
55
+ plateau_log = np.zeros(len(sorted_tols), dtype=bool)
56
+ for i in range(len(unique_counts) - datapoints_to_calculate_gradient):
57
+ gradient = (
58
+ unique_counts[i + datapoints_to_calculate_gradient] - unique_counts[i]
59
+ ) / (sorted_tols[i + datapoints_to_calculate_gradient] - sorted_tols[i])
60
+ if abs(gradient) < plateau_threshold: # Threshold for plateau detection
61
+ plateau_log[i] = True
62
+ # Record the start and end of each plateau and its length
63
+ plateau_lengths = []
64
+ for i in range(len(plateau_log)):
65
+ if plateau_log[i]:
66
+ if not plateau_log[i - 1]:
67
+ start = i
68
+ else:
69
+ if plateau_log[i - 1]:
70
+ end = i
71
+ plateau_lengths.append(
72
+ (sorted_tols[start], sorted_tols[end], end - start)
73
+ )
74
+
75
+ return plateau_lengths
76
+
77
+ def calculate_tolerance(self) -> float:
78
+ self._ensure_perturbed_dataset()
79
+ all_same_tolerance = self.binary_search_tolerance(
80
+ target_unique_vectors=1, find_largest_tolerance_for_target=False
81
+ )
82
+ all_different_tolerance = self.binary_search_tolerance(
83
+ target_unique_vectors=len(self.tolerance_dataset_array),
84
+ find_largest_tolerance_for_target=True,
85
+ )
86
+ probe_results = self.tolerance_probe(
87
+ all_same_tolerance, all_different_tolerance, self.probe_steps
88
+ )
89
+ plateaus = self.find_plateaus(probe_results)
90
+ if len(plateaus) == 0:
91
+ warnings.warn(
92
+ "No plateaus found in tolerance probe. Consider adding in perturbed structures and/or increasing dataset size.\nReturning average of all same and all different tolerance as fallback."
93
+ )
94
+ return (all_same_tolerance + all_different_tolerance) / 2
95
+ else:
96
+ longest_plateau = max(plateaus, key=lambda x: x[2])
97
+ return (longest_plateau[0] + longest_plateau[1]) / 2
@@ -0,0 +1,26 @@
1
+ from deduplicate_lib.core.tolerance_calculator import ToleranceCalculator
2
+ from deduplicate_lib.core.plugin_registry import register_plugin
3
+
4
+
5
+ @register_plugin("tolerance_calculator", "perturbed_dataset_reclustering")
6
+ class PerturbedDatasetReclustering(ToleranceCalculator):
7
+ def __str__(self) -> str:
8
+ return f"PerturbedDatasetReclustering(perturbations_per_vector={self.perturbations_per_vector}, perturbation_scale={self.perturbation_scale}, dda={str(self.duplicate_detection_algorithm_object).split('(')[0]})"
9
+
10
+ def calculate_tolerance(self) -> float:
11
+ """Find the highest and lowest values of tolerance that yield the length of the original dataset from the perturbed dataset, then returns the average of those two values.
12
+
13
+ Returns:
14
+ float: The calculated tolerance value.
15
+ """
16
+ self._ensure_perturbed_dataset()
17
+
18
+ low_tolerance = self.binary_search_tolerance(
19
+ target_unique_vectors=len(self.duplicate_detection_algorithm_object.dataset_array),
20
+ find_largest_tolerance_for_target=False,
21
+ )
22
+ high_tolerance = self.binary_search_tolerance(
23
+ target_unique_vectors=len(self.duplicate_detection_algorithm_object.dataset_array),
24
+ find_largest_tolerance_for_target=True,
25
+ )
26
+ return (low_tolerance + high_tolerance) / 2
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: deduplicate_lib
3
+ Version: 0.0.1
4
+ Summary: A Python package for deduplicating data.
5
+ Author-email: Julian Holland <holland@fhi.mpg.de>
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: numpy
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest; extra == "dev"
12
+ Requires-Dist: pytest-mock; extra == "dev"
13
+ Requires-Dist: coverage; extra == "dev"
14
+ Requires-Dist: ruff; extra == "dev"
15
+ Dynamic: license-file
16
+
17
+ <div align="center">
18
+ <h1><code>deduplicate_lib</code></h1>
19
+ <p><i>deduplication algorithms in python</i></p>
20
+ </div>
21
+
22
+ ***
23
+ ## Key Features
24
+
25
+
26
+ - Easy to use deduplication algorithms for any vector array
27
+ - Suite of tolerance tuning algorithms to help you find the right tolerance value for your system
28
+ - Suite of benchmarking tools to ensure rigor, accuracy, and speed (not yet implemented)
29
+ - Factory Plugin architecture, for easy extensibility and modification
30
+
31
+ ***
32
+ ## Implemented Algorithms
33
+
34
+ - Distance Matrix (Simple, accurate, expensive): Computes the distance matrix for all vectors and determines duplicates by finding those that fall below a given distance
35
+ - Multi Hashing (Fast): Smears and rounds the vectors using a normal distribution and computes the hashes for each which are then used to determine duplicates by proportion of hash clashes.
36
+ <!-- - Locality Sensitive Hashing (Fast, Accurate) -->
37
+
38
+ ## Quick Start
39
+ install using pip
40
+ ```bash
41
+ pip install deduplicate_lib
42
+ ```
43
+
44
+ load your data into python
45
+
46
+ ```python
47
+ from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
48
+
49
+ # define your paramerters in the MultiHash object
50
+ dda=MultiHash(
51
+ tolerance=0.01,
52
+ dataset_array: your_data_array,
53
+ perturbations: int = 200,
54
+ )
55
+
56
+ print(dda.get_dataset_unique_structures())
57
+ ```
58
+
59
+ A more detailed example can be seen in the `examples` directory
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/deduplicate_lib/__init__.py
5
+ src/deduplicate_lib.egg-info/PKG-INFO
6
+ src/deduplicate_lib.egg-info/SOURCES.txt
7
+ src/deduplicate_lib.egg-info/dependency_links.txt
8
+ src/deduplicate_lib.egg-info/requires.txt
9
+ src/deduplicate_lib.egg-info/top_level.txt
10
+ src/deduplicate_lib/core/__init__.py
11
+ src/deduplicate_lib/core/duplicate_detection_algorithm.py
12
+ src/deduplicate_lib/core/plugin_registry.py
13
+ src/deduplicate_lib/core/tolerance_calculator.py
14
+ src/deduplicate_lib/plugins/__init__.py
15
+ src/deduplicate_lib/plugins/duplicate_detection_algorithms/__init__.py
16
+ src/deduplicate_lib/plugins/duplicate_detection_algorithms/distance_matrix.py
17
+ src/deduplicate_lib/plugins/duplicate_detection_algorithms/multi_hashing.py
18
+ src/deduplicate_lib/plugins/tolerance_calculators/__init__.py
19
+ src/deduplicate_lib/plugins/tolerance_calculators/natural_tolerance_plateau_probe.py
20
+ src/deduplicate_lib/plugins/tolerance_calculators/perturbed_dataset_reclustering.py
@@ -0,0 +1,7 @@
1
+ numpy
2
+
3
+ [dev]
4
+ pytest
5
+ pytest-mock
6
+ coverage
7
+ ruff
@@ -0,0 +1 @@
1
+ deduplicate_lib