deduplicate-lib 0.0.3__tar.gz → 0.0.5__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 (23) hide show
  1. {deduplicate_lib-0.0.3/src/deduplicate_lib.egg-info → deduplicate_lib-0.0.5}/PKG-INFO +7 -4
  2. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/README.md +7 -4
  3. deduplicate_lib-0.0.5/src/deduplicate_lib/__init__.py +1 -0
  4. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/core/duplicate_detection_algorithm.py +96 -12
  5. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/core/tolerance_calculator.py +41 -34
  6. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/distance_matrix.py +13 -19
  7. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/multi_hashing.py +64 -36
  8. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/plugins/tolerance_calculators/natural_tolerance_plateau_probe.py +14 -12
  9. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/plugins/tolerance_calculators/perturbed_dataset_reclustering.py +17 -14
  10. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5/src/deduplicate_lib.egg-info}/PKG-INFO +7 -4
  11. deduplicate_lib-0.0.3/src/deduplicate_lib/__init__.py +0 -1
  12. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/LICENSE +0 -0
  13. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/pyproject.toml +0 -0
  14. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/setup.cfg +0 -0
  15. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/core/__init__.py +0 -0
  16. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/core/plugin_registry.py +0 -0
  17. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/plugins/__init__.py +0 -0
  18. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/__init__.py +0 -0
  19. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib/plugins/tolerance_calculators/__init__.py +0 -0
  20. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib.egg-info/SOURCES.txt +0 -0
  21. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib.egg-info/dependency_links.txt +0 -0
  22. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib.egg-info/requires.txt +0 -0
  23. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.5}/src/deduplicate_lib.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deduplicate_lib
3
- Version: 0.0.3
3
+ Version: 0.0.5
4
4
  Summary: A Python package for deduplicating data.
5
5
  Author-email: Julian Holland <holland@fhi.mpg.de>
6
6
  Requires-Python: >=3.8
@@ -63,7 +63,7 @@ load your data into python
63
63
  from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
64
64
 
65
65
  # define your paramerters in the MultiHash object
66
- dda=MultiHash(dataset_array=your_data_array)
66
+ dda=MultiHash(dataset_array=your_data_numpy_array)
67
67
 
68
68
  # return a list of all unique values
69
69
  print(dda.deduplicate())
@@ -125,7 +125,7 @@ If you use deduplicate_lib in your research, please cite:
125
125
  author={Julian Holland},
126
126
  year={2026},
127
127
  url={https://github.com/julianholland/deduplicate},
128
- version={0.0.2dev}
128
+ version={0.0.5}
129
129
  }
130
130
  ```
131
131
 
@@ -137,6 +137,8 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
137
137
 
138
138
  - The Fritz Haber Institute
139
139
  - Juan Manuel Lombardi <3
140
+ - Maximillion Ach
141
+ - Chiara Panosetti
140
142
 
141
143
 
142
144
  ## Project Links
@@ -146,9 +148,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
146
148
  ## Project To-Do
147
149
 
148
150
  - [x] Add example.ipynb
149
- - [ ] Create general Pre-allocation protocal
151
+ - [x] Create general Pre-allocation protocal
150
152
  - [ ] Add benchmarks for time and robustness
151
153
  - [ ] Add Locality-Sensitive Hashing as an option
152
154
  - [x] Speedup slow tasks with Numba
153
155
  - [ ] Set up Read the Docs
154
156
  - [x] Create general deduplicate function
157
+ - [x] Speed up NTPP
@@ -40,7 +40,7 @@ load your data into python
40
40
  from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
41
41
 
42
42
  # define your paramerters in the MultiHash object
43
- dda=MultiHash(dataset_array=your_data_array)
43
+ dda=MultiHash(dataset_array=your_data_numpy_array)
44
44
 
45
45
  # return a list of all unique values
46
46
  print(dda.deduplicate())
@@ -102,7 +102,7 @@ If you use deduplicate_lib in your research, please cite:
102
102
  author={Julian Holland},
103
103
  year={2026},
104
104
  url={https://github.com/julianholland/deduplicate},
105
- version={0.0.2dev}
105
+ version={0.0.5}
106
106
  }
107
107
  ```
108
108
 
@@ -114,6 +114,8 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
114
114
 
115
115
  - The Fritz Haber Institute
116
116
  - Juan Manuel Lombardi <3
117
+ - Maximillion Ach
118
+ - Chiara Panosetti
117
119
 
118
120
 
119
121
  ## Project Links
@@ -123,9 +125,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
123
125
  ## Project To-Do
124
126
 
125
127
  - [x] Add example.ipynb
126
- - [ ] Create general Pre-allocation protocal
128
+ - [x] Create general Pre-allocation protocal
127
129
  - [ ] Add benchmarks for time and robustness
