deduplicate-lib 0.0.1__tar.gz → 0.0.3__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 (29) hide show
  1. deduplicate_lib-0.0.3/PKG-INFO +154 -0
  2. deduplicate_lib-0.0.3/README.md +131 -0
  3. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/pyproject.toml +12 -1
  4. deduplicate_lib-0.0.3/src/deduplicate_lib/__init__.py +1 -0
  5. deduplicate_lib-0.0.3/src/deduplicate_lib/core/duplicate_detection_algorithm.py +154 -0
  6. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib/core/tolerance_calculator.py +10 -12
  7. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/distance_matrix.py +20 -14
  8. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/multi_hashing.py +67 -18
  9. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/tolerance_calculators/natural_tolerance_plateau_probe.py +62 -18
  10. deduplicate_lib-0.0.3/src/deduplicate_lib/plugins/tolerance_calculators/perturbed_dataset_reclustering.py +79 -0
  11. deduplicate_lib-0.0.3/src/deduplicate_lib.egg-info/PKG-INFO +154 -0
  12. deduplicate_lib-0.0.3/src/deduplicate_lib.egg-info/requires.txt +14 -0
  13. deduplicate_lib-0.0.1/PKG-INFO +0 -59
  14. deduplicate_lib-0.0.1/README.md +0 -43
  15. deduplicate_lib-0.0.1/src/deduplicate_lib/__init__.py +0 -1
  16. deduplicate_lib-0.0.1/src/deduplicate_lib/core/duplicate_detection_algorithm.py +0 -98
  17. deduplicate_lib-0.0.1/src/deduplicate_lib/plugins/tolerance_calculators/perturbed_dataset_reclustering.py +0 -26
  18. deduplicate_lib-0.0.1/src/deduplicate_lib.egg-info/PKG-INFO +0 -59
  19. deduplicate_lib-0.0.1/src/deduplicate_lib.egg-info/requires.txt +0 -7
  20. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/LICENSE +0 -0
  21. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/setup.cfg +0 -0
  22. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib/core/__init__.py +0 -0
  23. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib/core/plugin_registry.py +0 -0
  24. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/__init__.py +0 -0
  25. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/__init__.py +0 -0
  26. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/tolerance_calculators/__init__.py +0 -0
  27. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib.egg-info/SOURCES.txt +0 -0
  28. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib.egg-info/dependency_links.txt +0 -0
  29. {deduplicate_lib-0.0.1 → deduplicate_lib-0.0.3}/src/deduplicate_lib.egg-info/top_level.txt +0 -0
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.4
2
+ Name: deduplicate_lib
3
+ Version: 0.0.3
4
+ Summary: A Python package for deduplicating data.
5
+ Author-email: Julian Holland <holland@fhi.mpg.de>
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: numpy
10
+ Requires-Dist: numba
11
+ Requires-Dist: scipy
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest; extra == "dev"
14
+ Requires-Dist: pytest-mock; extra == "dev"
15
+ Requires-Dist: coverage; extra == "dev"
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"
22
+ Dynamic: license-file
23
+
24
+ <div align="center">
25
+ <h1><code>deduplicate_lib</code></h1>
26
+ <p><i>deduplication algorithms in python</i></p>
27
+ </div>
28
+
29
+ ***
30
+ [![GitHub](https://img.shields.io/badge/GitHub-Repository-black?logo=github)](https://github.com/julianholland/deduplicate)
31
+ [![codecov](https://codecov.io/gh/julianholland/deduplicate/graph/badge.svg?token=JL3OTRCXZD)](https://codecov.io/gh/julianholland/deduplicate)
32
+ [![PyPI version](https://badge.fury.io/py/deduplicate_lib.svg)](https://badge.fury.io/py/deduplicate_lib)
33
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
34
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
35
+ [![CI](https://github.com/julianholland/deduplicate/actions/workflows/ci.yml/badge.svg)](https://github.com/julianholland/deduplicate/actions/workflows/ci.yml)
36
+ [![Code style: ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
37
+ <!-- [![Documentation Status](https://readthedocs.org/projects/alomancy/badge/?version=latest)](https://alomancy.readthedocs.io/en/latest/index.html) -->
38
+
39
+ ## Key Features
40
+
41
+
42
+ - Easy to use deduplication algorithms for any vector array
43
+ - Suite of tolerance tuning algorithms to help you find the right tolerance value for your system
44
+ - Suite of benchmarking tools to ensure rigor, accuracy, and speed (not yet implemented)
45
+ - Factory Plugin architecture, for easy extensibility and modification
46
+
47
+ ***
48
+ ## Implemented Algorithms
49
+
50
+ - Distance Matrix (Simple, accurate, expensive): Computes the distance matrix for all vectors and determines duplicates by finding those that fall below a given distance
51
+ - Multi Hashing (Fast): Smears and rounds the vectors using a normal distribution and computes the hashes for each which are then used to determine duplicates by proportion of hash clashes.
52
+ <!-- - Locality Sensitive Hashing (Fast, Accurate) -->
53
+
54
+ ## Quick Start
55
+ install using pip
56
+ ```bash
57
+ pip install deduplicate_lib
58
+ ```
59
+
60
+ load your data into python
61
+
62
+ ```python
63
+ from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
64
+
65
+ # define your paramerters in the MultiHash object
66
+ dda=MultiHash(dataset_array=your_data_array)
67
+
68
+ # return a list of all unique values
69
+ print(dda.deduplicate())
70
+ ```
71
+
72
+ A more detailed example can be seen in the `examples` directory
73
+
74
+ ### Dependencies
75
+
76
+ - Python 3.9+
77
+ - `numpy`
78
+ - `numba`
79
+ - `scipy`
80
+
81
+ ## 🤝 Contributing
82
+
83
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
84
+
85
+ ### Development Setup
86
+
87
+ ```bash
88
+ # Clone the repository
89
+ git clone https://github.com/julianholland/deduplicate.git
90
+ cd deduplicate
91
+
92
+ # Install in development mode
93
+ pip install -e ".[dev]"
94
+
95
+ # Run tests
96
+ pytest
97
+
98
+ # Run linting
99
+ ruff check .
100
+ ruff format .
101
+ ```
102
+
103
+ ### Running Tests
104
+
105
+ ```bash
106
+ # Run all tests
107
+ pytest
108
+
109
+ # Run specific test categories
110
+ pytest tests/core/
111
+ pytest tests/plugins/
112
+ pytest tests/plugins/duplicate_detection_algorithms/distance_matrix
113
+
114
+ # Run with coverage
115
+ pytest --cov
116
+ ```
117
+
118
+ ## 📝 Citation
119
+
120
+ If you use deduplicate_lib in your research, please cite:
121
+
122
+ ```bibtex
123
+ @software{deduplicate2026,
124
+ title={deduplicate_lib: Auto Tolerance Finding Deduplication Algorithms in Python},
125
+ author={Julian Holland},
126
+ year={2026},
127
+ url={https://github.com/julianholland/deduplicate},
128
+ version={0.0.2dev}
129
+ }
130
+ ```
131
+
132
+ ## 📄 License
133
+
134
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
135
+
136
+ ## 🙏 Acknowledgments
137
+
138
+ - The Fritz Haber Institute
139
+ - Juan Manuel Lombardi <3
140
+
141
+
142
+ ## Project Links
143
+
144
+ - [GitHub Repository](https://github.com/julianholland/deduplicate)
145
+
146
+ ## Project To-Do
147
+
148
+ - [x] Add example.ipynb
149
+ - [ ] Create general Pre-allocation protocal
150
+ - [ ] Add benchmarks for time and robustness
151
+ - [ ] Add Locality-Sensitive Hashing as an option
152
+ - [x] Speedup slow tasks with Numba
153
+ - [ ] Set up Read the Docs
154
+ - [x] Create general deduplicate function
@@ -0,0 +1,131 @@
1
+ <div align="center">
2
+ <h1><code>deduplicate_lib</code></h1>
3
+ <p><i>deduplication algorithms in python</i></p>
4
+ </div>
5
+
6
+ ***
7
+ [![GitHub](https://img.shields.io/badge/GitHub-Repository-black?logo=github)](https://github.com/julianholland/deduplicate)
8
+ [![codecov](https://codecov.io/gh/julianholland/deduplicate/graph/badge.svg?token=JL3OTRCXZD)](https://codecov.io/gh/julianholland/deduplicate)
9
+ [![PyPI version](https://badge.fury.io/py/deduplicate_lib.svg)](https://badge.fury.io/py/deduplicate_lib)
10
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
11
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
12
+ [![CI](https://github.com/julianholland/deduplicate/actions/workflows/ci.yml/badge.svg)](https://github.com/julianholland/deduplicate/actions/workflows/ci.yml)
13
+ [![Code style: ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
14
+ <!-- [![Documentation Status](https://readthedocs.org/projects/alomancy/badge/?version=latest)](https://alomancy.readthedocs.io/en/latest/index.html) -->
15
+
16
+ ## Key Features
17
+
18
+
19
+ - Easy to use deduplication algorithms for any vector array
20
+ - Suite of tolerance tuning algorithms to help you find the right tolerance value for your system
21
+ - Suite of benchmarking tools to ensure rigor, accuracy, and speed (not yet implemented)
22
+ - Factory Plugin architecture, for easy extensibility and modification
23
+
24
+ ***
25
+ ## Implemented Algorithms
26
+
27
+ - Distance Matrix (Simple, accurate, expensive): Computes the distance matrix for all vectors and determines duplicates by finding those that fall below a given distance
28
+ - Multi Hashing (Fast): Smears and rounds the vectors using a normal distribution and computes the hashes for each which are then used to determine duplicates by proportion of hash clashes.
29
+ <!-- - Locality Sensitive Hashing (Fast, Accurate) -->
30
+
31
+ ## Quick Start
32
+ install using pip
33
+ ```bash
34
+ pip install deduplicate_lib
35
+ ```
36
+
37
+ load your data into python
38
+
39
+ ```python
40
+ from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
41
+
42
+ # define your paramerters in the MultiHash object
43
+ dda=MultiHash(dataset_array=your_data_array)
44
+
45
+ # return a list of all unique values
46
+ print(dda.deduplicate())
47
+ ```
48
+
49
+ A more detailed example can be seen in the `examples` directory
50
+
51
+ ### Dependencies
52
+
53
+ - Python 3.9+
54
+ - `numpy`
55
+ - `numba`
56
+ - `scipy`
57
+
58
+ ## 🤝 Contributing
59
+
60
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
61
+
62
+ ### Development Setup
63
+
64
+ ```bash
65
+ # Clone the repository
66
+ git clone https://github.com/julianholland/deduplicate.git
67
+ cd deduplicate
68
+
69
+ # Install in development mode
70
+ pip install -e ".[dev]"
71
+
72
+ # Run tests
73
+ pytest
74
+
75
+ # Run linting
76
+ ruff check .
77
+ ruff format .
78
+ ```
79
+
80
+ ### Running Tests
81
+
82
+ ```bash
83
+ # Run all tests
84
+ pytest
85
+
86
+ # Run specific test categories
87
+ pytest tests/core/
88
+ pytest tests/plugins/
89
+ pytest tests/plugins/duplicate_detection_algorithms/distance_matrix
90
+
91
+ # Run with coverage
92
+ pytest --cov
93
+ ```
94
+
95
+ ## 📝 Citation
96
+
97
+ If you use deduplicate_lib in your research, please cite:
98
+
99
+ ```bibtex
100
+ @software{deduplicate2026,
101
+ title={deduplicate_lib: Auto Tolerance Finding Deduplication Algorithms in Python},
102
+ author={Julian Holland},
103
+ year={2026},
104
+ url={https://github.com/julianholland/deduplicate},
105
+ version={0.0.2dev}
106
+ }
107
+ ```
108
+
109
+ ## 📄 License
110
+
111
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
112
+
113
+ ## 🙏 Acknowledgments
114
+
115
+ - The Fritz Haber Institute
116
+ - Juan Manuel Lombardi <3
117
+
118
+
119
+ ## Project Links
120
+
121
+ - [GitHub Repository](https://github.com/julianholland/deduplicate)
122
+
123
+ ## Project To-Do
124
+
125
+ - [x] Add example.ipynb
126
+ - [ ] Create general Pre-allocation protocal
127
+ - [ ] Add benchmarks for time and robustness
128
+ - [ ] Add Locality-Sensitive Hashing as an option
129
+ - [x] Speedup slow tasks with Numba
130
+ - [ ] Set up Read the Docs
131
+ - [x] Create general deduplicate function
@@ -9,6 +9,8 @@ readme = "README.md"
9
9
  requires-python = ">=3.8"
10
10
  dependencies = [
11
11
  "numpy",
12
+ "numba",
13
+ "scipy",
12
14
  ]
13
15
 
14
16
  [tool.setuptools]
@@ -18,7 +20,16 @@ package-dir = {"" = "src"}
18
20
  version = {attr = "deduplicate_lib.__version__"}
19
21
 
20
22
  [project.optional-dependencies]
21
- 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",]
22
33
 
23
34
  [tool.pytest.ini_options]
24
35
  testpaths = ["tests"]
@@ -0,0 +1 @@
1
+ __version__ = "0.0.3"
@@ -0,0 +1,154 @@
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
+ ) -> None:
75
+ self.tolerance = tolerance
76
+ self.input_vector = input_vector
77
+ self.dataset_array = dataset_array
78
+ self.distance_matrix = distance_matrix
79
+ self.distance_metric = distance_metric
80
+ self.unique_vector_indices = unique_vector_indices
81
+
82
+ # In DuplicateDetectionAlgorithm
83
+
84
+ @property
85
+ def distance_metric(self):
86
+ return self._distance_metric
87
+
88
+ @distance_metric.setter
89
+ def distance_metric(self, value):
90
+ if value not in self.ALLOWED_DISTANCES:
91
+ raise ValueError(
92
+ f"Unsupported distance metric: {value}, "
93
+ f"supported metrics are: {list(self.ALLOWED_DISTANCES.keys())}"
94
+ )
95
+ self._distance_metric = value
96
+ self.distance_function = self.ALLOWED_DISTANCES[value]
97
+
98
+ def calculate_distance(self, vector1: np.ndarray, vector2: np.ndarray) -> float:
99
+ return self.distance_function(vector1, vector2)
100
+
101
+ def compute_distance_matrix(self, vector_array: np.ndarray) -> None:
102
+ """Compute the distance matrix for the dataset from scratch."""
103
+ self.distance_matrix = fast_compute_distance_matrix(
104
+ vector_array, self.distance_function
105
+ )
106
+
107
+ def get_new_distance_matrix_column(self, vector_array: np.ndarray) -> np.ndarray:
108
+ """Calculates the distance matrix for the distances of a new input vector.
109
+
110
+ Returns:
111
+ np.ndarray: A 1D array containing the distances from the input vector to each vector in the dataset.
112
+ """
113
+ return fast_get_new_distance_matrix_column(
114
+ self.input_vector, vector_array, self.distance_function
115
+ )
116
+
117
+ def add_new_vector_to_distance_matrix(self, vector_array: np.ndarray) -> None:
118
+ """Add a new input vector to the distance matrix."""
119
+ 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))
125
+
126
+ def pre_dda_processing(
127
+ self, input_dataset_array: np.ndarray | None = None, *args, **kwargs
128
+ ) -> None:
129
+ """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."""
130
+ pass
131
+
132
+ def add_input_vector_to_dda(self) -> None:
133
+ """Add the input vector to the dataset array and update the distance matrix accordingly."""
134
+ pass
135
+
136
+ def get_unique_vector_indices(self) -> np.ndarray:
137
+ """Returns the indices of the unique vectors in the dataset."""
138
+ if self.unique_vector_indices.shape[0] != self.dataset_array.shape[0]:
139
+ raise ValueError(
140
+ "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
+ )
142
+ return np.where(self.unique_vector_indices)[0]
143
+
144
+ def deduplicate(self):
145
+ """Finds all unique vectors in the dataset and returns them as a new array."""
146
+ return self.dataset_array[self.get_unique_vector_indices()]
147
+
148
+ @abstractmethod
149
+ def duplicate_check(self) -> bool:
150
+ pass # pragma: no cover
151
+
152
+ @abstractmethod
153
+ def get_dataset_unique_structures(self) -> int:
154
+ pass # pragma: no cover
@@ -42,17 +42,15 @@ class ToleranceCalculator(ABC):
42
42
  ptp=np.ptp(self.tolerance_dataset_array)
43
43
  abs_std=np.mean(np.std(self.tolerance_dataset_array, axis=0))
44
44
  best_max = (ptp + abs_std) * self.duplicate_detection_algorithm_object.dataset_array.shape[1]
45
- tolerance = best_max
45
+ tolerance = best_max
46
46
 
47
47
  exact_list = []
48
- all_diff_dict = {}
49
-
48
+ results_dict = {}
50
49
  if self.binary_search_steps <= 0:
51
50
  warnings.warn(f"Binary search called with {self.binary_search_steps} steps. No binary search performed.\n Returning tolerance of half the range of the perturbed dataset: {tolerance}.")
52
51
  return tolerance
53
52
 
54
53
  # temporarily set the dataset_array to the tolerance_dataset_array for the duration of the search
55
- print(self.duplicate_detection_algorithm_object.distance_matrix.shape)
56
54
  with self.temp_attr(
57
55
  self.duplicate_detection_algorithm_object,
58
56
  "dataset_array",
@@ -65,7 +63,7 @@ class ToleranceCalculator(ABC):
65
63
  ):
66
64
 
67
65
  unique_vectors = self.duplicate_detection_algorithm_object.get_dataset_unique_structures()
68
- all_diff_dict[tolerance] = unique_vectors
66
+ results_dict[tolerance] = unique_vectors
69
67
  if unique_vectors < target_unique_vectors: # loosen tolerance
70
68
  best_max = tolerance
71
69
  elif unique_vectors > target_unique_vectors: # tighten tolerance
@@ -92,14 +90,14 @@ class ToleranceCalculator(ABC):
92
90
  else:
93
91
  tolerance = min(exact_list)
94
92
  else:
95
-
93
+ closest_tol = min(results_dict.keys(), key=lambda tol: abs(results_dict[tol] - target_unique_vectors))
94
+ min_diff = results_dict[closest_tol] - target_unique_vectors
96
95
  tolerance = [
97
96
  tol
98
- for tol, diff in all_diff_dict.items()
99
- if diff == min(all_diff_dict.values())
97
+ for tol, unique_vectors in results_dict.items()
98
+ if unique_vectors == target_unique_vectors + min_diff
100
99
  ][0]
101
- warnings.warn(f"No exact tolerance found for target of {target_unique_vectors} unique vectors during binary search.\n Returning closest tolerance found: {tolerance} with {all_diff_dict[tolerance]} unique vectors.")
102
- print(all_diff_dict)
100
+ warnings.warn(f"No exact tolerance found for target of {target_unique_vectors} unique vectors during binary search.\n Returning closest tolerance found: {tolerance} with {results_dict[tolerance]} unique vectors.")
103
101
  return tolerance
104
102
 
105
103
  def create_perturbed_dataset(self, seed: int = 803):
@@ -132,7 +130,7 @@ class ToleranceCalculator(ABC):
132
130
  if (
133
131
  self.tolerance_dataset_array.shape[0]
134
132
  != len(self.duplicate_detection_algorithm_object.dataset_array)
135
- * self.perturbations_per_vector
133
+ * self.perturbations_per_vector and self.perturbations_per_vector > 1
136
134
  ):
137
135
  warnings.warn(
138
136
  "Perturbed dataset is not properly initialized. Recreating it.\nEnsure a perturbed dataset is set prior finding tolerance."
@@ -141,4 +139,4 @@ class ToleranceCalculator(ABC):
141
139
 
142
140
  @abstractmethod
143
141
  def calculate_tolerance(self) -> float:
144
- pass
142
+ pass # pragma: no cover, implemented in child classes
@@ -1,20 +1,21 @@
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
-
4
+ import warnings
5
5
 
6
6
  @register_plugin(kind="duplicate_detection_algorithm", name="distance_matrix")
7
7
  class DistanceMatrix(DuplicateDetectionAlgorithm):
8
8
  def __init__(
9
9
  self,
10
- tolerance: float,
11
- input_vector: np.ndarray,
12
- dataset_array: np.ndarray,
10
+ tolerance: float = 0.1,
11
+ input_vector: np.ndarray = np.array([]),
12
+ dataset_array: np.ndarray = np.array([]),
13
13
  distance_matrix: np.ndarray = np.array([]),
14
14
  distance_metric: str = "euclidean",
15
+ unique_vector_indices: np.ndarray = np.array([]),
15
16
  ) -> None:
16
17
  super().__init__(
17
- tolerance, input_vector, dataset_array, distance_matrix, distance_metric
18
+ tolerance, input_vector, dataset_array, distance_matrix, distance_metric, unique_vector_indices
18
19
  )
19
20
 
20
21
  def __str__(self) -> str:
@@ -22,10 +23,9 @@ class DistanceMatrix(DuplicateDetectionAlgorithm):
22
23
 
23
24
  def _ensure_distance_matrix(self):
24
25
  if self.distance_matrix.shape[0] != self.dataset_array.shape[0]:
25
- # warnings.warn(f"Distance matrix shape does not match dataset; recomputing.{self.dataset_array.shape[0]}, {self.distance_matrix.shape[0]}")
26
- # self.compute_distance_matrix(self.dataset_array)
27
- print(self.dataset_array.shape, self.distance_matrix.shape)
28
- raise ValueError("Distance matrix shape does not match dataset; recomputing is currently disabled to avoid long computations during testing. Please compute the distance matrix manually and assign it to the duplicate detection algorithm object before duplication checks.")
26
+ warnings.warn("Distance matrix shape does not match dataset; recomputing.")
27
+ self.compute_distance_matrix(self.dataset_array)
28
+
29
29
 
30
30
  def duplicate_check(self) -> bool:
31
31
  return bool(
@@ -36,15 +36,21 @@ class DistanceMatrix(DuplicateDetectionAlgorithm):
36
36
 
37
37
  def get_dataset_unique_structures(self) -> int:
38
38
  self._ensure_distance_matrix()
39
- unique_structures = 1
40
-
39
+ self.unique_vector_indices = np.zeros(self.dataset_array.shape[0], dtype=bool)
40
+ self.unique_vector_indices[0] = True # the first vector is always unique
41
41
  for i in range(1, self.distance_matrix.shape[0]):
42
42
  imask = np.arange(self.distance_matrix.shape[0]) != i
43
43
  if np.all(self.distance_matrix[i][imask] >= self.tolerance):
44
- unique_structures += 1
45
- return unique_structures
44
+ self.unique_vector_indices[i] = True
45
+ return np.sum(self.unique_vector_indices)
46
46
 
47
47
  def pre_dda_processing(self, input_dataset_array: np.ndarray | None = None, *args, **kwargs) -> None:
48
48
  if input_dataset_array is None:
49
49
  input_dataset_array = self.dataset_array
50
- self.compute_distance_matrix(input_dataset_array)
50
+ self.compute_distance_matrix(input_dataset_array)
51
+
52
+ def add_input_vector_to_dda(self) -> None:
53
+ """Add the input vector to the dataset array and update the distance matrix accordingly."""
54
+ self.add_new_vector_to_distance_matrix(self.dataset_array)
55
+ self.dataset_array = np.vstack((self.dataset_array, self.input_vector))
56
+