deduplicate-lib 0.1.0__tar.gz → 0.1.2__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.1.0/src/deduplicate_lib.egg-info → deduplicate_lib-0.1.2}/PKG-INFO +19 -11
  2. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/README.md +14 -10
  3. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/pyproject.toml +24 -13
  4. deduplicate_lib-0.1.2/src/deduplicate_lib/__init__.py +1 -0
  5. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/core/duplicate_detection_algorithm.py +66 -2
  6. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/core/tolerance_calculator.py +7 -0
  7. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/distance_matrix.py +28 -0
  8. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/multi_hashing.py +51 -0
  9. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/plugins/tolerance_calculators/natural_tolerance_plateau_probe.py +68 -5
  10. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/plugins/tolerance_calculators/perturbed_dataset_reclustering.py +25 -14
  11. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2/src/deduplicate_lib.egg-info}/PKG-INFO +19 -11
  12. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib.egg-info/requires.txt +5 -0
  13. deduplicate_lib-0.1.0/src/deduplicate_lib/__init__.py +0 -1
  14. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/LICENSE +0 -0
  15. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/setup.cfg +0 -0
  16. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/core/__init__.py +0 -0
  17. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/core/plugin_registry.py +0 -0
  18. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/plugins/__init__.py +0 -0
  19. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/plugins/duplicate_detection_algorithms/__init__.py +0 -0
  20. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib/plugins/tolerance_calculators/__init__.py +0 -0
  21. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib.egg-info/SOURCES.txt +0 -0
  22. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/src/deduplicate_lib.egg-info/dependency_links.txt +0 -0
  23. {deduplicate_lib-0.1.0 → deduplicate_lib-0.1.2}/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.1.0
3
+ Version: 0.1.2
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
@@ -19,6 +19,10 @@ Requires-Dist: nbclient; extra == "dev"
19
19
  Requires-Dist: notebook; extra == "dev"
20
20
  Requires-Dist: ipykernel; extra == "dev"
21
21
  Requires-Dist: matplotlib; extra == "dev"
22
+ Provides-Extra: docs
23
+ Requires-Dist: sphinx>=7; extra == "docs"
24
+ Requires-Dist: furo; extra == "docs"
25
+ Requires-Dist: sphinx-autodoc-typehints; extra == "docs"
22
26
  Dynamic: license-file
23
27
 
24
28
  <div align="center">
