deduplicate-lib 0.0.2__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 (24) hide show
  1. {deduplicate_lib-0.0.2/src/deduplicate_lib.egg-info → deduplicate_lib-0.0.3}/PKG-INFO +13 -10
  2. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/README.md +7 -9
  3. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/pyproject.toml +10 -1
  4. deduplicate_lib-0.0.3/src/deduplicate_lib/__init__.py +1 -0
  5. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib/core/duplicate_detection_algorithm.py +20 -20
  6. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib/core/tolerance_calculator.py +1 -1
  7. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/distance_matrix.py +4 -5
  8. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/multi_hashing.py +46 -12
  9. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/tolerance_calculators/natural_tolerance_plateau_probe.py +32 -24
  10. deduplicate_lib-0.0.3/src/deduplicate_lib/plugins/tolerance_calculators/perturbed_dataset_reclustering.py +79 -0
  11. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3/src/deduplicate_lib.egg-info}/PKG-INFO +13 -10
  12. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/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/plugins/tolerance_calculators/perturbed_dataset_reclustering.py +0 -46
  15. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/LICENSE +0 -0
  16. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/setup.cfg +0 -0
  17. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib/core/__init__.py +0 -0
  18. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib/core/plugin_registry.py +0 -0
  19. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/__init__.py +0 -0
  20. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/__init__.py +0 -0
  21. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib/plugins/tolerance_calculators/__init__.py +0 -0
  22. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib.egg-info/SOURCES.txt +0 -0
  23. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/src/deduplicate_lib.egg-info/dependency_links.txt +0 -0
  24. {deduplicate_lib-0.0.2 → deduplicate_lib-0.0.3}/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.3
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_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
 
@@ -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_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
 
@@ -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.3"
@@ -5,14 +5,14 @@ from numba import njit
5
5
 
6
6
  @njit
7
7
  def fast_compute_distance_matrix(vector_array, distance_func):
8
- num_samples = vector_array.shape[0]
9
- distance_matrix = np.zeros((num_samples, num_samples))
10
- for i in range(num_samples):
11
- for j in range(i + 1, num_samples):
12
- distance = distance_func(vector_array[i], vector_array[j])
13
- distance_matrix[i, j] = distance
14
- distance_matrix[j, i] = distance
15
- return distance_matrix
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
16
 
17
17
 
18
18
  @njit
