deduplicate-lib 0.0.2__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 (25) hide show
  1. {deduplicate_lib-0.0.2/src/deduplicate_lib.egg-info → deduplicate_lib-0.0.4}/PKG-INFO +17 -11
  2. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/README.md +12 -11
  3. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/pyproject.toml +10 -1
  4. deduplicate_lib-0.0.4/src/deduplicate_lib/__init__.py +1 -0
  5. deduplicate_lib-0.0.4/src/deduplicate_lib/core/duplicate_detection_algorithm.py +238 -0
  6. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib/core/tolerance_calculator.py +39 -35
  7. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/distance_matrix.py +13 -20
  8. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/multi_hashing.py +68 -24
  9. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/tolerance_calculators/natural_tolerance_plateau_probe.py +46 -36
  10. deduplicate_lib-0.0.4/src/deduplicate_lib/plugins/tolerance_calculators/perturbed_dataset_reclustering.py +82 -0
  11. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4/src/deduplicate_lib.egg-info}/PKG-INFO +17 -11
  12. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib.egg-info/requires.txt +5 -0
  13. deduplicate_lib-0.0.2/src/deduplicate_lib/__init__.py +0 -1
  14. deduplicate_lib-0.0.2/src/deduplicate_lib/core/duplicate_detection_algorithm.py +0 -154
  15. deduplicate_lib-0.0.2/src/deduplicate_lib/plugins/tolerance_calculators/perturbed_dataset_reclustering.py +0 -46
  16. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/LICENSE +0 -0
  17. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/setup.cfg +0 -0
  18. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib/core/__init__.py +0 -0
  19. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib/core/plugin_registry.py +0 -0
  20. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/__init__.py +0 -0
  21. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/__init__.py +0 -0
  22. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib/plugins/tolerance_calculators/__init__.py +0 -0
  23. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib.egg-info/SOURCES.txt +0 -0
  24. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.4}/src/deduplicate_lib.egg-info/dependency_links.txt +0 -0
  25. {deduplicate_lib-0.0.2 → 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.2
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
@@ -14,6 +14,11 @@ Requires-Dist: pytest; extra == "dev"
14
14
  Requires-Dist: pytest-mock; extra == "dev"
15
15
  Requires-Dist: coverage; extra == "dev"
16
16
  Requires-Dist: ruff; extra == "dev"
17
+ Requires-Dist: nbconvert; extra == "dev"
18
+ Requires-Dist: nbclient; extra == "dev"
19
+ Requires-Dist: notebook; extra == "dev"
20
+ Requires-Dist: ipykernel; extra == "dev"
21
+ Requires-Dist: matplotlib; extra == "dev"
17
22
  Dynamic: license-file
18
23
 
19
24
  <div align="center">
@@ -58,13 +63,10 @@ load your data into python
58
63
  from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
59
64
 
60
65
  # define your paramerters in the MultiHash object
61
- dda=MultiHash(
62
- tolerance=0.01,
63
- dataset_array: your_data_array,
64
- perturbations: int = 200,
65
- )
66
+ dda=MultiHash(dataset_array=your_data_numpy_array)
66
67
 
67
- print(dda.get_dataset_unique_structures())
68
+ # return a list of all unique values
69
+ print(dda.deduplicate())
68
70
  ```
69
71
 
70
72
  A more detailed example can be seen in the `examples` directory
@@ -74,6 +76,7 @@ A more detailed example can be seen in the `examples` directory
74
76
  - Python 3.9+
75
77
  - `numpy`
76
78
  - `numba`
79
+ - `scipy`
77
80
 
78
81
  ## 🤝 Contributing
79
82
 
@@ -117,12 +120,12 @@ pytest --cov
117
120
  If you use deduplicate_lib in your research, please cite:
118
121
 
119
122
  ```bibtex
120
- @software{alomancy2025,
121
- title={Deduplicate_lib: Auto Tolerance Finding Deduplication Algorithms in Python},
123
+ @software{deduplicate2026,
124
+ title={deduplicate_lib: Auto Tolerance Finding Deduplication Algorithms in Python},
122
125
  author={Julian Holland},
123
126
  year={2026},
124
127
  url={https://github.com/julianholland/deduplicate},
125
- version={0.0.1dev}
128
+ version={0.0.2dev}
126
129
  }
127
130
  ```
128
131
 
@@ -134,6 +137,8 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
134
137
 
135
138
  - The Fritz Haber Institute
136
139
  - Juan Manuel Lombardi <3
140
+ - Maximillion Ach
141
+ - Chiara Panosetti
137
142
 
138
143
 
139
144
  ## Project Links
@@ -143,9 +148,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
143
148
  ## Project To-Do
144
149
 
145
150
  - [x] Add example.ipynb
146
- - [ ] Create general Pre-allocation protocal
151
+ - [x] Create general Pre-allocation protocal
147
152
  - [ ] Add benchmarks for time and robustness
148
153
  - [ ] Add Locality-Sensitive Hashing as an option
149
154
  - [x] Speedup slow tasks with Numba
150
155
  - [ ] Set up Read the Docs
151
156
  - [x] Create general deduplicate function
157
+ - [ ] Speed up NTPP
@@ -40,13 +40,10 @@ 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(
44
- tolerance=0.01,
45
- dataset_array: your_data_array,
46
- perturbations: int = 200,
47
- )
43
+ dda=MultiHash(dataset_array=your_data_numpy_array)
48
44
 
49
- print(dda.get_dataset_unique_structures())
45
+ # return a list of all unique values
46
+ print(dda.deduplicate())
50
47
  ```
51
48
 
52
49
  A more detailed example can be seen in the `examples` directory
@@ -56,6 +53,7 @@ A more detailed example can be seen in the `examples` directory
56
53
  - Python 3.9+
57
54
  - `numpy`
58
55
  - `numba`
56
+ - `scipy`
59
57
 
60
58
  ## 🤝 Contributing
61
59
 
@@ -99,12 +97,12 @@ pytest --cov
99
97
  If you use deduplicate_lib in your research, please cite:
100
98
 
101
99
  ```bibtex
102
- @software{alomancy2025,
103
- title={Deduplicate_lib: Auto Tolerance Finding Deduplication Algorithms in Python},
100
+ @software{deduplicate2026,
101
+ title={deduplicate_lib: Auto Tolerance Finding Deduplication Algorithms in Python},
104
102
  author={Julian Holland},
105
103
  year={2026},
106
104
  url={https://github.com/julianholland/deduplicate},
107
- version={0.0.1dev}
105
+ version={0.0.2dev}
108
106
  }
109
107
  ```
110
108
 
@@ -116,6 +114,8 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
116
114
 
117
115
  - The Fritz Haber Institute
118
116
  - Juan Manuel Lombardi <3
117
+ - Maximillion Ach
118
+ - Chiara Panosetti
119
119
 
120
120
 
121
121
  ## Project Links
@@ -125,9 +125,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
125
125
  ## Project To-Do
126
126
 
127
127
  - [x] Add example.ipynb
128
- - [ ] Create general Pre-allocation protocal
128
+ - [x] Create general Pre-allocation protocal
129
129
  - [ ] Add benchmarks for time and robustness
130
130
  - [ ] Add Locality-Sensitive Hashing as an option
131
131
  - [x] Speedup slow tasks with Numba
132
132
  - [ ] Set up Read the Docs
133
- - [x] Create general deduplicate function
133
+ - [x] Create general deduplicate function
134
+ - [ ] Speed up NTPP
@@ -20,7 +20,16 @@ package-dir = {"" = "src"}
20
20
  version = {attr = "deduplicate_lib.__version__"}
21
21
 
22
22
  [project.optional-dependencies]
23
- dev = ["pytest", "pytest-mock", "coverage", "ruff"]
23
+ dev = [
24
+ "pytest",
25
+ "pytest-mock",
26
+ "coverage",
27
+ "ruff",
28
+ "nbconvert",
29
+ "nbclient",
30
+ "notebook",
31
+ "ipykernel",
32
+ "matplotlib",]
24
33
 
25
34
  [tool.pytest.ini_options]
26
35
  testpaths = ["tests"]
@@ -0,0 +1 @@
1
+ __version__ = "0.0.4"
@@ -0,0 +1,238 @@
1
+ import numpy as np
2
+ from abc import ABC, abstractmethod
3
+ from numba import njit
4
+
5
+
6
+ @njit
7
+ def fast_compute_distance_matrix(vector_array, distance_func):
8
+ num_samples = vector_array.shape[0] # pragma: no cover, tested but does not appear in coverage report due to numba jit compilation
9
+ distance_matrix = np.zeros((num_samples, num_samples)) # pragma: no cover
10
+ for i in range(num_samples): # pragma: no cover
11
+ for j in range(i + 1, num_samples): # pragma: no cover
12
+ distance = distance_func(vector_array[i], vector_array[j]) # pragma: no cover
13
+ distance_matrix[i, j] = distance # pragma: no cover
14
+ distance_matrix[j, i] = distance # pragma: no cover
15
+ return distance_matrix # pragma: no cover
16
+
17
+
18
+ @njit
19
+ def fast_get_new_distance_matrix_column(
20
+ input_vector: np.ndarray, vector_array: np.ndarray, distance_func
21
+ ) -> np.ndarray:
22
+ """Calculates the distance matrix for the distances of a new input vector.
23
+
24
+ Returns:
25
+ np.ndarray: A 1D array containing the distances from the input vector to each vector in the dataset.
26
+ """
27
+ num_samples = vector_array.shape[0] # pragma: no cover
28
+ new_distances = np.zeros(num_samples) # pragma: no cover
29
+ for i in range(num_samples): # pragma: no cover
30
+ new_distances[i] = distance_func(input_vector, vector_array[i]) # pragma: no cover
31
+ return new_distances # pragma: no cover
32
+
33
+
34
+ # must be jit compatible functions, so defined outside of the class and not as static methods
35
+ @njit
36
+ def euclidean_distance(v1, v2):
37
+ return float(np.linalg.norm(v1 - v2)) # pragma: no cover
38
+
39
+
40
+ @njit
41
+ def manhattan_distance(v1, v2):
42
+ return np.sum(np.abs(v1 - v2)) # pragma: no cover
43
+
44
+
45
+ @njit
46
+ def cosine_distance(v1, v2):
47
+ return 1 - np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)) # pragma: no cover
48
+
49
+
50
+ @njit
51
+ def hamming_distance(v1, v2):
52
+ return np.sum(v1 != v2) # pragma: no cover
53
+
54
+
55
+ DISTANCE_FUNCTIONS = {
56
+ "euclidean": euclidean_distance,
57
+ "manhattan": manhattan_distance,
58
+ "cosine": cosine_distance,
59
+ "hamming": hamming_distance,
60
+ }
61
+
62
+
63
+ class DuplicateDetectionAlgorithm(ABC):
64
+ ALLOWED_DISTANCES = DISTANCE_FUNCTIONS
65
+
66
+ def __init__(
67
+ self,
68
+ tolerance: float,
69
+ input_vector: np.ndarray = np.array([]),
70
+ dataset_array: np.ndarray = np.array([]),
71
+ distance_matrix: np.ndarray = np.array([]),
72
+ distance_metric: str = "euclidean",
73
+ unique_vector_indices: np.ndarray = np.array([]),
74
+ max_vector_array_size: int = 10000,
75
+ ) -> None:
76
+ self.tolerance = tolerance
77
+ self.input_vector = input_vector
78
+ self._dataset_array = np.array([]) # will be initialized properly in preinitialize_dataset_array
79
+
80
+ self.distance_matrix = distance_matrix
81
+ self.distance_metric = distance_metric
82
+ self.unique_vector_indices = unique_vector_indices
83
+ self.max_vector_array_size = max_vector_array_size
84
+
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
101
+
102
+ @property
103
+ def distance_metric(self):
104
+ return self._distance_metric
105
+
106
+ @distance_metric.setter
107
+ def distance_metric(self, value):
108
+ if value not in self.ALLOWED_DISTANCES:
109
+ raise ValueError(
110
+ f"Unsupported distance metric: {value}, "
111
+ f"supported metrics are: {list(self.ALLOWED_DISTANCES.keys())}"
112
+ )
113
+ self._distance_metric = value
114
+ self.distance_function = self.ALLOWED_DISTANCES[value]
115
+
116
+ def calculate_distance(self, vector1: np.ndarray, vector2: np.ndarray) -> float:
117
+ return self.distance_function(vector1, vector2)
118
+
119
+ def compute_distance_matrix(self, vector_array: np.ndarray | None = None) -> None:
120
+ """Compute the distance matrix for the dataset from scratch."""
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
129
+ )
130
+
131
+ def get_new_distance_matrix_column(self, vector_array: np.ndarray) -> np.ndarray:
132
+ """Calculates the distance matrix for the distances of a new input vector.
133
+
134
+ Returns:
135
+ np.ndarray: A 1D array containing the distances from the input vector to each vector in the dataset.
136
+ """
137
+ return fast_get_new_distance_matrix_column(
138
+ self.input_vector, vector_array[: self.vector_count], self.distance_function
139
+ )
140
+
141
+ def add_new_vector_to_distance_matrix(self, vector_array: np.ndarray) -> None:
142
+ """Add a new input vector to the distance matrix."""
143
+ new_distances = self.get_new_distance_matrix_column(vector_array)
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
+
147
+
148
+ def pre_dda_processing(
149
+ self, input_dataset_array: np.ndarray | None = None, *args, **kwargs
150
+ ) -> None:
151
+ """A method that can be overridden by child classes to perform any necessary processing before duplication checks. For example, this could be used to compute the distance matrix for the dataset before any duplication checks are performed, which would save time if multiple duplication checks are being performed on the same dataset with different input vectors."""
152
+ pass
153
+
154
+ def add_input_vector_to_dda(self) -> None:
155
+ """Add the input vector to the dataset array and update the distance matrix accordingly."""
156
+ pass
157
+
158
+ def get_unique_vector_indices(self) -> np.ndarray:
159
+ """Returns the indices of the unique vectors in the dataset."""
160
+ if self.unique_vector_indices.shape[0] != self.vector_count:
161
+ raise ValueError(
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."
163
+ )
164
+ return np.where(self.unique_vector_indices)[0]
165
+
166
+ def deduplicate(self):
167
+ """Finds all unique vectors in the dataset and returns them as a new array."""
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
231
+
232
+ @abstractmethod
233
+ def duplicate_check(self) -> bool:
234
+ pass # pragma: no cover
235
+
236
+ @abstractmethod
237
+ def get_dataset_unique_structures(self) -> int:
238
+ pass # pragma: no cover
@@ -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(
@@ -139,4 +143,4 @@ class ToleranceCalculator(ABC):
139
143
 
140
144
  @abstractmethod
141
145
  def calculate_tolerance(self) -> float:
142
- pass
146
+ pass # pragma: no cover, implemented in child classes
@@ -2,7 +2,6 @@ from deduplicate_lib.core.duplicate_detection_algorithm import DuplicateDetectio
2
2
  from deduplicate_lib.core.plugin_registry import register_plugin
3
3
  import numpy as np
4
4
 
5
-
6
5
  @register_plugin(kind="duplicate_detection_algorithm", name="distance_matrix")
7
6
  class DistanceMatrix(DuplicateDetectionAlgorithm):
8
7
  def __init__(
@@ -13,21 +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(f"Distance matrix shape does not match dataset; recomputing.{self.dataset_array.shape[0]}, {self.distance_matrix.shape[0]}")
27
- # self.compute_distance_matrix(self.dataset_array)
28
- print(self.dataset_array.shape, self.distance_matrix.shape)
29
- 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.")
30
-
31
24
  def duplicate_check(self) -> bool:
32
25
  return bool(
33
26
  np.any(
@@ -36,22 +29,22 @@ class DistanceMatrix(DuplicateDetectionAlgorithm):
36
29
  )
37
30
 
38
31
  def get_dataset_unique_structures(self) -> int:
39
- self._ensure_distance_matrix()
40
- 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)
41
33
  self.unique_vector_indices[0] = True # the first vector is always unique
42
- for i in range(1, self.distance_matrix.shape[0]):
43
- imask = np.arange(self.distance_matrix.shape[0]) != i
44
- 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):
45
37
  self.unique_vector_indices[i] = True
46
38
  return np.sum(self.unique_vector_indices)
47
39
 
48
- def pre_dda_processing(self, input_dataset_array: np.ndarray | None = None, *args, **kwargs) -> None:
49
- if input_dataset_array is None:
50
- input_dataset_array = self.dataset_array
51
- 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)
52
44
 
53
45
  def add_input_vector_to_dda(self) -> None:
54
46
  """Add the input vector to the dataset array and update the distance matrix accordingly."""
55
47
  self.add_new_vector_to_distance_matrix(self.dataset_array)
56
- self.dataset_array = np.vstack((self.dataset_array, self.input_vector))
57
-
48
+ self._dataset_array[self.vector_count] = self.input_vector
49
+ self.vector_count += 1
50
+