@@ -34,7 +38,7 @@ Dynamic: license-file
34
38
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
35
39
  [![CI](https://github.com/julianholland/deduplicate/actions/workflows/ci.yml/badge.svg)](https://github.com/julianholland/deduplicate/actions/workflows/ci.yml)
36
40
  [![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) -->
41
+ [![Documentation Status](https://readthedocs.org/projects/deduplicate-lib/badge/?version=latest)](https://deduplicate-lib.readthedocs.io/en/latest/)
38
42
 
39
43
  ## Key Features
40
44
 
@@ -52,24 +56,27 @@ Dynamic: license-file
52
56
  <!-- - Locality Sensitive Hashing (Fast, Accurate) -->
53
57
 
54
58
  ## Quick Start
55
- install using pip
59
+
56
60
  ```bash
57
61
  pip install deduplicate_lib
58
62
  ```
59
63
 
60
- load your data into python
61
-
62
64
  ```python
63
- from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
65
+ from deduplicate_lib.plugins.duplicate_detection_algorithms.multi_hashing import MultiHashing
66
+ import numpy as np
64
67
 
65
- # define your paramerters in the MultiHash object
66
- dda=MultiHash(dataset_array=your_data_numpy_array)
68
+ dataset = np.array([[1.0, 2.0], [1.01, 2.01], [5.0, 6.0]])
69
+ dda = MultiHashing(tolerance=0.1, dataset_array=dataset)
67
70
 
68
- # return a list of all unique values
71
+ # return unique vectors
69
72
  print(dda.deduplicate())
73
+
74
+ # check a single vector against the dataset
75
+ dda.input_vector = np.array([1.0, 2.0])
76
+ print(dda.duplicate_check()) # True
70
77
  ```
71
78
 
72
- A more detailed example can be seen in the `examples` directory
79
+ See the **[full documentation](https://deduplicate-lib.readthedocs.io)** for API reference, tolerance tuning, and more examples.
73
80
 
74
81
  ### Dependencies
75
82
 
@@ -144,6 +151,7 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
144
151
  ## Project Links
145
152
 
146
153
  - [GitHub Repository](https://github.com/julianholland/deduplicate)
154
+ - [Documentation](https://deduplicate-lib.readthedocs.io)
147
155
 
148
156
  ## Project To-Do
149
157
 
@@ -152,6 +160,6 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
152
160
  - [ ] Add benchmarks for time and robustness
153
161
  - [ ] Add Locality-Sensitive Hashing as an option
154
162
  - [x] Speedup slow tasks with Numba
155
- - [ ] Set up Read the Docs
163
+ - [x] Set up Read the Docs
156
164
  - [x] Create general deduplicate function
157
165
  - [x] Speed up NTPP
@@ -11,7 +11,7 @@
11
11
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
12
12
  [![CI](https://github.com/julianholland/deduplicate/actions/workflows/ci.yml/badge.svg)](https://github.com/julianholland/deduplicate/actions/workflows/ci.yml)
13
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) -->
14
+ [![Documentation Status](https://readthedocs.org/projects/deduplicate-lib/badge/?version=latest)](https://deduplicate-lib.readthedocs.io/en/latest/)
15
15
 
16
16
  ## Key Features
17
17
 
@@ -29,24 +29,27 @@
29
29
  <!-- - Locality Sensitive Hashing (Fast, Accurate) -->
30
30
 
31
31
  ## Quick Start
32
- install using pip
32
+
33
33
  ```bash
34
34
  pip install deduplicate_lib
35
35
  ```
36
36
 
37
- load your data into python
38
-
39
37
  ```python
40
- from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
38
+ from deduplicate_lib.plugins.duplicate_detection_algorithms.multi_hashing import MultiHashing
39
+ import numpy as np
41
40
 
42
- # define your paramerters in the MultiHash object
43
- dda=MultiHash(dataset_array=your_data_numpy_array)
41
+ dataset = np.array([[1.0, 2.0], [1.01, 2.01], [5.0, 6.0]])
42
+ dda = MultiHashing(tolerance=0.1, dataset_array=dataset)
44
43
 
45
- # return a list of all unique values
44
+ # return unique vectors
46
45
  print(dda.deduplicate())
46
+
47
+ # check a single vector against the dataset
48
+ dda.input_vector = np.array([1.0, 2.0])
49
+ print(dda.duplicate_check()) # True
47
50
  ```
48
51
 
49
- A more detailed example can be seen in the `examples` directory
52
+ See the **[full documentation](https://deduplicate-lib.readthedocs.io)** for API reference, tolerance tuning, and more examples.
50
53
 
51
54
  ### Dependencies
52
55
 
@@ -121,6 +124,7 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
121
124
  ## Project Links
122
125
 
123
126
  - [GitHub Repository](https://github.com/julianholland/deduplicate)
127
+ - [Documentation](https://deduplicate-lib.readthedocs.io)
124
128
 
125
129
  ## Project To-Do
126
130
 
@@ -129,6 +133,6 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
129
133
  - [ ] Add benchmarks for time and robustness
130
134
  - [ ] Add Locality-Sensitive Hashing as an option
131
135
  - [x] Speedup slow tasks with Numba
132
- - [ ] Set up Read the Docs
136
+ - [x] Set up Read the Docs
133
137
  - [x] Create general deduplicate function
134
138
  - [x] Speed up NTPP
@@ -3,7 +3,7 @@ name = "deduplicate_lib"
3
3
  dynamic = ["version"]
4
4
  description = "A Python package for deduplicating data."
5
5
  authors = [
6
- { name="Julian Holland", email="holland@fhi.mpg.de" }
6
+ { name = "Julian Holland", email = "holland@fhi.mpg.de" },
7
7
  ]
8
8
  readme = "README.md"
9
9
  requires-python = ">=3.8"
@@ -13,23 +13,34 @@ dependencies = [
13
13
  "scipy",
14
14
  ]
15
15
 
16
- [tool.setuptools]
17
- package-dir = {"" = "src"}
18
-
19
- [tool.setuptools.dynamic]
20
- version = {attr = "deduplicate_lib.__version__"}
21
-
22
16
  [project.optional-dependencies]
23
17
  dev = [
24
- "pytest",
25
- "pytest-mock",
26
- "coverage",
27
- "ruff",
28
- "nbconvert",
18
+ "pytest",
19
+ "pytest-mock",
20
+ "coverage",
21
+ "ruff",
22
+ "nbconvert",
29
23
  "nbclient",
30
24
  "notebook",
31
25
  "ipykernel",
32
- "matplotlib",]
26
+ "matplotlib",
27
+ ]
28
+ docs = [
29
+ "sphinx>=7",
30
+ "furo",
31
+ "sphinx-autodoc-typehints",
32
+ ]
33
+
34
+ [tool.setuptools]
35
+ package-dir = {"" = "src"}
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["src"]
39
+ include = ["deduplicate_lib*"]
40
+ namespaces = false
41
+
42
+ [tool.setuptools.dynamic]
43
+ version = { attr = "deduplicate_lib.__version__" }
33
44
 
34
45
  [tool.pytest.ini_options]
35
46
  testpaths = ["tests"]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.2"
@@ -61,6 +61,43 @@ DISTANCE_FUNCTIONS = {
61
61
 
62
62
 
63
63
  class DuplicateDetectionAlgorithm(ABC):
64
+ """Abstract base class for deduplication algorithms operating on numpy vector arrays.
65
+
66
+ Subclasses implement ``duplicate_check()`` and ``get_dataset_unique_structures()``
67
+ using algorithm-specific auxiliary structures (e.g. a distance matrix or hash
68
+ dictionary). The public interface is:
69
+
70
+ * ``tolerance`` — distance threshold below which two vectors are considered duplicates.
71
+ * ``input_vector`` — the single vector to check or append.
72
+ * ``dataset_array`` — read-only view of the currently loaded vectors.
73
+ * ``vector_count`` — number of vectors currently in the dataset.
74
+
75
+ ``_dataset_array`` and ``distance_matrix`` are pre-allocated to
76
+ ``max_vector_array_size`` rows to avoid repeated reallocation. Load data via
77
+ ``set_dataset_array()``; never assign to ``dataset_array`` directly.
78
+
79
+ Parameters
80
+ ----------
81
+ tolerance : float
82
+ Distance threshold for duplicate detection.
83
+ input_vector : np.ndarray, optional
84
+ Single vector to check against the dataset.
85
+ dataset_array : np.ndarray, optional
86
+ Initial dataset of vectors (rows). Copied into the pre-allocated backing
87
+ array.
88
+ distance_matrix : np.ndarray, optional
89
+ Pre-computed distance matrix. If empty, it is allocated on first use.
90
+ distance_metric : str, optional
91
+ One of ``"euclidean"``, ``"manhattan"``, ``"cosine"``, ``"hamming"``.
92
+ Defaults to ``"euclidean"``.
93
+ unique_vector_indices : np.ndarray, optional
94
+ Boolean array marking unique vectors. Updated by
95
+ ``get_dataset_unique_structures()``.
96
+ max_vector_array_size : int, optional
97
+ Maximum number of vectors the pre-allocated arrays can hold.
98
+ Defaults to 10000.
99
+ """
100
+
64
101
  ALLOWED_DISTANCES = DISTANCE_FUNCTIONS
65
102
 
66
103
  def __init__(
@@ -162,7 +199,13 @@ class DuplicateDetectionAlgorithm(ABC):
162
199
  pass
163
200
 
164
201
  def add_input_vector_to_dda(self) -> None:
165
- """Add the input vector to the dataset array and update any auxiliary structures accordingly."""
202
+ """Add ``self.input_vector`` to the dataset and incrementally update auxiliary structures.
203
+
204
+ ``self.input_vector`` must be set before calling. Auxiliary structures
205
+ (distance-matrix column or hash-dict entry) are updated incrementally
206
+ rather than rebuilt from scratch, making this efficient for streaming
207
+ ingestion.
208
+ """
166
209
  self.pre_dda_processing()
167
210
  self._append_vector_to_structures()
168
211
 
@@ -179,7 +222,18 @@ class DuplicateDetectionAlgorithm(ABC):
179
222
  return np.where(self.unique_vector_indices)[0]
180
223
 
181
224
  def deduplicate(self):
182
- """Finds all unique vectors in the dataset and returns them as a new array."""
225
+ """Return all unique vectors in the dataset as a new array.
226
+
227
+ Returns
228
+ -------
229
+ np.ndarray
230
+ 2-D array whose rows are the unique vectors.
231
+
232
+ Notes
233
+ -----
234
+ Calls ``get_dataset_unique_structures()`` (via ``pre_dda_processing``) to
235
+ ensure auxiliary structures are up to date before selecting unique rows.
236
+ """
183
237
  return self.dataset_array[self.get_unique_vector_indices()]
184
238
 
185
239
  def initialize_dataset_array(self, vector_length: int) -> None:
@@ -258,6 +312,16 @@ class DuplicateDetectionAlgorithm(ABC):
258
312
 
259
313
  @abstractmethod
260
314
  def duplicate_check(self) -> bool:
315
+ """Check whether ``self.input_vector`` is a duplicate of any vector in the dataset.
316
+
317
+ ``self.input_vector`` must be set before calling.
318
+
319
+ Returns
320
+ -------
321
+ bool
322
+ ``True`` if ``self.input_vector`` is within ``self.tolerance`` of any
323
+ existing dataset vector; ``False`` otherwise.
324
+ """
261
325
  pass # pragma: no cover
262
326
 
263
327
  @abstractmethod
@@ -146,4 +146,11 @@ class ToleranceCalculator(ABC):
146
146
 
147
147
  @abstractmethod
148
148
  def calculate_tolerance(self) -> float:
149
+ """Compute and return a tolerance value for the configured dataset and DDA.
150
+
151
+ Returns
152
+ -------
153
+ float
154
+ A tolerance value suitable for use as ``dda.tolerance``.
155
+ """
149
156
  pass # pragma: no cover, implemented in child classes
@@ -4,6 +4,34 @@ import numpy as np
4
4
 
5
5
  @register_plugin(kind="duplicate_detection_algorithm", name="distance_matrix")
6
6
  class DistanceMatrix(DuplicateDetectionAlgorithm):
7
+ """Exact deduplication using a full pairwise distance matrix.
8
+
9
+ Computes all N×N pairwise distances and flags any vector whose nearest
10
+ neighbour is within ``tolerance`` as a duplicate. O(N²) time and space;
11
+ suitable for small-to-medium datasets (up to ~5 000 vectors) where exact
12
+ results are required. Supports all four distance metrics: ``"euclidean"``,
13
+ ``"manhattan"``, ``"cosine"``, and ``"hamming"``.
14
+
15
+ Parameters
16
+ ----------
17
+ tolerance : float, optional
18
+ Distance threshold for duplicate detection. Defaults to ``0.1``.
19
+ input_vector : np.ndarray, optional
20
+ Single vector to check against the dataset.
21
+ dataset_array : np.ndarray, optional
22
+ Initial dataset of vectors (rows).
23
+ distance_matrix : np.ndarray, optional
24
+ Pre-computed distance matrix. Allocated automatically if empty.
25
+ distance_metric : str, optional
26
+ One of ``"euclidean"``, ``"manhattan"``, ``"cosine"``, ``"hamming"``.
27
+ Defaults to ``"euclidean"``.
28
+ unique_vector_indices : np.ndarray, optional
29
+ Boolean array marking unique vectors.
30
+ max_vector_array_size : int, optional
31
+ Maximum number of vectors the pre-allocated arrays can hold.
32
+ Defaults to 10000.
33
+ """
34
+
7
35
  def __init__(
8
36
  self,
9
37
  tolerance: float = 0.1,
@@ -24,6 +24,57 @@ def fast_round_and_perturb(input_vector, perturbation_array, tolerance):
24
24
 
25
25
  @register_plugin(kind="duplicate_detection_algorithm", name="multi_hashing")
26
26
  class MultiHashing(DuplicateDetectionAlgorithm):
27
+ """Approximate deduplication via random perturbation and hashing.
28
+
29
+ Each vector is smeared with ``perturbations`` random scale factors, rounded
30
+ to the nearest ``tolerance`` grid point, and hashed. A vector is declared a
31
+ duplicate if at least ``acceptance_threshold`` (derived from
32
+ ``sigma_accepatnce_threshold``) of its perturbation hashes collide with any
33
+ existing hash-dictionary entry. O(N · perturbations) time; significantly
34
+ faster than :class:`DistanceMatrix` for large datasets.
35
+
36
+ Only ``"hamming"`` distance is supported.
37
+
38
+ Parameters
39
+ ----------
40
+ tolerance : float, optional
41
+ Rounding grid size and distance threshold. Defaults to ``0.1``.
42
+ input_vector : np.ndarray, optional
43
+ Single vector to check against the dataset.
44
+ dataset_array : np.ndarray, optional
45
+ Initial dataset of vectors (rows).
46
+ perturbations : int, optional
47
+ Number of random perturbations per vector. More perturbations increase
48
+ accuracy at the cost of speed. Defaults to ``200``.
49
+ seed : int, optional
50
+ Random seed for generating the perturbation array. Defaults to ``803``.
51
+ pertrubation_array : np.ndarray, optional
52
+ Pre-computed perturbation scale factors. Generated from ``seed`` if
53
+ not provided or if its length does not match ``perturbations``.
54
+ distance_metric : str, optional
55
+ Must be ``"hamming"``.
56
+ sigma_accepatnce_threshold : int, optional
57
+ Controls the acceptance band (1–4):
58
+
59
+ ====== ================
60
+ Value Acceptance band
61
+ ====== ================
62
+ 1 68.3% (default)
63
+ 2 95.4%
64
+ 3 99.7%
65
+ 4 99.99%
66
+ ====== ================
67
+
68
+ Higher values reduce false positives but require more perturbations.
69
+ distance_matrix : np.ndarray, optional
70
+ Unused by this algorithm; kept for interface compatibility.
71
+ unique_vector_indices : np.ndarray, optional
72
+ Boolean array marking unique vectors.
73
+ max_vector_array_size : int, optional
74
+ Maximum number of vectors the pre-allocated arrays can hold.
75
+ Defaults to 10000.
76
+ """
77
+
27
78
  ALLOWED_DISTANCES = {"hamming": hamming_distance}
28
79
 
29
80
  def __init__(
@@ -7,6 +7,47 @@ import numpy as np
7
7
  import warnings
8
8
  @register_plugin("tolerance_calculator", "natural_tolerance_plateau_probe")
9
9
  class NaturalTolerancePlateauProbe(ToleranceCalculator):
10
+ """Tolerance calculator that finds a stable tolerance directly from the dataset.
11
+
12
+ No perturbed copies are required. The algorithm:
13
+
14
+ 1. Binary-searches for the "all same" tolerance (nearly all vectors
15
+ collapse to one cluster) and the "all different" tolerance (nearly every
16
+ vector is unique).
17
+ 2. Sweeps ``probe_steps`` evenly-spaced tolerance values between those bounds
18
+ and records the unique-structure count at each step.
19
+ 3. Identifies plateaus — regions where the gradient of unique counts with
20
+ respect to tolerance is below ``plateau_threshold`` — and returns the
21
+ midpoint of the longest plateau found.
22
+
23
+ Parameters
24
+ ----------
25
+ duplicate_detection_algorithm_object : DuplicateDetectionAlgorithm
26
+ The DDA used to count unique structures during the search.
27
+ tolerance_dataset_array : np.ndarray, optional
28
+ Dataset to probe. Defaults to the DDA's current dataset.
29
+ perturbations_per_vector : int, optional
30
+ Inherited from base class; not used by this calculator.
31
+ perturbation_scale : float, optional
32
+ Inherited from base class; not used by this calculator.
33
+ binary_search_steps : int, optional
34
+ Iterations for the all-same / all-different binary searches.
35
+ Defaults to ``50``.
36
+ probe_steps : int, optional
37
+ Number of evenly-spaced tolerance values to evaluate between the
38
+ all-same and all-different bounds. Defaults to ``100``.
39
+ probe_buffer_fraction : float, optional
40
+ Fraction of dataset size used as a margin when defining the all-same
41
+ and all-different bounds (avoids exact extremes). Defaults to ``0.1``.
42
+ datapoints_to_calculate_gradient : int, optional
43
+ Window size (in probe steps) for computing the local gradient.
44
+ Must be greater than 1. Defaults to ``3``.
45
+ plateau_threshold : float, optional
46
+ Gradient magnitude below which a region is considered a plateau,
47
+ expressed as a fraction of the total gradient across the sweep.
48
+ Defaults to ``1e-3``.
49
+ """
50
+
10
51
  def __init__(
11
52
  self,
12
53
  duplicate_detection_algorithm_object: DuplicateDetectionAlgorithm,
@@ -69,7 +110,6 @@ class NaturalTolerancePlateauProbe(ToleranceCalculator):
69
110
  unique_counts = [tolerance_results[tol] for tol in sorted_tols]
70
111
  total_gradient = (unique_counts[-1] - unique_counts[0]) / (sorted_tols[-1] - sorted_tols[0])
71
112
  relative_plateau_threshold = self.plateau_threshold * total_gradient
72
-
73
113
  # detect plateaus by calculating the gradient of unique_counts with respect to tolerance and finding where it is close to zero
74
114
  plateau_log = np.zeros(len(sorted_tols) - self.datapoints_to_calculate_gradient, dtype=bool)
75
115
  gradient_log = np.zeros(len(sorted_tols) - self.datapoints_to_calculate_gradient)
@@ -90,7 +130,6 @@ class NaturalTolerancePlateauProbe(ToleranceCalculator):
90
130
 
91
131
  return plateau_log
92
132
 
93
-
94
133
  def find_plateaus(
95
134
  self,
96
135
  tolerance_results: dict,
@@ -140,7 +179,19 @@ class NaturalTolerancePlateauProbe(ToleranceCalculator):
140
179
 
141
180
  return plateau_lengths
142
181
 
143
- def calculate_tolerance(self) -> float:
182
+ def calculate_tolerance(self, condition: str = "longest") -> float:
183
+ """Compute and return the midpoint of the longest plateau in the unique-count curve.
184
+
185
+ Parameters
186
+ ----------
187
+ condition : str, optional
188
+ Condition for selecting the plateau. Currently only supports "longest".
189
+ Returns
190
+ -------
191
+ float
192
+ Midpoint of the longest detected plateau. Falls back to the average
193
+ of the all-same and all-different tolerances if no plateau is found.
194
+ """
144
195
  self._ensure_perturbed_dataset()
145
196
  all_same_tolerance = self.binary_search_tolerance(
146
197
  target_unique_vectors=int(
@@ -164,5 +215,17 @@ class NaturalTolerancePlateauProbe(ToleranceCalculator):
164
215
  )
165
216
  return (all_same_tolerance + all_different_tolerance) / 2
166
217
  else:
167
- longest_plateau = max(plateaus, key=lambda x: x[2])
168
- return (longest_plateau[0] + longest_plateau[1]) / 2
218
+ if condition not in ["longest", "minimum", "maximum"]:
219
+ raise ValueError(
220
+ f"Invalid condition '{condition}'. Must be one of 'longest', 'minimum', or 'maximum'."
221
+ )
222
+ if condition == "minimum":
223
+ chosen_plateau = min(plateaus, key=lambda x: x[0])
224
+ tolerance = chosen_plateau[0]
225
+ elif condition == "maximum":
226
+ chosen_plateau = max(plateaus, key=lambda x: x[0])
227
+ tolerance = chosen_plateau[1]
228
+ else: # condition == "longest"
229
+ chosen_plateau = max(plateaus, key=lambda x: x[2])
230
+ tolerance = (chosen_plateau[0] + chosen_plateau[1]) / 2
231
+ return tolerance
@@ -6,22 +6,33 @@ import numpy as np
6
6
 
7
7
  @register_plugin("tolerance_calculator", "perturbed_dataset_reclustering")
8
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).
9
+ """Tolerance calculator based on perturbed-dataset reclustering.
10
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'.
11
+ Creates ``perturbations_per_vector`` noisy copies of each original vector,
12
+ then binary-searches for the tolerance that recovers the original unique-vector
13
+ count in the perturbed dataset. The returned value depends on
14
+ ``target_unique_vectors_threshold``: ``"loose"`` returns the highest valid
15
+ tolerance, ``"tight"`` the lowest, and ``"average"`` their mean.
19
16
 
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.
17
+ Parameters
18
+ ----------
19
+ duplicate_detection_algorithm_object : DuplicateDetectionAlgorithm
20
+ The DDA used to count unique structures during the search.
21
+ tolerance_dataset_array : np.ndarray, optional
22
+ Dataset to search over. Defaults to the DDA's current dataset.
23
+ perturbations_per_vector : int, optional
24
+ Number of perturbed copies per original vector. Defaults to ``1``
25
+ (no perturbation; pass the original vectors directly).
26
+ perturbation_scale : float, optional
27
+ Standard deviation of the Gaussian noise added per perturbation.
28
+ Defaults to ``0.1``.
29
+ binary_search_steps : int, optional
30
+ Number of binary-search iterations. Defaults to ``20``.
31
+ target_unique_vectors : int or None, optional
32
+ Target unique-vector count. ``None`` uses the current dataset size.
33
+ target_unique_vectors_threshold : str, optional
34
+ One of ``"average"``, ``"loose"``, or ``"tight"``. Defaults to
35
+ ``"average"``.
25
36
  """
26
37
  def __init__(self,
27
38
  duplicate_detection_algorithm_object: DuplicateDetectionAlgorithm,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deduplicate_lib
3
- Version: 0.1.0
3
+ Version: 0.1.2
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
@@ -19,6 +19,10 @@ Requires-Dist: nbclient; extra == "dev"
19
19
  Requires-Dist: notebook; extra == "dev"
20
20
  Requires-Dist: ipykernel; extra == "dev"
21
21
  Requires-Dist: matplotlib; extra == "dev"
22
+ Provides-Extra: docs
23
+ Requires-Dist: sphinx>=7; extra == "docs"
24
+ Requires-Dist: furo; extra == "docs"
25
+ Requires-Dist: sphinx-autodoc-typehints; extra == "docs"
22
26
  Dynamic: license-file
23
27
 
24
28
  <div align="center">
@@ -34,7 +38,7 @@ Dynamic: license-file
34
38
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
35
39
  [![CI](https://github.com/julianholland/deduplicate/actions/workflows/ci.yml/badge.svg)](https://github.com/julianholland/deduplicate/actions/workflows/ci.yml)
36
40
  [![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) -->
41
+ [![Documentation Status](https://readthedocs.org/projects/deduplicate-lib/badge/?version=latest)](https://deduplicate-lib.readthedocs.io/en/latest/)
38
42
 
39
43
  ## Key Features
40
44
 
@@ -52,24 +56,27 @@ Dynamic: license-file
52
56
  <!-- - Locality Sensitive Hashing (Fast, Accurate) -->
53
57
 
54
58
  ## Quick Start
55
- install using pip
59
+
56
60
  ```bash
57
61
  pip install deduplicate_lib
58
62
  ```
59
63
 
60
- load your data into python
61
-
62
64
  ```python
63
- from deduplicate_lib.plugins.deduplication_algorithms.multi_hash import MultiHash
65
+ from deduplicate_lib.plugins.duplicate_detection_algorithms.multi_hashing import MultiHashing
66
+ import numpy as np
64
67
 
65
- # define your paramerters in the MultiHash object
66
- dda=MultiHash(dataset_array=your_data_numpy_array)
68
+ dataset = np.array([[1.0, 2.0], [1.01, 2.01], [5.0, 6.0]])
69
+ dda = MultiHashing(tolerance=0.1, dataset_array=dataset)
67
70
 
68
- # return a list of all unique values
71
+ # return unique vectors
69
72
  print(dda.deduplicate())
73
+
74
+ # check a single vector against the dataset
75
+ dda.input_vector = np.array([1.0, 2.0])
76
+ print(dda.duplicate_check()) # True
70
77
  ```
71
78
 
72
- A more detailed example can be seen in the `examples` directory
79
+ See the **[full documentation](https://deduplicate-lib.readthedocs.io)** for API reference, tolerance tuning, and more examples.
73
80
 
74
81
  ### Dependencies
75
82
 
@@ -144,6 +151,7 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
144
151
  ## Project Links
145
152
 
146
153
  - [GitHub Repository](https://github.com/julianholland/deduplicate)
154
+ - [Documentation](https://deduplicate-lib.readthedocs.io)
147
155
 
148
156
  ## Project To-Do
149
157
 
@@ -152,6 +160,6 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
152
160
  - [ ] Add benchmarks for time and robustness
153
161
  - [ ] Add Locality-Sensitive Hashing as an option
154
162
  - [x] Speedup slow tasks with Numba
155
- - [ ] Set up Read the Docs
163
+ - [x] Set up Read the Docs
156
164
  - [x] Create general deduplicate function
157
165
  - [x] Speed up NTPP
@@ -12,3 +12,8 @@ nbclient
12
12
  notebook
13
13
  ipykernel
14
14
  matplotlib
15
+
16
+ [docs]
17
+ sphinx>=7
18
+ furo
19
+ sphinx-autodoc-typehints
@@ -1 +0,0 @@
1
- __version__ = "0.1.0"
File without changes