128
130
  - [ ] Add Locality-Sensitive Hashing as an option
129
131
  - [x] Speedup slow tasks with Numba
130
132
  - [ ] Set up Read the Docs
131
- - [x] Create general deduplicate function
133
+ - [x] Create general deduplicate function
134
+ - [x] Speed up NTPP
@@ -0,0 +1 @@
1
+ __version__ = "0.0.5"
@@ -71,15 +71,33 @@ class DuplicateDetectionAlgorithm(ABC):
71
71
  distance_matrix: np.ndarray = np.array([]),
72
72
  distance_metric: str = "euclidean",
73
73
  unique_vector_indices: np.ndarray = np.array([]),
74
+ max_vector_array_size: int = 10000,
74
75
  ) -> None:
75
76
  self.tolerance = tolerance
76
77
  self.input_vector = input_vector
77
- self.dataset_array = dataset_array
78
+ self._dataset_array = np.array([]) # will be initialized properly in preinitialize_dataset_array
79
+
78
80
  self.distance_matrix = distance_matrix
79
81
  self.distance_metric = distance_metric
80
82
  self.unique_vector_indices = unique_vector_indices
83
+ self.max_vector_array_size = max_vector_array_size
81
84
 
82
- # In DuplicateDetectionAlgorithm
85
+ self.set_dataset_array(dataset_array) if dataset_array.size > 0 else None
86
+
87
+ @property
88
+ def dataset_array(self) -> np.ndarray:
89
+ view = self._dataset_array.view()
90
+ view.flags.writeable = False
91
+ return view
92
+
93
+ @dataset_array.setter
94
+ def dataset_array(self, _value: np.ndarray) -> None:
95
+ raise AttributeError(
96
+ "Cannot assign to 'dataset_array' directly; use set_dataset_array(...)."
97
+ )
98
+
99
+ def _set_dataset_array_internal(self, arr:np.ndarray) -> None:
100
+ self._dataset_array = arr
83
101
 
84
102
  @property
85
103
  def distance_metric(self):
@@ -98,10 +116,16 @@ class DuplicateDetectionAlgorithm(ABC):
98
116
  def calculate_distance(self, vector1: np.ndarray, vector2: np.ndarray) -> float:
99
117
  return self.distance_function(vector1, vector2)
100
118
 
101
- def compute_distance_matrix(self, vector_array: np.ndarray) -> None:
119
+ def compute_distance_matrix(self, vector_array: np.ndarray | None = None) -> None:
102
120
  """Compute the distance matrix for the dataset from scratch."""
