deduplicate-lib 0.0.3__tar.gz → 0.0.4__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.4}/PKG-INFO +6 -3
  2. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/README.md +6 -3
  3. deduplicate_lib-0.0.4/src/deduplicate_lib/__init__.py +1 -0
  4. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/core/duplicate_detection_algorithm.py +96 -12
  5. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/core/tolerance_calculator.py +38 -34
  6. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/distance_matrix.py +13 -19
  7. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/multi_hashing.py +23 -13
  8. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/tolerance_calculators/natural_tolerance_plateau_probe.py +14 -12
  9. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/tolerance_calculators/perturbed_dataset_reclustering.py +17 -14
  10. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4/src/deduplicate_lib.egg-info}/PKG-INFO +6 -3
  11. deduplicate_lib-0.0.3/src/deduplicate_lib/__init__.py +0 -1
  12. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/LICENSE +0 -0
  13. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/pyproject.toml +0 -0
  14. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/setup.cfg +0 -0
  15. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/core/__init__.py +0 -0
  16. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/core/plugin_registry.py +0 -0
  17. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/__init__.py +0 -0
  18. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/__init__.py +0 -0
  19. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/tolerance_calculators/__init__.py +0 -0
  20. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib.egg-info/SOURCES.txt +0 -0
  21. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib.egg-info/dependency_links.txt +0 -0
  22. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/src/deduplicate_lib.egg-info/requires.txt +0 -0
  23. {deduplicate_lib-0.0.3 → deduplicate_lib-0.0.4}/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.4
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())
@@ -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
+ - [ ] 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())
@@ -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
+ - [ ] Speed up NTPP
@@ -0,0 +1 @@
1
+ __version__ = "0.0.4"
@@ -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,41 @@ 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
+ self.duplicate_detection_algorithm_object.pre_dda_processing()
59
+
60
+ for _ in range(self.binary_search_steps):
61
+ # temporarily set the tolerance for the duration of this iteration of the search
62
+ with self.temp_attr(
63
+ self.duplicate_detection_algorithm_object, "tolerance", tolerance
64
+ ):
65
+
66
+ unique_vectors = self.duplicate_detection_algorithm_object.get_dataset_unique_structures()
67
+
68
+ results_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
+ == self.duplicate_detection_algorithm_object.vector_count
64
79
 
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
80
+ or find_largest_tolerance_for_target
81
+ ):
70
82
  best_min = tolerance
71
-
72
83
  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
84
+ best_max = tolerance
85
+ tolerance = (best_min + best_max) / 2
86
+
87
+ # reset the dataset_array to the original dataset array after the search is complete
88
+ self.duplicate_detection_algorithm_object.set_dataset_array(old_array)
89
+ self.duplicate_detection_algorithm_object.vector_count = old_vector_count
86
90
  # Find the best exact value if it exists, otherwise find the closest value
87
91
  if len(exact_list) > 0:
88
92
  if find_largest_tolerance_for_target:
@@ -107,21 +111,21 @@ class ToleranceCalculator(ABC):
107
111
  rng=np.random.default_rng(seed)
108
112
  self.tolerance_dataset_array = np.zeros(
109
113
  (
110
- len(self.duplicate_detection_algorithm_object.dataset_array)
114
+ self.duplicate_detection_algorithm_object.vector_count
111
115
  * self.perturbations_per_vector,
112
116
  self.duplicate_detection_algorithm_object.dataset_array.shape[1],
113
117
  )
114
118
  )
115
119
 
116
- for i, vector in enumerate(self.duplicate_detection_algorithm_object.dataset_array):
120
+ for i in range(self.duplicate_detection_algorithm_object.vector_count):
117
121
  self.tolerance_dataset_array[i * self.perturbations_per_vector] = (
118
122
  self.duplicate_detection_algorithm_object.dataset_array[i]
119
123
  )
120
124
  for j in range(1, self.perturbations_per_vector):
121
125
  perturbation = rng.normal(
122
- loc=0.0, scale=self.perturbation_scale, size=vector.shape
126
+ loc=0.0, scale=self.perturbation_scale, size=self.duplicate_detection_algorithm_object.dataset_array.shape[1]
123
127
  )
124
- perturbed_vector = vector + perturbation
128
+ perturbed_vector = self.duplicate_detection_algorithm_object.dataset_array[i] + perturbation
125
129
  self.tolerance_dataset_array[i * self.perturbations_per_vector + j] = (
126
130
  perturbed_vector
127
131
  )
@@ -129,7 +133,7 @@ class ToleranceCalculator(ABC):
129
133
  def _ensure_perturbed_dataset(self):
130
134
  if (
131
135
  self.tolerance_dataset_array.shape[0]
132
- != len(self.duplicate_detection_algorithm_object.dataset_array)
136
+ != self.duplicate_detection_algorithm_object.vector_count
133
137
  * self.perturbations_per_vector and self.perturbations_per_vector > 1
134
138
  ):
135
139
  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
+
@@ -39,6 +39,7 @@ class MultiHashing(DuplicateDetectionAlgorithm):
39
39
  distance_matrix: np.ndarray = np.array([]),