@@ -24,32 +24,32 @@ def fast_get_new_distance_matrix_column(
24
24
  Returns:
25
25
  np.ndarray: A 1D array containing the distances from the input vector to each vector in the dataset.
26
26
  """
27
- num_samples = vector_array.shape[0]
28
- new_distances = np.zeros(num_samples)
29
- for i in range(num_samples):
30
- new_distances[i] = distance_func(input_vector, vector_array[i])
31
- return new_distances
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
32
 
33
33
 
34
34
  # must be jit compatible functions, so defined outside of the class and not as static methods
35
35
  @njit
36
36
  def euclidean_distance(v1, v2):
37
- return float(np.linalg.norm(v1 - v2))
37
+ return float(np.linalg.norm(v1 - v2)) # pragma: no cover
38
38
 
39
39
 
40
40
  @njit
41
41
  def manhattan_distance(v1, v2):
42
- return np.sum(np.abs(v1 - v2))
42
+ return np.sum(np.abs(v1 - v2)) # pragma: no cover
43
43
 
44
44
 
45
45
  @njit
46
46
  def cosine_distance(v1, v2):
47
- return 1 - np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
47
+ return 1 - np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)) # pragma: no cover
48
48
 
49
49
 
50
50
  @njit
51
51
  def hamming_distance(v1, v2):
52
- return np.sum(v1 != v2)
52
+ return np.sum(v1 != v2) # pragma: no cover
53
53
 
54
54
 
55
55
  DISTANCE_FUNCTIONS = {
@@ -70,7 +70,7 @@ class DuplicateDetectionAlgorithm(ABC):
70
70
  dataset_array: np.ndarray = np.array([]),
71
71
  distance_matrix: np.ndarray = np.array([]),
72
72
  distance_metric: str = "euclidean",
73
- unique_vector_indices: np.array = np.array([]),
73
+ unique_vector_indices: np.ndarray = np.array([]),
74
74
  ) -> None:
75
75
  self.tolerance = tolerance
76
76
  self.input_vector = input_vector
@@ -147,8 +147,8 @@ class DuplicateDetectionAlgorithm(ABC):
147
147
 
148
148
  @abstractmethod
149
149
  def duplicate_check(self) -> bool:
150
- pass
150
+ pass # pragma: no cover
151
151
 
152
152
  @abstractmethod
153
153
  def get_dataset_unique_structures(self) -> int:
154
- pass
154
+ pass # pragma: no cover
@@ -139,4 +139,4 @@ class ToleranceCalculator(ABC):
139
139
 
140
140
  @abstractmethod
141
141
  def calculate_tolerance(self) -> float:
142
- pass
142
+ pass # pragma: no cover, implemented in child classes
@@ -1,7 +1,7 @@
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):
@@ -23,10 +23,9 @@ class DistanceMatrix(DuplicateDetectionAlgorithm):
23
23
 
24
24
  def _ensure_distance_matrix(self):
25
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.")
26
+ warnings.warn("Distance matrix shape does not match dataset; recomputing.")
27
+ self.compute_distance_matrix(self.dataset_array)
28
+
30
29
 
31
30
  def duplicate_check(self) -> bool:
32
31
  return bool(
@@ -10,11 +10,17 @@ from numba import njit
10
10
 
11
11
  @njit
12
12
  def fast_round_and_perturb(input_vector, perturbation_array, tolerance):
13
- rounded_vector = np.round(input_vector / tolerance) * tolerance
14
- round_and_perturb_array = np.zeros((perturbation_array.shape[0], len(input_vector)))
15
- for i in range(perturbation_array.shape[0]):
16
- round_and_perturb_array[i] = rounded_vector * perturbation_array[i]
17
- return round_and_perturb_array
13
+ n_pert = perturbation_array.shape[0] # pragma: no cover
14
+ n_feat = input_vector.shape[0] # pragma: no cover
15
+ out = np.empty((n_pert, n_feat), dtype=input_vector.dtype) # pragma: no cover
16
+
17
+ for i in range(n_pert): # pragma: no cover
18
+ p = perturbation_array[i] # pragma: no cover
19
+ for j in range(n_feat): # pragma: no cover
20
+ v = p * input_vector[j]# pragma: no cover
21
+ out[i, j] = np.round(v / tolerance) * tolerance # pragma: no cover
22
+
23
+ return out # pragma: no cover
18
24
 
19
25
  @register_plugin(kind="duplicate_detection_algorithm", name="multi_hashing")
20
26
  class MultiHashing(DuplicateDetectionAlgorithm):
@@ -28,8 +34,8 @@ class MultiHashing(DuplicateDetectionAlgorithm):
28
34
  perturbations: int = 200,
29
35
  seed: int = 803,
30
36
  pertrubation_array: np.ndarray = np.array([]),
31
- acceptance_threshold: float = 0.5,
32
37
  distance_metric: str = "hamming",
38
+ sigma_accepatnce_threshold: int = 1,
33
39
  distance_matrix: np.ndarray = np.array([]),
34
40
  hash_vector_array: np.ndarray = np.array([]),
35
41
  unique_vector_indices: np.ndarray = np.array([]),
@@ -43,13 +49,15 @@ class MultiHashing(DuplicateDetectionAlgorithm):
43
49
  unique_vector_indices=unique_vector_indices,
44
50
  )
45
51
  self.seed = seed
46
- self.acceptance_threshold = acceptance_threshold
52
+ self.sigma_accepatnce_threshold = sigma_accepatnce_threshold
47
53
  self.perturbations = perturbations
48
54
  self.hash_vector_array = hash_vector_array
49
55
  self.perturbation_array = pertrubation_array
50
56
 
57
+ self.set_acceptance_threshold()
58
+
51
59
  def __str__(self) -> str:
52
- return f"MultiHashing(tolerance={self.tolerance}, perturbations={self.perturbations}, acceptance_threshold={self.acceptance_threshold})"
60
+ return f"MultiHashing(tolerance={self.tolerance}, perturbations={self.perturbations}, sigma_acceptance_threshold={self.sigma_accepatnce_threshold})"
53
61
 
54
62
  def set_perturbation_array(self) -> None:
55
63
  rng = np.random.default_rng(self.seed)
@@ -65,13 +73,29 @@ class MultiHashing(DuplicateDetectionAlgorithm):
65
73
  )
66
74
  self.set_perturbation_array()
67
75
 
76
+ def set_acceptance_threshold(self) -> None:
77
+ if self.sigma_accepatnce_threshold < 1 or self.sigma_accepatnce_threshold > 4 or not isinstance(self.sigma_accepatnce_threshold, int):
78
+ raise ValueError("Sigma acceptance threshold must be an integer between 1 and 4 inclusive.")
79
+ sigma_dict = {
80
+ 1: 0.682689492137086,
81
+ 2: 0.954499736103642,
82
+ 3: 0.997300203936740,
83
+ 4: 0.999936657516333,
84
+ }
85
+ if 1/(1-sigma_dict[self.sigma_accepatnce_threshold]) > self.perturbations and self.sigma_accepatnce_threshold > 1:
86
+ warnings.warn(f"Sigma acceptance threshold of {self.sigma_accepatnce_threshold} corresponds to an acceptance threshold of {sigma_dict[self.sigma_accepatnce_threshold]} which may be too high for the number of perturbations ({self.perturbations}) and could lead to false positives. Consider lowering the sigma acceptance threshold or increasing the number of perturbations to over {int(np.ceil(1/(1-sigma_dict[self.sigma_accepatnce_threshold])))}.")
87
+
88
+ self.acceptance_threshold = sigma_dict[self.sigma_accepatnce_threshold]
89
+
68
90
  def round_to_tolerance(self) -> np.ndarray:
69
91
  rounded_vector = np.round(self.input_vector / self.tolerance) * self.tolerance
70
92
  return rounded_vector
71
93
 
72
- def create_hash_vector(self) -> np.ndarray:
94
+ def create_hash_vector(self, input_vector: np.ndarray | None = None) -> np.ndarray:
95
+ if input_vector is None:
96
+ input_vector = self.input_vector
73
97
  self._ensure_perturbation_array()
74
- rounded_and_perturbed = fast_round_and_perturb(self.input_vector, self.perturbation_array, self.tolerance)
98
+ rounded_and_perturbed = fast_round_and_perturb(input_vector, self.perturbation_array, self.tolerance)
75
99
  hash_vector = np.zeros(self.perturbations, dtype=int)
76
100
  for i in range(self.perturbations):
77
101
  hash_vector[i] = hash(rounded_and_perturbed[i].tobytes())
@@ -88,8 +112,7 @@ class MultiHashing(DuplicateDetectionAlgorithm):
88
112
  )
89
113
  self._ensure_perturbation_array()
90
114
  for i in range(self.dataset_array.shape[0]):
91
- self.input_vector = self.dataset_array[i]
92
- hash_vector = self.create_hash_vector()
115
+ hash_vector = self.create_hash_vector(self.dataset_array[i])
93
116
  for j in range(self.perturbations):
94
117
  if hash_vector[j] not in self.hash_vector_array[:, j]:
95
118
  self.hash_vector_array[i, j] = hash_vector[j]
@@ -120,6 +143,17 @@ class MultiHashing(DuplicateDetectionAlgorithm):
120
143
  duplicate_structure = duplicate_vote_array >= self.acceptance_threshold
121
144
 
122
145
  return bool(duplicate_structure)
146
+
147
+ def get_uniqueness_score(self) -> float:
148
+ self._ensure_hash_vector_array()
149
+ hash_vector = self.create_hash_vector()
150
+ clash_vector = np.zeros(self.perturbations, dtype=bool)
151
+ for hash_index, hash_value in enumerate(hash_vector):
152
+ if hash_value in self.hash_vector_array[:, hash_index]:
153
+ clash_vector[hash_index] = True
154
+ uniqueness_score = 1 - np.sum(clash_vector) / self.perturbations
155
+
156
+ return uniqueness_score
123
157
 
124
158
  def get_dataset_unique_structures(self) -> int:
125
159
  """Counts the number of unique structures in the dataset by checking for hash value clashes across the dataset for each perturbation.
@@ -5,8 +5,6 @@ from deduplicate_lib.core.duplicate_detection_algorithm import (
5
5
  from deduplicate_lib.core.plugin_registry import register_plugin
6
6
  import numpy as np
7
7
  import warnings
8
-
9
-
10
8
  @register_plugin("tolerance_calculator", "natural_tolerance_plateau_probe")
11
9
  class NaturalTolerancePlateauProbe(ToleranceCalculator):
12
10
  def __init__(
@@ -18,6 +16,8 @@ class NaturalTolerancePlateauProbe(ToleranceCalculator):
18
16
  binary_search_steps: int = 50,
19
17
  probe_steps: int = 100,
20
18
  probe_buffer_fraction: float = 0.1,
19
+ datapoints_to_calculate_gradient: int = 3,
20
+ plateau_threshold: float = 1e-3,
21
21
  ) -> None:
22
22
  super().__init__(
23
23
  duplicate_detection_algorithm_object=duplicate_detection_algorithm_object,
@@ -28,12 +28,14 @@ class NaturalTolerancePlateauProbe(ToleranceCalculator):
28
28
  )
29
29
  self.probe_steps = probe_steps
30
30
  self.probe_buffer_fraction = probe_buffer_fraction
31
+ self.datapoints_to_calculate_gradient = datapoints_to_calculate_gradient
32
+ self.plateau_threshold = plateau_threshold
31
33
 
32
34
  def __str__(self) -> str:
33
35
  return f"NaturalTolerancePlateauProbe(perturbations_per_vector={self.perturbations_per_vector}, perturbation_scale={self.perturbation_scale}, dda={str(self.duplicate_detection_algorithm_object).split('(')[0]})"
34
36
 
35
37
  def tolerance_probe(
36
- self, lower_tolerance: float, upper_tolerance: float, tolerance_steps: float
38
+ self, lower_tolerance: float, upper_tolerance: float, tolerance_steps: int
37
39
  ) -> dict:
38
40
  tolerance_results = {}
39
41
  with self.temp_attr(
@@ -52,43 +54,49 @@ class NaturalTolerancePlateauProbe(ToleranceCalculator):
52
54
 
53
55
  def get_plateau_log(
54
56
  self,
57
+ sorted_tols: list,
55
58
  tolerance_results: dict,
56
- datapoints_to_calculate_gradient: int = 3,
57
- plateau_threshold: float = 1e-3,
58
- sorted_tols: list | None = None,
59
59
  ) -> np.ndarray:
60
- if sorted_tols is None:
61
- sorted_tols = sorted(tolerance_results.keys())
60
+
61
+ if self.datapoints_to_calculate_gradient <= 1:
62
+ raise ValueError("datapoints_to_calculate_gradient must be greater than 1.")
63
+
64
+ if len(sorted_tols) < self.datapoints_to_calculate_gradient:
65
+ raise ValueError("Not enough tolerance steps to calculate gradient with the given datapoints_to_calculate_gradient.")
62
66
 
63
67
  unique_counts = [tolerance_results[tol] for tol in sorted_tols]
64
-
65
- relative_plateau_threshold = plateau_threshold * max(
66
- unique_counts
67
- ) # Scale threshold based on the maximum number of unique structures
68
+ total_gradient = (unique_counts[-1] - unique_counts[0]) / (sorted_tols[-1] - sorted_tols[0])
69
+ relative_plateau_threshold = self.plateau_threshold * total_gradient
70
+
68
71
  # detect plateaus by calculating the gradient of unique_counts with respect to tolerance and finding where it is close to zero
69
- plateau_log = np.zeros(len(sorted_tols), dtype=bool)
70
- for i in range(len(unique_counts) - datapoints_to_calculate_gradient):
72
+ plateau_log = np.zeros(len(sorted_tols) - self.datapoints_to_calculate_gradient, dtype=bool)
73
+ gradient_log = np.zeros(len(sorted_tols) - self.datapoints_to_calculate_gradient)
74
+ for i in range(len(unique_counts) - self.datapoints_to_calculate_gradient):
71
75
  gradient = (
72
- unique_counts[i + datapoints_to_calculate_gradient] - unique_counts[i]
73
- ) / (sorted_tols[i + datapoints_to_calculate_gradient] - sorted_tols[i])
76
+ unique_counts[i + self.datapoints_to_calculate_gradient] - unique_counts[i]
77
+ ) / (sorted_tols[i + self.datapoints_to_calculate_gradient] - sorted_tols[i])
78
+ gradient_log[i] = gradient
74
79
  if (
75
- abs(gradient) < relative_plateau_threshold
80
+ abs(gradient) < abs(relative_plateau_threshold)
76
81
  ): # Threshold for plateau detection
77
82
  plateau_log[i] = True
83
+
84
+ # store the plateau data for potential plotting and analysis
85
+ self.plateau_data = {'tolerances': [sorted_tols[:-self.datapoints_to_calculate_gradient]],
86
+ 'unique_counts': [unique_counts[:-self.datapoints_to_calculate_gradient]],
87
+ 'gradients': list(gradient_log)}
88
+
78
89
  return plateau_log
79
90
 
91
+
80
92
  def find_plateaus(
81
93
  self,
82
94
  tolerance_results: dict,
83
- datapoints_to_calculate_gradient: int = 3,
84
- plateau_threshold: float = 1e-3,
85
- ) -> tuple:
95
+ ) -> list:
86
96
  sorted_tols = sorted(tolerance_results.keys())
87
97
  plateau_log = self.get_plateau_log(
88
- tolerance_results,
89
- datapoints_to_calculate_gradient,
90
- plateau_threshold,
91
98
  sorted_tols,
99
+ tolerance_results,
92
100
  )
93
101
 
94
102
  plateau_lengths = []
@@ -109,7 +117,7 @@ class NaturalTolerancePlateauProbe(ToleranceCalculator):
109
117
  self._ensure_perturbed_dataset()
110
118
  all_same_tolerance = self.binary_search_tolerance(
111
119
  target_unique_vectors=int(
112
- np.floor(self.probe_buffer_fraction * len(self.tolerance_dataset_array))
120
+ np.max([1, np.floor(self.probe_buffer_fraction * len(self.tolerance_dataset_array))])
113
121
  ),
114
122
  find_largest_tolerance_for_target=False,
115
123
  )
@@ -0,0 +1,79 @@
1
+ from deduplicate_lib.core.tolerance_calculator import ToleranceCalculator
2
+ from deduplicate_lib.core.duplicate_detection_algorithm import DuplicateDetectionAlgorithm
3
+ from deduplicate_lib.core.plugin_registry import register_plugin
4
+ import numpy as np
5
+
6
+
7
+ @register_plugin("tolerance_calculator", "perturbed_dataset_reclustering")
8
+ class PerturbedDatasetReclustering(ToleranceCalculator):
9
+ """A tolerance calculator that creates a perturbed dataset from the original dataset, then uses the duplicate detection algorithm to find the tolerance that yields the same number of unique structures in the perturbed dataset as in the target. The tolerance can be calculated as 'loose' (the highest tolerance that yields the target number of unique structures), 'tight' (the lowest tolerance that yields the target number of unique structures), or 'average' (the average of the highest and lowest tolerances that yield the target number of unique structures).
10
+
11
+ Args:
12
+ duplicate_detection_algorithm_object (DuplicateDetectionAlgorithm): The duplicate detection algorithm object to use for calculating the tolerance.
13
+ tolerance_dataset_array (np.ndarray, optional): The dataset array to use for calculating the tolerance. If not provided, the dataset array from the duplicate detection algorithm object will be used. Defaults to np.array([]).
14
+ perturbations_per_vector (int, optional): The number of perturbations to create for each vector in the dataset array. Defaults to 1.
15
+ perturbation_scale (float, optional): The scale of the perturbations to create. Defaults to 0.1.
16
+ binary_search_steps (int, optional): The number of steps to use for the binary search to find the tolerance. Defaults to 20.
17
+ target_structures (int | None, optional): The target number of unique structures to find the tolerance for. If None, the target will be the number of unique structures in the original dataset array. Defaults to None.
18
+ target_structures_threshold (str, optional): The method to use for calculating the tolerance threshold. Can be 'average', 'loose', or 'tight'. Defaults to 'average'.
19
+
20
+ Functions:
21
+ calculate_tolerance: Calculate the tolerance value based on the perturbed dataset and the target number of unique structures.
22
+
23
+ Returns:
24
+ float: The calculated tolerance value.
25
+ """
26
+ def __init__(self,
27
+ duplicate_detection_algorithm_object: DuplicateDetectionAlgorithm,
28
+ tolerance_dataset_array: np.ndarray = np.array([]),
29
+ perturbations_per_vector: int = 1,
30
+ perturbation_scale: float = 0.1,
31
+ binary_search_steps: int = 20,
32
+ target_structures: int | None = None,
33
+ target_structures_threshold: str = "average"
34
+ ):
35
+
36
+ super().__init__(
37
+ duplicate_detection_algorithm_object=duplicate_detection_algorithm_object,
38
+ tolerance_dataset_array=tolerance_dataset_array,
39
+ perturbations_per_vector=perturbations_per_vector,
40
+ perturbation_scale=perturbation_scale,
41
+ binary_search_steps=binary_search_steps,
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
47
+ def __str__(self) -> str:
48
+ 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
+
50
+ def calculate_tolerance(self) -> float:
51
+ """Find the highest and lowest values of tolerance that yield the length of the original dataset from the perturbed dataset, then returns the average of those two values.
52
+
53
+ Returns:
54
+ float: The calculated tolerance value.
55
+ """
56
+ self._ensure_perturbed_dataset()
57
+ if self.target_structures_threshold == "average":
58
+ low_tolerance = self.binary_search_tolerance(
59
+ target_unique_vectors=self.target_structures,
60
+ find_largest_tolerance_for_target=False,
61
+ )
62
+ high_tolerance = self.binary_search_tolerance(
63
+ target_unique_vectors=self.target_structures,
64
+ find_largest_tolerance_for_target=True,
65
+ )
66
+ return (low_tolerance + high_tolerance) / 2
67
+
68
+ elif self.target_structures_threshold == "loose":
69
+ return self.binary_search_tolerance(
70
+ target_unique_vectors=self.target_structures,
71
+ find_largest_tolerance_for_target=True,
72
+ )
73
+ elif self.target_structures_threshold == "tight":
74
+ return self.binary_search_tolerance(
75
+ target_unique_vectors=self.target_structures,
76
+ find_largest_tolerance_for_target=False,
77
+ )
78
+ else:
79
+ raise ValueError(f"Invalid target_structures_threshold: {self.target_structures_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.2
3
+ Version: 0.0.3
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_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
 
@@ -7,3 +7,8 @@ pytest
7
7
  pytest-mock
8
8
  coverage
9
9
  ruff
10
+ nbconvert
11
+ nbclient
12
+ notebook
13
+ ipykernel
14
+ matplotlib
@@ -1 +0,0 @@
1
- __version__ = "0.0.2"
@@ -1,46 +0,0 @@
1
- from deduplicate_lib.core.tolerance_calculator import ToleranceCalculator
2
- from deduplicate_lib.core.duplicate_detection_algorithm import DuplicateDetectionAlgorithm
3
- from deduplicate_lib.core.plugin_registry import register_plugin
4
- import numpy as np
5
-
6
-
7
- @register_plugin("tolerance_calculator", "perturbed_dataset_reclustering")
8
- class PerturbedDatasetReclustering(ToleranceCalculator):
9
- def __init__(self,
10
- duplicate_detection_algorithm_object: DuplicateDetectionAlgorithm,
11
- tolerance_dataset_array: np.ndarray = np.array([]),
12
- perturbations_per_vector: int = 1,
13
- perturbation_scale: float = 0.1,
14
- binary_search_steps: int = 20,
15
- target_structures: int | None = None,):
16
- super().__init__(
17
- duplicate_detection_algorithm_object=duplicate_detection_algorithm_object,
18
- tolerance_dataset_array=tolerance_dataset_array,
19
- perturbations_per_vector=perturbations_per_vector,
20
- perturbation_scale=perturbation_scale,
21
- binary_search_steps=binary_search_steps,
22
- )
23
- if target_structures is None:
24
- target_structures = len(duplicate_detection_algorithm_object.dataset_array)
25
- self.target_structures = target_structures
26
-
27
- def __str__(self) -> str:
28
- return f"PerturbedDatasetReclustering(perturbations_per_vector={self.perturbations_per_vector}, perturbation_scale={self.perturbation_scale}, dda={str(self.duplicate_detection_algorithm_object).split('(')[0]})"
29
-
30
- def calculate_tolerance(self) -> float:
31
- """Find the highest and lowest values of tolerance that yield the length of the original dataset from the perturbed dataset, then returns the average of those two values.
32
-
33
- Returns:
34
- float: The calculated tolerance value.
35
- """
36
- self._ensure_perturbed_dataset()
37
-
38
- low_tolerance = self.binary_search_tolerance(
39
- target_unique_vectors=self.target_structures,
40
- find_largest_tolerance_for_target=False,
41
- )
42
- high_tolerance = self.binary_search_tolerance(
43
- target_unique_vectors=self.target_structures,
44
- find_largest_tolerance_for_target=True,
45
- )
46
- return (low_tolerance + high_tolerance) / 2
File without changes