103
- self.distance_matrix = fast_compute_distance_matrix(
104
- vector_array, self.distance_function
121
+ if self.distance_matrix.size == 0:
122
+ self.initialize_distance_matrix()
123
+
124
+ if vector_array is None:
125
+ vector_array = self._dataset_array
126
+
127
+ self.distance_matrix[: self.vector_count, : self.vector_count] = fast_compute_distance_matrix(
128
+ vector_array[: self.vector_count], self.distance_function
105
129
  )
106
130
 
107
131
  def get_new_distance_matrix_column(self, vector_array: np.ndarray) -> np.ndarray:
@@ -111,17 +135,15 @@ class DuplicateDetectionAlgorithm(ABC):
111
135
  np.ndarray: A 1D array containing the distances from the input vector to each vector in the dataset.
112
136
  """
113
137
  return fast_get_new_distance_matrix_column(
114
- self.input_vector, vector_array, self.distance_function
138
+ self.input_vector, vector_array[: self.vector_count], self.distance_function
115
139
  )
116
140
 
117
141
  def add_new_vector_to_distance_matrix(self, vector_array: np.ndarray) -> None:
118
142
  """Add a new input vector to the distance matrix."""
119
143
  new_distances = self.get_new_distance_matrix_column(vector_array)
120
- self.distance_matrix = np.hstack(
121
- (self.distance_matrix, new_distances[:, np.newaxis])
122
- )
123
- new_row = np.append(new_distances, 0) # Distance to itself is 0
124
- self.distance_matrix = np.vstack((self.distance_matrix, new_row))
144
+ self.distance_matrix[self.vector_count] = np.pad(new_distances, (0, self.max_vector_array_size - len(new_distances)), constant_values=0)
145
+ self.distance_matrix[:, self.vector_count] = np.pad(new_distances, (0, self.max_vector_array_size - len(new_distances)), constant_values=0)
146
+
125
147
 
126
148
  def pre_dda_processing(
127
149
  self, input_dataset_array: np.ndarray | None = None, *args, **kwargs
@@ -135,7 +157,7 @@ class DuplicateDetectionAlgorithm(ABC):
135
157
 
136
158
  def get_unique_vector_indices(self) -> np.ndarray:
137
159
  """Returns the indices of the unique vectors in the dataset."""
138
- if self.unique_vector_indices.shape[0] != self.dataset_array.shape[0]:
160
+ if self.unique_vector_indices.shape[0] != self.vector_count:
139
161
  raise ValueError(
140
162
  "Unique vector indices array shape does not match dataset; please run get_dataset_unique_structures() to update the unique vector indices before calling this method."
141
163
  )
@@ -144,6 +166,68 @@ class DuplicateDetectionAlgorithm(ABC):
144
166
  def deduplicate(self):
145
167
  """Finds all unique vectors in the dataset and returns them as a new array."""
146
168
  return self.dataset_array[self.get_unique_vector_indices()]
169
+
170
+ def initialize_dataset_array(self, vector_length: int) -> None:
171
+ self._set_dataset_array_internal(np.zeros((self.max_vector_array_size, vector_length)))
172
+
173
+ def initialize_distance_matrix(self) -> None:
174
+ self.distance_matrix = np.zeros((self.max_vector_array_size, self.max_vector_array_size))
175
+
176
+ def get_filled_dataset_array(self) -> np.ndarray:
177
+ return self._dataset_array[: self.vector_count]
178
+
179
+ def get_filled_distance_matrix(self) -> np.ndarray:
180
+ return self.distance_matrix[: self.vector_count, : self.vector_count]
181
+
182
+ def set_dataset_array(self, new_dataset_array: np.ndarray) -> None:
183
+ """Create new dataset array with correct shape and vector count
184
+ if the input vector and dataset are both empty then the vector length cannot be determined, so we initialize an empty dataset array"""
185
+ if new_dataset_array.shape[0] > self.max_vector_array_size:
186
+ raise ValueError("New dataset array size exceeds maximum allowed size.")
187
+
188
+ self.vector_count = new_dataset_array.shape[0]
189
+ if new_dataset_array.size == 0 and self.input_vector.size > 0:
190
+ self.initialize_dataset_array(len(self.input_vector))
191
+ elif new_dataset_array.size > 0:
192
+ self.initialize_dataset_array(new_dataset_array.shape[1])
193
+ self._dataset_array[: self.vector_count] = new_dataset_array
194
+ else:
195
+ self._dataset_array = new_dataset_array
196
+
197
+ def get_vector_length(self) -> int:
198
+ has_input = self.input_vector.size > 0
199
+ has_dataset = self._dataset_array.size > 0
200
+ print(f"has_input: {has_input}, has_dataset: {has_dataset}")
201
+ print(f"input_vector: {self.input_vector}, dataset_array: {self._dataset_array}")
202
+
203
+ if has_input and has_dataset:
204
+ print(self.input_vector.shape, self._dataset_array.shape)
205
+ if self.input_vector.shape[0] != self._dataset_array.shape[1]:
206
+ raise ValueError(
207
+ "Input vector length does not match dataset vector length."
208
+ )
209
+ vector_length = self.input_vector.shape[0]
210
+ elif has_dataset:
211
+ vector_length = self._dataset_array.shape[1]
212
+ else:
213
+ raise ValueError(
214
+ "Cannot determine vector length from input vector or dataset array. "
215
+ "Assign one of them before preinitialization."
216
+ )
217
+
218
+ return vector_length
219
+
220
+ def preinitialize_dataset_array(self) -> None:
221
+ vector_length=self.get_vector_length()
222
+
223
+ if self._dataset_array.shape[0] > self.max_vector_array_size:
224
+ raise ValueError("Dataset array size exceeds maximum allowed size.")
225
+
226
+ if self._dataset_array.shape[0] != self.max_vector_array_size:
227
+ existing_data = self._dataset_array.copy()
228
+ self.vector_count = existing_data.shape[0]
229
+ self.initialize_dataset_array(vector_length)
230
+ self._dataset_array[: self.vector_count] = existing_data
147
231
 
148
232
  @abstractmethod
149
233
  def duplicate_check(self) -> bool:
@@ -20,6 +20,7 @@ class ToleranceCalculator(ABC):
20
20
  self.perturbation_scale = perturbation_scale
21
21
  self.binary_search_steps = binary_search_steps
22
22
 
23
+
23
24
  @contextmanager
24
25
  def temp_attr(self, obj, attr, value):
25
26
  original = getattr(obj, attr)
@@ -51,38 +52,44 @@ class ToleranceCalculator(ABC):
51
52
  return tolerance
52
53
 
53
54
  # temporarily set the dataset_array to the tolerance_dataset_array for the duration of the search
54
- with self.temp_attr(
55
- self.duplicate_detection_algorithm_object,
56
- "dataset_array",
57
- self.tolerance_dataset_array,
58
- ):
59
- for _ in range(self.binary_search_steps):
60
- # temporarily set the tolerance for the duration of this iteration of the search
61
- with self.temp_attr(
62
- self.duplicate_detection_algorithm_object, "tolerance", tolerance
63
- ):
55
+ old_array=self.duplicate_detection_algorithm_object.get_filled_dataset_array()
56
+ old_vector_count=self.duplicate_detection_algorithm_object.vector_count
57
+ self.duplicate_detection_algorithm_object.set_dataset_array(self.tolerance_dataset_array)
58
+
59
+ self.duplicate_detection_algorithm_object.pre_dda_processing()
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
+
69
+
70
+ results_dict[tolerance] = unique_vectors
71
+ if unique_vectors < target_unique_vectors: # loosen tolerance
72
+ best_max = tolerance
73
+ elif unique_vectors > target_unique_vectors: # tighten tolerance
74
+ best_min = tolerance
75
+
76
+ else:
77
+ exact_list.append(tolerance)
78
+ if (
79
+ target_unique_vectors
80
+ == self.duplicate_detection_algorithm_object.vector_count
64
81
 
65
- unique_vectors = self.duplicate_detection_algorithm_object.get_dataset_unique_structures()
66
- results_dict[tolerance] = unique_vectors
67
- if unique_vectors < target_unique_vectors: # loosen tolerance
68
- best_max = tolerance
69
- elif unique_vectors > target_unique_vectors: # tighten tolerance
82
+ or find_largest_tolerance_for_target
83
+ ):
70
84
  best_min = tolerance
71
-
72
85
  else:
73
- exact_list.append(tolerance)
74
- if (
75
- target_unique_vectors
76
- == len(
77
- self.duplicate_detection_algorithm_object.dataset_array
78
- )
79
- or find_largest_tolerance_for_target
80
- ):
81
- best_min = tolerance
82
- else:
83
- best_max = tolerance
84
-
85
- tolerance = (best_min + best_max) / 2
86
+ best_max = tolerance
87
+
88
+ tolerance = (best_min + best_max) / 2
89
+
90
+ # reset the dataset_array to the original dataset array after the search is complete
91
+ self.duplicate_detection_algorithm_object.set_dataset_array(old_array)
92
+ self.duplicate_detection_algorithm_object.vector_count = old_vector_count
86
93
  # Find the best exact value if it exists, otherwise find the closest value
87
94
  if len(exact_list) > 0:
88
95
  if find_largest_tolerance_for_target:
@@ -107,21 +114,21 @@ class ToleranceCalculator(ABC):
107
114
  rng=np.random.default_rng(seed)
108
115
  self.tolerance_dataset_array = np.zeros(
109
116
  (
110
- len(self.duplicate_detection_algorithm_object.dataset_array)
117
+ self.duplicate_detection_algorithm_object.vector_count
111
118
  * self.perturbations_per_vector,
112
119
  self.duplicate_detection_algorithm_object.dataset_array.shape[1],
113
120
  )
114
121
  )
115
122
 
116
- for i, vector in enumerate(self.duplicate_detection_algorithm_object.dataset_array):
123
+ for i in range(self.duplicate_detection_algorithm_object.vector_count):
117
124
  self.tolerance_dataset_array[i * self.perturbations_per_vector] = (
118
125
  self.duplicate_detection_algorithm_object.dataset_array[i]
119
126
  )
120
127
  for j in range(1, self.perturbations_per_vector):
121
128
  perturbation = rng.normal(
122
- loc=0.0, scale=self.perturbation_scale, size=vector.shape
129
+ loc=0.0, scale=self.perturbation_scale, size=self.duplicate_detection_algorithm_object.dataset_array.shape[1]
123
130
  )
124
- perturbed_vector = vector + perturbation
131
+ perturbed_vector = self.duplicate_detection_algorithm_object.dataset_array[i] + perturbation
125
132
  self.tolerance_dataset_array[i * self.perturbations_per_vector + j] = (
126
133
  perturbed_vector
127
134
  )
@@ -129,7 +136,7 @@ class ToleranceCalculator(ABC):
129
136
  def _ensure_perturbed_dataset(self):
130
137
  if (
131
138
  self.tolerance_dataset_array.shape[0]
132
- != len(self.duplicate_detection_algorithm_object.dataset_array)
139
+ != self.duplicate_detection_algorithm_object.vector_count
133
140
  * self.perturbations_per_vector and self.perturbations_per_vector > 1
134
141
  ):
135
142
  warnings.warn(
@@ -1,7 +1,6 @@
1
1
  from deduplicate_lib.core.duplicate_detection_algorithm import DuplicateDetectionAlgorithm
2
2
  from deduplicate_lib.core.plugin_registry import register_plugin
3
3
  import numpy as np
4
- import warnings
5
4
 
6
5
  @register_plugin(kind="duplicate_detection_algorithm", name="distance_matrix")
7
6
  class DistanceMatrix(DuplicateDetectionAlgorithm):
@@ -13,20 +12,15 @@ class DistanceMatrix(DuplicateDetectionAlgorithm):
13
12
  distance_matrix: np.ndarray = np.array([]),
14
13
  distance_metric: str = "euclidean",
15
14
  unique_vector_indices: np.ndarray = np.array([]),
15
+ max_vector_array_size: int = 10000,
16
16
  ) -> None:
17
17
  super().__init__(
18
- tolerance, input_vector, dataset_array, distance_matrix, distance_metric, unique_vector_indices
18
+ tolerance, input_vector, dataset_array, distance_matrix, distance_metric, unique_vector_indices, max_vector_array_size
19
19
  )
20
20
 
21
21
  def __str__(self) -> str:
22
22
  return f"DistanceMatrix(tolerance={self.tolerance}, distance_metric={self.distance_metric})"
23
23
 
24
- def _ensure_distance_matrix(self):
25
- if self.distance_matrix.shape[0] != self.dataset_array.shape[0]:
26
- warnings.warn("Distance matrix shape does not match dataset; recomputing.")
27
- self.compute_distance_matrix(self.dataset_array)
28
-
29
-
30
24
  def duplicate_check(self) -> bool:
31
25
  return bool(
32
26
  np.any(
@@ -35,22 +29,22 @@ class DistanceMatrix(DuplicateDetectionAlgorithm):
35
29
  )
36
30
 
37
31
  def get_dataset_unique_structures(self) -> int:
38
- self._ensure_distance_matrix()
39
- self.unique_vector_indices = np.zeros(self.dataset_array.shape[0], dtype=bool)
32
+ self.unique_vector_indices = np.zeros(self.vector_count, dtype=bool)
40
33
  self.unique_vector_indices[0] = True # the first vector is always unique
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):
34
+ for i in range(1, self.vector_count):
35
+ imask = np.arange(self.vector_count) != i
36
+ if np.all(self.distance_matrix[i, : self.vector_count][imask] >= self.tolerance):
44
37
  self.unique_vector_indices[i] = True
45
38
  return np.sum(self.unique_vector_indices)
46
39
 
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)
40
+ def pre_dda_processing(self, *args, **kwargs) -> None:
41
+ self.preinitialize_dataset_array()
42
+ self.initialize_distance_matrix()
43
+ self.compute_distance_matrix(self.dataset_array)
51
44
 
52
45
  def add_input_vector_to_dda(self) -> None:
53
46
  """Add the input vector to the dataset array and update the distance matrix accordingly."""
54
47
  self.add_new_vector_to_distance_matrix(self.dataset_array)
55
- self.dataset_array = np.vstack((self.dataset_array, self.input_vector))
56
-
48
+ self._dataset_array[self.vector_count] = self.input_vector
49
+ self.vector_count += 1
50
+
@@ -37,8 +37,8 @@ class MultiHashing(DuplicateDetectionAlgorithm):
37
37
  distance_metric: str = "hamming",
38
38
  sigma_accepatnce_threshold: int = 1,
39
39
  distance_matrix: np.ndarray = np.array([]),
40
- hash_vector_array: np.ndarray = np.array([]),
41
40
  unique_vector_indices: np.ndarray = np.array([]),
41
+ max_vector_array_size: int = 10000,
42
42
  ) -> None:
43
43
  super().__init__(
44
44
  tolerance=tolerance,
@@ -47,13 +47,14 @@ class MultiHashing(DuplicateDetectionAlgorithm):
47
47
  distance_metric=distance_metric,
48
48
  distance_matrix=distance_matrix,
49
49
  unique_vector_indices=unique_vector_indices,
50
+ max_vector_array_size=max_vector_array_size
50
51
  )
51
52
  self.seed = seed
52
53
  self.sigma_accepatnce_threshold = sigma_accepatnce_threshold
53
54
  self.perturbations = perturbations
54
- self.hash_vector_array = hash_vector_array
55
55
  self.perturbation_array = pertrubation_array
56
-
56
+
57
+ self.initialize_hash_vector_dictionary()
57
58
  self.set_acceptance_threshold()
58
59
 
59
60
  def __str__(self) -> str:
@@ -101,29 +102,35 @@ class MultiHashing(DuplicateDetectionAlgorithm):
101
102
  hash_vector[i] = hash(rounded_and_perturbed[i].tobytes())
102
103
  return hash_vector
103
104
 
104
- def create_hash_vector_array(self) -> np.ndarray:
105
- """Creates the hash vector array for the dataset. Only unique hash values are stored for each perturbation.
105
+ def initialize_hash_vector_dictionary(self) -> None:
106
+ self.hash_dict = {i: {} for i in range(self.perturbations)}
106
107
 
107
- Returns:
108
- np.ndarray: A 2D array containing the hash values for each vector in the dataset for each perturbation.
109
- """
110
- self.hash_vector_array = np.zeros(
111
- (self.dataset_array.shape[0], self.perturbations), dtype=int
112
- )
113
- self._ensure_perturbation_array()
114
- for i in range(self.dataset_array.shape[0]):
115
- hash_vector = self.create_hash_vector(self.dataset_array[i])
116
- for j in range(self.perturbations):
117
- if hash_vector[j] not in self.hash_vector_array[:, j]:
118
- self.hash_vector_array[i, j] = hash_vector[j]
119
- return self.hash_vector_array
120
-
121
- def _ensure_hash_vector_array(self):
122
- if self.hash_vector_array.shape[0] != self.dataset_array.shape[0]:
123
- warnings.warn(
124
- "Hash vector array shape does not match dataset; recomputing."
125
- )
126
- self.create_hash_vector_array()
108
+ def compute_hash_vector_dictionary(self) -> dict:
109
+ self.initialize_hash_vector_dictionary()
110
+ for i in range(self.vector_count):
111
+ self.add_input_vector_hashes_to_dictionary(input_vector=self._dataset_array[i], input_index=i)
112
+
113
+ return self.hash_dict
114
+
115
+ def add_input_vector_hashes_to_dictionary(self, input_vector: np.ndarray | None = None, input_index: int = None) -> None:
116
+ if input_vector is None:
117
+ input_vector = self.input_vector
118
+ if input_index is None:
119
+ input_index = self.vector_count
120
+
121
+ hash_vector = self.create_hash_vector(input_vector)
122
+ self.warn_if_vector_dict_mismatch(hash_vector)
123
+
124
+ for hash_index, hash_value in enumerate(hash_vector):
125
+ if hash_value not in self.hash_dict[hash_index]:
126
+ self.hash_dict[hash_index][hash_value] = [input_index]
127
+ else:
128
+ self.hash_dict[hash_index][hash_value].append(input_index) # maybe replace with pre init boolean np array
129
+
130
+ def warn_if_vector_dict_mismatch(self, hash_vector: np.ndarray):
131
+ if len(self.hash_dict) != len(hash_vector):
132
+ warnings.warn("Hash vector dictionary length does not match number of perturbations; recomputing. \nAssign the perturbation array and compute the hash vector dictionary prior to duplication checks to avoid this warning.")
133
+ self.compute_hash_vector_dictionary()
127
134
 
128
135
  def duplicate_check(self) -> bool:
129
136
  """duplicate check against dataset using multi-hashing approach.
@@ -131,12 +138,12 @@ class MultiHashing(DuplicateDetectionAlgorithm):
131
138
  Returns:
132
139
  bool: True if a duplicate is detected, False otherwise.
133
140
  """
134
- self._ensure_hash_vector_array()
135
141
  hash_vector = self.create_hash_vector()
142
+ self.warn_if_vector_dict_mismatch(hash_vector)
136
143
 
137
144
  clash_vector = np.zeros(self.perturbations, dtype=bool)
138
145
  for hash_index, hash_value in enumerate(hash_vector):
139
- if hash_value in self.hash_vector_array[:, hash_index]:
146
+ if hash_value in self.hash_dict[hash_index]:
140
147
  clash_vector[hash_index] = True
141
148
  duplicate_vote_array = np.sum(clash_vector) / self.perturbations
142
149
 
@@ -145,34 +152,55 @@ class MultiHashing(DuplicateDetectionAlgorithm):
145
152
  return bool(duplicate_structure)
146
153
 
147
154
  def get_uniqueness_score(self) -> float:
148
- self._ensure_hash_vector_array()
149
155
  hash_vector = self.create_hash_vector()
156
+ self.warn_if_vector_dict_mismatch(hash_vector)
150
157
  clash_vector = np.zeros(self.perturbations, dtype=bool)
151
158
  for hash_index, hash_value in enumerate(hash_vector):
152
- if hash_value in self.hash_vector_array[:, hash_index]:
159
+ if hash_value in self.hash_dict[hash_index]:
153
160
  clash_vector[hash_index] = True
154
161
  uniqueness_score = 1 - np.sum(clash_vector) / self.perturbations
155
162
 
156
163
  return uniqueness_score
157
164
 
165
+
158
166
  def get_dataset_unique_structures(self) -> int:
159
167
  """Counts the number of unique structures in the dataset by checking for hash value clashes across the dataset for each perturbation.
160
168
 
161
169
  Returns:
162
170
  int: The number of unique structures in the dataset.
163
171
  """
164
- self.create_hash_vector_array()
165
- clash_array = np.zeros((self.hash_vector_array.shape), dtype=bool)
166
- clash_array[np.nonzero(self.hash_vector_array)] = True
167
- self.unique_vector_indices = np.sum(clash_array, axis=1) / self.perturbations >= self.acceptance_threshold
172
+ self.compute_hash_vector_dictionary()
173
+ u_list_of_lists = []
174
+ for i in range(self.perturbations):
175
+ u_list = [self.hash_dict[i][hash_value][0] for hash_value in self.hash_dict[i]]
176
+ u_list_of_lists.append(u_list)
177
+
178
+ # count the number of times each index appears across all perturbations
179
+ index_counts = {}
180
+ for i in range(self.vector_count):
181
+ for u_list in u_list_of_lists:
182
+ if i in u_list:
183
+ if i not in index_counts:
184
+ index_counts[i] = 1
185
+ else:
186
+ index_counts[i] += 1
168
187
 
188
+ # get indexes that appear in at least acceptance_threshold * perturbations perturbations
189
+ index_filter = [index for index, count in index_counts.items() if count / self.perturbations >= self.acceptance_threshold]
190
+
191
+ # convert to boolean array for indexing
192
+ self.unique_vector_indices = np.zeros(self.vector_count, dtype=bool)
193
+ self.unique_vector_indices[index_filter] = True
194
+
169
195
  return np.sum(self.unique_vector_indices)
170
196
 
171
197
  def pre_dda_processing(self, *args, **kwargs) -> None:
172
198
  self.set_perturbation_array()
199
+ self.compute_hash_vector_dictionary()
200
+
173
201
 
174
202
  def add_input_vector_to_dda(self) -> None:
175
203
  """Add the input vector to the dataset array and update the hash vector array accordingly."""
176
- self.dataset_array = np.vstack((self.dataset_array, self.input_vector))
177
- new_hash_vector = self.create_hash_vector()
178
- self.hash_vector_array = np.vstack((self.hash_vector_array, new_hash_vector))
204
+ self._dataset_array[self.vector_count] = self.input_vector
205
+ self.add_input_vector_hashes_to_dictionary(self.input_vector)
206
+ self.vector_count += 1
@@ -38,18 +38,20 @@ class NaturalTolerancePlateauProbe(ToleranceCalculator):
38
38
  self, lower_tolerance: float, upper_tolerance: float, tolerance_steps: int
39
39
  ) -> dict:
40
40
  tolerance_results = {}
41
- with self.temp_attr(
42
- self.duplicate_detection_algorithm_object,
43
- "dataset_array",
44
- self.tolerance_dataset_array,
45
- ):
46
- for tol in np.linspace(lower_tolerance, upper_tolerance, tolerance_steps):
47
- with self.temp_attr(
48
- self.duplicate_detection_algorithm_object, "tolerance", tol
49
- ):
50
- self.duplicate_detection_algorithm_object.tolerance = tol
51
- unique_structures = self.duplicate_detection_algorithm_object.get_dataset_unique_structures()
52
- tolerance_results[tol] = unique_structures
41
+ old_array=self.duplicate_detection_algorithm_object.get_filled_dataset_array()
42
+ old_vector_count=self.duplicate_detection_algorithm_object.vector_count
43
+
44
+ self.duplicate_detection_algorithm_object.set_dataset_array(self.tolerance_dataset_array)
45
+
46
+ for tol in np.linspace(lower_tolerance, upper_tolerance, tolerance_steps):
47
+ with self.temp_attr(
48
+ self.duplicate_detection_algorithm_object, "tolerance", tol
49
+ ):
50
+ unique_structures = self.duplicate_detection_algorithm_object.get_dataset_unique_structures()
51
+ tolerance_results[tol] = unique_structures
52
+
53
+ self.duplicate_detection_algorithm_object.set_dataset_array(old_array)
54
+ self.duplicate_detection_algorithm_object.vector_count = old_vector_count
53
55
  return tolerance_results
54
56
 
55
57
  def get_plateau_log(
@@ -29,8 +29,8 @@ class PerturbedDatasetReclustering(ToleranceCalculator):
29
29
  perturbations_per_vector: int = 1,
30
30
  perturbation_scale: float = 0.1,
31
31
  binary_search_steps: int = 20,
32
- target_structures: int | None = None,
33
- target_structures_threshold: str = "average"
32
+ target_unique_vectors: int | None = None,
33
+ target_unique_vectors_threshold: str = "average"
34
34
  ):
35
35
 
36
36
  super().__init__(
@@ -40,10 +40,13 @@ class PerturbedDatasetReclustering(ToleranceCalculator):
40
40
  perturbation_scale=perturbation_scale,
41
41
  binary_search_steps=binary_search_steps,
42
42
  )
43
- if target_structures is None:
44
- target_structures = len(duplicate_detection_algorithm_object.dataset_array)
45
- self.target_structures = target_structures
46
- self.target_structures_threshold = target_structures_threshold
43
+
44
+ if target_unique_vectors is None:
45
+ self.target_unique_vectors = duplicate_detection_algorithm_object.vector_count
46
+ else:
47
+ self.target_unique_vectors = target_unique_vectors
48
+
49
+ self.target_unique_vectors_threshold = target_unique_vectors_threshold
47
50
  def __str__(self) -> str:
48
51
  return f"PerturbedDatasetReclustering(perturbations_per_vector={self.perturbations_per_vector}, perturbation_scale={self.perturbation_scale}, dda={str(self.duplicate_detection_algorithm_object).split('(')[0]})"
49
52
 
@@ -54,26 +57,26 @@ class PerturbedDatasetReclustering(ToleranceCalculator):
54
57
  float: The calculated tolerance value.
55
58
  """
56
59
  self._ensure_perturbed_dataset()
57
- if self.target_structures_threshold == "average":
60
+ if self.target_unique_vectors_threshold == "average":
58
61
  low_tolerance = self.binary_search_tolerance(
59
- target_unique_vectors=self.target_structures,
62
+ target_unique_vectors=self.target_unique_vectors,
60
63
  find_largest_tolerance_for_target=False,
61
64
  )
62
65
  high_tolerance = self.binary_search_tolerance(
63
- target_unique_vectors=self.target_structures,
66
+ target_unique_vectors=self.target_unique_vectors,
64
67
  find_largest_tolerance_for_target=True,
65
68
  )
66
69
  return (low_tolerance + high_tolerance) / 2
67
70
 
68
- elif self.target_structures_threshold == "loose":
71
+ elif self.target_unique_vectors_threshold == "loose":
69
72
  return self.binary_search_tolerance(
70
- target_unique_vectors=self.target_structures,
73
+ target_unique_vectors=self.target_unique_vectors,
71
74
  find_largest_tolerance_for_target=True,
72
75
  )
73
- elif self.target_structures_threshold == "tight":
76
+ elif self.target_unique_vectors_threshold == "tight":
74
77
  return self.binary_search_tolerance(
75
- target_unique_vectors=self.target_structures,
78
+ target_unique_vectors=self.target_unique_vectors,
76
79
  find_largest_tolerance_for_target=False,
77
80
  )
78
81
  else:
79
- raise ValueError(f"Invalid target_structures_threshold: {self.target_structures_threshold}. Must be 'average', 'loose', or 'tight'.")
82
+ raise ValueError(f"Invalid target_unique_vectors_threshold: {self.target_unique_vectors_threshold}. Must be 'average', 'loose', or 'tight'.")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deduplicate_lib
3
- Version: 0.0.3
3
+ Version: 0.0.5
4
4
  Summary: A Python package for deduplicating data.
5
5
  Author-email: Julian Holland <holland@fhi.mpg.de>
6
6
  Requires-Python: >=3.8
@@ -63,7 +63,7 @@ load your data into python
63
63
  from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
64
64
 
65
65
  # define your paramerters in the MultiHash object
66
- dda=MultiHash(dataset_array=your_data_array)
66
+ dda=MultiHash(dataset_array=your_data_numpy_array)
67
67
 
68
68
  # return a list of all unique values
69
69
  print(dda.deduplicate())
@@ -125,7 +125,7 @@ If you use deduplicate_lib in your research, please cite:
125
125
  author={Julian Holland},
126
126
  year={2026},
127
127
  url={https://github.com/julianholland/deduplicate},
128
- version={0.0.2dev}
128
+ version={0.0.5}
129
129
  }
130
130
  ```
131
131
 
@@ -137,6 +137,8 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
137
137
 
138
138
  - The Fritz Haber Institute
139
139
  - Juan Manuel Lombardi <3
140
+ - Maximillion Ach
141
+ - Chiara Panosetti
140
142
 
141
143
 
142
144
  ## Project Links
@@ -146,9 +148,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
146
148
  ## Project To-Do
147
149
 
148
150
  - [x] Add example.ipynb
149
- - [ ] Create general Pre-allocation protocal
151
+ - [x] Create general Pre-allocation protocal
150
152
  - [ ] Add benchmarks for time and robustness
151
153
  - [ ] Add Locality-Sensitive Hashing as an option
152
154
  - [x] Speedup slow tasks with Numba
153
155
  - [ ] Set up Read the Docs
154
156
  - [x] Create general deduplicate function
157
+ - [x] Speed up NTPP
@@ -1 +0,0 @@
1
- __version__ = "0.0.3"
File without changes