40
40
  hash_vector_array: np.ndarray = np.array([]),
41
41
  unique_vector_indices: np.ndarray = np.array([]),
42
+ max_vector_array_size: int = 10000,
42
43
  ) -> None:
43
44
  super().__init__(
44
45
  tolerance=tolerance,
@@ -47,6 +48,7 @@ class MultiHashing(DuplicateDetectionAlgorithm):
47
48
  distance_metric=distance_metric,
48
49
  distance_matrix=distance_matrix,
49
50
  unique_vector_indices=unique_vector_indices,
51
+ max_vector_array_size=max_vector_array_size
50
52
  )
51
53
  self.seed = seed
52
54
  self.sigma_accepatnce_threshold = sigma_accepatnce_threshold
@@ -101,29 +103,34 @@ class MultiHashing(DuplicateDetectionAlgorithm):
101
103
  hash_vector[i] = hash(rounded_and_perturbed[i].tobytes())
102
104
  return hash_vector
103
105
 
104
- def create_hash_vector_array(self) -> np.ndarray:
106
+ def compute_hash_vector_array(self) -> np.ndarray:
105
107
  """Creates the hash vector array for the dataset. Only unique hash values are stored for each perturbation.
106
108
 
107
109
  Returns:
108
110
  np.ndarray: A 2D array containing the hash values for each vector in the dataset for each perturbation.
109
111
  """
110
- self.hash_vector_array = np.zeros(
111
- (self.dataset_array.shape[0], self.perturbations), dtype=int
112
- )
112
+ self.initialize_hash_vector_array()
113
113
  self._ensure_perturbation_array()
114
- for i in range(self.dataset_array.shape[0]):
114
+ for i in range(self.vector_count):
115
115
  hash_vector = self.create_hash_vector(self.dataset_array[i])
116
116
  for j in range(self.perturbations):
117
117
  if hash_vector[j] not in self.hash_vector_array[:, j]:
118
118
  self.hash_vector_array[i, j] = hash_vector[j]
119
119
  return self.hash_vector_array
120
+
121
+ def initialize_hash_vector_array(self) -> None:
122
+ self.hash_vector_array = np.zeros((self.max_vector_array_size, self.perturbations), dtype=int)
123
+
124
+ def get_filled_hash_vector_array(self) -> np.ndarray:
125
+ """Returns the filled portion of the hash vector array corresponding to the current dataset size."""
126
+ return self.hash_vector_array[: self.vector_count]
120
127
 
121
128
  def _ensure_hash_vector_array(self):
122
129
  if self.hash_vector_array.shape[0] != self.dataset_array.shape[0]:
123
130
  warnings.warn(
124
131
  "Hash vector array shape does not match dataset; recomputing."
125
132
  )
126
- self.create_hash_vector_array()
133
+ self.compute_hash_vector_array()
127
134
 
128
135
  def duplicate_check(self) -> bool:
129
136
  """duplicate check against dataset using multi-hashing approach.
@@ -136,7 +143,7 @@ class MultiHashing(DuplicateDetectionAlgorithm):
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_vector_array[: self.vector_count, hash_index]:
140
147
  clash_vector[hash_index] = True
141
148
  duplicate_vote_array = np.sum(clash_vector) / self.perturbations
142
149
 
@@ -149,7 +156,7 @@ class MultiHashing(DuplicateDetectionAlgorithm):
149
156
  hash_vector = self.create_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_vector_array[: self.vector_count, hash_index]:
153
160
  clash_vector[hash_index] = True
154
161
  uniqueness_score = 1 - np.sum(clash_vector) / self.perturbations
155
162
 
@@ -161,18 +168,21 @@ class MultiHashing(DuplicateDetectionAlgorithm):
161
168
  Returns:
162
169
  int: The number of unique structures in the dataset.
163
170
  """
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
171
+ self.compute_hash_vector_array()
172
+ clash_array = np.zeros((self.hash_vector_array[: self.vector_count].shape), dtype=bool)
173
+ clash_array[np.nonzero(self.hash_vector_array[: self.vector_count])] = True
167
174
  self.unique_vector_indices = np.sum(clash_array, axis=1) / self.perturbations >= self.acceptance_threshold
168
175
 
169
176
  return np.sum(self.unique_vector_indices)
170
177
 
171
178
  def pre_dda_processing(self, *args, **kwargs) -> None:
179
+ self.preinitialize_dataset_array()
172
180
  self.set_perturbation_array()
173
181
 
174
182
  def add_input_vector_to_dda(self) -> None:
175
183
  """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))
184
+ self._ensure_hash_vector_array()
185
+ self._dataset_array[self.vector_count] = self.input_vector
177
186
  new_hash_vector = self.create_hash_vector()
178
- self.hash_vector_array = np.vstack((self.hash_vector_array, new_hash_vector))
187
+ self.hash_vector_array[self.vector_count] = new_hash_vector
188
+ 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.4
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())
@@ -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
+ - [ ] Speed up NTPP
@@ -1 +0,0 @@
1
- __version__ = "0.0.3"
File without changes