benchmake 1.0.0__py3-none-any.whl

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.

Potentially problematic release.


This version of benchmake might be problematic. Click here for more details.

BenchMake.py ADDED
@@ -0,0 +1,423 @@
1
+ #BenchMake
2
+ #(c) 2025, Prof Dr Amanda S Barnard PhD DSc
3
+ # Version 1.0, 06/02/2025
4
+
5
+ import os
6
+ import math
7
+ import numpy as np
8
+ import pandas as pd
9
+ from joblib import Parallel, delayed
10
+ from sklearn.feature_extraction.text import CountVectorizer
11
+ import hashlib
12
+
13
+ # Attempt to import CuPy for GPU computations and check GPU compatibility
14
+ try:
15
+ import cupy as cp
16
+ # Check if at least one CUDA-capable device is available
17
+ if cp.cuda.runtime.getDeviceCount() > 0:
18
+ try:
19
+ from cupy.cuda import Device
20
+ device = Device(0) # Use the first device
21
+ _ = device.compute_capability # Verify compatibility
22
+ gpu_available = True
23
+ cp.random.seed(42)
24
+ print("GPU is available. Using CuPy for GPU computations.")
25
+ except cp.cuda.runtime.CUDARuntimeError as e:
26
+ cp = None
27
+ gpu_available = False
28
+ print(f"Warning: CuPy is installed but the GPU is not compatible: {e}. Reverting to CPU.")
29
+ else:
30
+ cp = None
31
+ gpu_available = False
32
+ print("Warning: No CUDA-capable devices found. Reverting to CPU.")
33
+ except ImportError:
34
+ cp = None
35
+ gpu_available = False
36
+ print("CuPy not installed. Using NumPy for CPU computations.")
37
+ except Exception as e:
38
+ cp = None
39
+ gpu_available = False
40
+ print(f"Warning: An unexpected error occurred while initializing CuPy: {e}\nReverting to CPU computations.")
41
+
42
+ # Fixed random seed for NumPy
43
+ np.random.seed(42)
44
+
45
+ class NMF:
46
+ FIXED_RANDOM_STATE = 42 # Fixed seed for determinism
47
+
48
+ def __init__(self, n_components, max_iter=1000, tol=1e-4, random_state=FIXED_RANDOM_STATE):
49
+ self.n_components = n_components
50
+ self.max_iter = max_iter
51
+ self.tol = tol
52
+ self.random_state = random_state
53
+
54
+ def fit_transform(self, X):
55
+ """
56
+ Fit the NMF model to X (in FP32) and return the factorized matrices (W, H).
57
+
58
+ If GPU is available, attempts GPU-based factorization with CuPy.
59
+ Otherwise, falls back to CPU-based factorization with NumPy.
60
+ """
61
+ if gpu_available:
62
+ try:
63
+ return self._fit_transform_gpu(X)
64
+ except cp.cuda.memory.OutOfMemoryError:
65
+ print("GPU out of memory during NMF computation. Switching to CPU.")
66
+ return self._fit_transform_cpu(cp.asnumpy(X))
67
+ else:
68
+ return self._fit_transform_cpu(X)
69
+
70
+ def _fit_transform_gpu(self, X):
71
+ cp.random.seed(self.random_state)
72
+ X = cp.asarray(X, dtype=cp.float32)
73
+ n_samples, n_features = X.shape
74
+
75
+ W = cp.maximum(cp.random.rand(n_samples, self.n_components, dtype=cp.float32), 1e-4)
76
+ H = cp.maximum(cp.random.rand(self.n_components, n_features, dtype=cp.float32), 1e-4)
77
+
78
+ for _ in range(self.max_iter):
79
+ try:
80
+ numerator_H = W.T @ X
81
+ denominator_H = W.T @ W @ H + 1e-9
82
+ H *= numerator_H / denominator_H
83
+ H = cp.maximum(H, 1e-4)
84
+
85
+ numerator_W = X @ H.T
86
+ denominator_W = W @ H @ H.T + 1e-9
87
+ W *= numerator_W / denominator_W
88
+ W = cp.maximum(W, 1e-4)
89
+ except cp.cuda.memory.OutOfMemoryError:
90
+ print("GPU out of memory during NMF iteration. Switching to CPU.")
91
+ del W, H, X
92
+ cp._default_memory_pool.free_all_blocks()
93
+ return self._fit_transform_cpu(cp.asnumpy(X))
94
+ return W.get(), H.get()
95
+
96
+ def _fit_transform_cpu(self, X):
97
+ np.random.seed(self.random_state)
98
+ X = X.astype(np.float32)
99
+ n_samples, n_features = X.shape
100
+
101
+ W = np.maximum(np.random.rand(n_samples, self.n_components).astype(np.float32), 1e-4)
102
+ H = np.maximum(np.random.rand(self.n_components, n_features).astype(np.float32), 1e-4)
103
+
104
+ for _ in range(self.max_iter):
105
+ numerator_H = W.T @ X
106
+ denominator_H = W.T @ W @ H + 1e-9
107
+ H *= numerator_H / denominator_H
108
+ H = np.maximum(H, 1e-4)
109
+
110
+ numerator_W = X @ H.T
111
+ denominator_W = W @ H @ H.T + 1e-9
112
+ W *= numerator_W / denominator_W
113
+ W = np.maximum(W, 1e-4)
114
+ return W, H
115
+
116
+ class BenchMake:
117
+ FIXED_RANDOM_STATE = 42 # For any random operations in NMF, etc.
118
+
119
+ def __init__(self, n_jobs=-1):
120
+ """
121
+ Initialize BenchMake with the specified number of parallel jobs.
122
+ """
123
+ self.n_jobs = n_jobs
124
+
125
+ def _determine_batch_size(self, n_samples):
126
+ """
127
+ Automatically determine a batch size based on the number of samples and the number of jobs.
128
+ Aim for roughly 10 batches per worker; clamp the result between 100 and 1000.
129
+ """
130
+ p = self.n_jobs if self.n_jobs > 0 else (os.cpu_count() or 1)
131
+ batch_size = math.ceil(n_samples / (10 * p))
132
+ batch_size = max(100, min(batch_size, 1000))
133
+ return batch_size
134
+
135
+ def partition(self, X, y, test_size=0.2, data_type='tabular', return_indices=False):
136
+ """
137
+ Partition the dataset into training and testing sets via archetypal analysis
138
+ (with stable hashing) using FP32 throughout.
139
+
140
+ The only inputs required from the user are:
141
+ X, y, test_size, data_type, and return_indices.
142
+ Batch size is automatically determined.
143
+
144
+ Before GPU computations, the code estimates the required memory and checks
145
+ available GPU memory. If insufficient, it prints a warning and reverts to CPU.
146
+
147
+ If return_indices is False (default):
148
+ returns (X_train, X_test, y_train, y_test) in the same type as the inputs.
149
+ If return_indices is True:
150
+ returns (train_indices, test_indices) as lists of integers.
151
+ """
152
+ if data_type == 'tabular':
153
+ return self._partition_tabular(X, y, test_size, return_indices)
154
+ elif data_type == 'image':
155
+ return self._partition_image(X, y, test_size, return_indices)
156
+ elif data_type == 'sequential':
157
+ return self._partition_sequential(X, y, test_size, return_indices)
158
+ elif data_type == 'signal':
159
+ return self._partition_signal(X, y, test_size, return_indices)
160
+ elif data_type == 'graph':
161
+ return self._partition_graph(X, y, test_size, return_indices)
162
+ else:
163
+ raise ValueError(f"Unsupported data type: {data_type}")
164
+
165
+ # --- Partitioning methods for each data type ---
166
+
167
+ def _partition_tabular(self, X, y, test_size, return_indices):
168
+ if isinstance(X, pd.DataFrame):
169
+ X = X.values.astype(np.float32)
170
+ X_ordered, y_ordered = self._order_data_by_hash(X, y)
171
+ if gpu_available:
172
+ self._check_gpu_memory(X_ordered, test_size)
173
+ batch_size = self._determine_batch_size(len(X_ordered))
174
+ num_samples = len(X_ordered)
175
+ num_archetypes = max(1, int(np.ceil(num_samples * test_size)))
176
+ _, selected_indices = self._perform_archetypal_analysis(X_ordered, test_size, num_archetypes, batch_size)
177
+ return self._split_data(X_ordered, y_ordered, selected_indices, return_indices)
178
+
179
+ def _partition_image(self, X, y, test_size, return_indices):
180
+ if isinstance(X, pd.DataFrame):
181
+ X = X.values
182
+ if X.ndim >= 3:
183
+ n_samples = X.shape[0]
184
+ X = X.reshape(n_samples, -1).astype(np.float32)
185
+ elif X.ndim == 2:
186
+ X = X.astype(np.float32)
187
+ else:
188
+ raise ValueError("Unsupported image data shape.")
189
+ X_ordered, y_ordered = self._order_data_by_hash(X, y)
190
+ if gpu_available:
191
+ self._check_gpu_memory(X_ordered, test_size)
192
+ batch_size = self._determine_batch_size(len(X_ordered))
193
+ num_samples = len(X_ordered)
194
+ num_archetypes = max(1, int(np.ceil(num_samples * test_size)))
195
+ _, selected_indices = self._perform_archetypal_analysis(X_ordered, test_size, num_archetypes, batch_size)
196
+ return self._split_data(X_ordered, y_ordered, selected_indices, return_indices)
197
+
198
+ def _partition_signal(self, X, y, test_size, return_indices):
199
+ if isinstance(X, pd.DataFrame):
200
+ X = X.values
201
+ if isinstance(X, np.ndarray):
202
+ if X.ndim == 1:
203
+ X = X.reshape(-1, 1).astype(np.float32)
204
+ elif X.ndim > 2:
205
+ n_samples = X.shape[0]
206
+ X = X.reshape(n_samples, -1).astype(np.float32)
207
+ else:
208
+ X = X.astype(np.float32)
209
+ X_ordered, y_ordered = self._order_data_by_hash(X, y)
210
+ if gpu_available:
211
+ self._check_gpu_memory(X_ordered, test_size)
212
+ batch_size = self._determine_batch_size(len(X_ordered))
213
+ num_samples = len(X_ordered)
214
+ num_archetypes = max(1, int(np.ceil(num_samples * test_size)))
215
+ _, selected_indices = self._perform_archetypal_analysis(X_ordered, test_size, num_archetypes, batch_size)
216
+ return self._split_data(X_ordered, y_ordered, selected_indices, return_indices)
217
+
218
+ def _partition_sequential(self, X, y, test_size, return_indices):
219
+ if isinstance(X, pd.Series):
220
+ X_seq = X.tolist()
221
+ elif isinstance(X, list):
222
+ X_seq = X
223
+ else:
224
+ raise ValueError("Sequential data must be a list or Series.")
225
+ vectorizer = CountVectorizer(analyzer='char', lowercase=False)
226
+ X_numerical = vectorizer.fit_transform(X_seq).toarray().astype(np.float32)
227
+ X_ordered_num, y_ordered = self._order_data_by_hash(X_numerical, y)
228
+ if gpu_available:
229
+ self._check_gpu_memory(X_ordered_num, test_size)
230
+ batch_size = self._determine_batch_size(len(X_ordered_num))
231
+ num_samples = len(X_ordered_num)
232
+ num_archetypes = max(1, int(np.ceil(num_samples * test_size)))
233
+ _, selected_indices = self._perform_archetypal_analysis(X_ordered_num, test_size, num_archetypes, batch_size)
234
+ X_seq_ordered, _ = self._order_data_by_hash(X_seq, y)
235
+ return self._split_data(X_seq_ordered, y_ordered, selected_indices, return_indices)
236
+
237
+ def _partition_graph(self, X, y, test_size, return_indices):
238
+ if isinstance(X, pd.DataFrame):
239
+ X = X.values
240
+ if X.ndim > 2:
241
+ n_samples = X.shape[0]
242
+ X = X.reshape(n_samples, -1)
243
+ X = X.astype(np.float32)
244
+ X_ordered, y_ordered = self._order_data_by_hash(X, y)
245
+ if gpu_available:
246
+ self._check_gpu_memory(X_ordered, test_size)
247
+ batch_size = self._determine_batch_size(len(X_ordered))
248
+ num_samples = len(X_ordered)
249
+ num_archetypes = max(1, int(np.ceil(num_samples * test_size)))
250
+ _, selected_indices = self._perform_archetypal_analysis(X_ordered, test_size, num_archetypes, batch_size)
251
+ return self._split_data(X_ordered, y_ordered, selected_indices, return_indices)
252
+
253
+ # --- Archetypal Analysis and Distance Computations (FP32) ---
254
+
255
+ def _perform_archetypal_analysis(self, X, test_size, num_archetypes, batch_size=1000):
256
+ if isinstance(X, pd.DataFrame):
257
+ X = X.values
258
+ elif isinstance(X, list):
259
+ X = np.array(X, dtype=np.float32)
260
+ X = X.astype(np.float32)
261
+ X_min = np.min(X, axis=0).astype(np.float32)
262
+ X_max = np.max(X, axis=0).astype(np.float32)
263
+ X_scaled = (X - X_min) / (X_max - X_min + 1e-9)
264
+ X_scaled = X_scaled.astype(np.float32)
265
+ n_samples, n_features = X_scaled.shape
266
+ test_size_count = max(1, int(np.ceil(n_samples * test_size)))
267
+ num_archetypes = test_size_count
268
+ nmf = NMF(n_components=num_archetypes, max_iter=200, tol=1e-4, random_state=42)
269
+ W, H = nmf.fit_transform(X_scaled)
270
+ explained_variances = np.var(W, axis=0)
271
+ sorted_indices = np.argsort(explained_variances)[::-1]
272
+ H_sorted = H[sorted_indices]
273
+ distances = self._compute_distances(X_scaled, H_sorted, batch_size)
274
+ selected_indices = set()
275
+ for i in range(num_archetypes):
276
+ archetype_distances = distances[:, i].copy()
277
+ if selected_indices:
278
+ archetype_distances[list(selected_indices)] = np.inf
279
+ idx = np.argmin(archetype_distances)
280
+ selected_indices.add(idx)
281
+ selected_indices = sorted(selected_indices)
282
+ return X_scaled, selected_indices
283
+
284
+ def _compute_distances(self, X_scaled, H_sorted, batch_size=1000):
285
+ if gpu_available and cp is not None:
286
+ return self._compute_distances_gpu_batched(X_scaled, H_sorted, batch_size)
287
+ else:
288
+ return self._compute_distances_cpu_batched(X_scaled, H_sorted, batch_size)
289
+
290
+ def _compute_distances_gpu_batched(self, X_scaled, H_sorted, batch_size=1000):
291
+ n_samples = X_scaled.shape[0]
292
+ n_archetypes = H_sorted.shape[0]
293
+ distances = np.empty((n_samples, n_archetypes), dtype=np.float32)
294
+ try:
295
+ H_sorted_cp = cp.asarray(H_sorted, dtype=cp.float32)
296
+ for start_idx in range(0, n_samples, batch_size):
297
+ end_idx = min(start_idx + batch_size, n_samples)
298
+ X_batch = cp.asarray(X_scaled[start_idx:end_idx], dtype=cp.float32)
299
+ batch_distances = cp.linalg.norm(
300
+ X_batch[:, cp.newaxis, :] - H_sorted_cp[cp.newaxis, :, :],
301
+ axis=2
302
+ ).get()
303
+ distances[start_idx:end_idx] = batch_distances
304
+ del X_batch, batch_distances
305
+ cp._default_memory_pool.free_all_blocks()
306
+ del H_sorted_cp
307
+ cp._default_memory_pool.free_all_blocks()
308
+ except cp.cuda.memory.OutOfMemoryError:
309
+ print("GPU out of memory. Switching to CPU distance computation.")
310
+ cp._default_memory_pool.free_all_blocks()
311
+ return self._compute_distances_cpu_batched(X_scaled, H_sorted, batch_size)
312
+ return distances
313
+
314
+ def _compute_distances_cpu_batched(self, X_scaled, H_sorted, batch_size=500):
315
+ n_samples = X_scaled.shape[0]
316
+ n_archetypes = H_sorted.shape[0]
317
+ distances = np.empty((n_samples, n_archetypes), dtype=np.float32)
318
+ def compute_batch(start_idx, end_idx):
319
+ X_batch = X_scaled[start_idx:end_idx]
320
+ batch_distances = np.linalg.norm(
321
+ X_batch[:, np.newaxis, :] - H_sorted[np.newaxis, :, :],
322
+ axis=2
323
+ ).astype(np.float32)
324
+ return (start_idx, end_idx, batch_distances)
325
+ batches = [(i, min(i + batch_size, n_samples)) for i in range(0, n_samples, batch_size)]
326
+ results = Parallel(n_jobs=self.n_jobs)(delayed(compute_batch)(start, end) for start, end in batches)
327
+ for start, end, batch_distances in results:
328
+ distances[start:end] = batch_distances
329
+ return distances
330
+
331
+ # --- GPU Memory Estimation and Check ---
332
+
333
+ def _estimate_memory(self, X, test_size):
334
+ n_samples, n_features = X.shape
335
+ n_components = max(1, int(np.ceil(n_samples * test_size)))
336
+ size_X = n_samples * n_features * 4
337
+ size_W = n_samples * n_components * 4
338
+ size_H = n_components * n_features * 4
339
+ size_X_scaled = size_X
340
+ size_distance = n_samples * n_components * 4
341
+ total = size_X + size_W + size_H + size_X_scaled + size_distance
342
+ safety_factor = 1.5
343
+ return total * safety_factor
344
+
345
+ def _check_gpu_memory(self, X, test_size):
346
+ global gpu_available
347
+ estimated = self._estimate_memory(X, test_size)
348
+ free_mem = cp.cuda.runtime.memGetInfo()[0]
349
+ if free_mem < estimated:
350
+ print(f"Warning: Estimated GPU memory required is {estimated} bytes, "
351
+ f"but only {free_mem} bytes are free. Switching to CPU.")
352
+ gpu_available = False
353
+
354
+ # --- Hash-based ordering ---
355
+
356
+ def _order_data_by_hash(self, X, y):
357
+ row_hashes = []
358
+ num_rows = len(X)
359
+ for i in range(num_rows):
360
+ row_i = self._get_row(X, i)
361
+ row_bytes = self._row_to_bytes(row_i)
362
+ h = hashlib.md5(row_bytes).hexdigest()
363
+ row_hashes.append(h)
364
+ sorted_indices = np.argsort(row_hashes)
365
+ X_ordered = self._reindex_data(X, sorted_indices)
366
+ y_ordered = self._reindex_data(y, sorted_indices)
367
+ return X_ordered, y_ordered
368
+
369
+ def _get_row(self, X, i):
370
+ if isinstance(X, pd.DataFrame):
371
+ return X.iloc[i].values
372
+ elif isinstance(X, pd.Series):
373
+ return X.iloc[i]
374
+ elif isinstance(X, np.ndarray):
375
+ return X[i]
376
+ elif isinstance(X, list):
377
+ return X[i]
378
+ else:
379
+ raise TypeError("Unsupported type for X in _get_row().")
380
+
381
+ def _row_to_bytes(self, row_i):
382
+ if isinstance(row_i, str):
383
+ return row_i.encode('utf-8')
384
+ if isinstance(row_i, (np.ndarray, list, tuple)):
385
+ try:
386
+ arr = np.array(row_i, dtype=np.float32).reshape(-1)
387
+ return arr.tobytes()
388
+ except ValueError:
389
+ return str(row_i).encode('utf-8')
390
+ else:
391
+ return str(row_i).encode('utf-8')
392
+
393
+ def _reindex_data(self, data, indices):
394
+ if isinstance(data, pd.DataFrame):
395
+ return data.iloc[indices].reset_index(drop=True)
396
+ elif isinstance(data, pd.Series):
397
+ return data.iloc[indices].reset_index(drop=True)
398
+ elif isinstance(data, np.ndarray):
399
+ return data[indices]
400
+ elif isinstance(data, list):
401
+ return [data[i] for i in indices]
402
+ else:
403
+ raise TypeError("Unsupported data type in _reindex_data.")
404
+
405
+ # --- Splitting train/test with optional return of indices ---
406
+
407
+ def _split_data(self, X, y, selected_indices, return_indices):
408
+ test_set = set(selected_indices)
409
+ all_set = set(range(len(X)))
410
+ train_set = sorted(all_set - test_set)
411
+ test_set = sorted(test_set)
412
+ if len(test_set) == 0:
413
+ raise ValueError("No instances selected for the test set.")
414
+ if len(train_set) == 0:
415
+ raise ValueError("No instances left for the training set.")
416
+ if return_indices:
417
+ return train_set, test_set
418
+ else:
419
+ X_train = self._reindex_data(X, train_set)
420
+ X_test = self._reindex_data(X, test_set)
421
+ y_train = self._reindex_data(y, train_set)
422
+ y_test = self._reindex_data(y, test_set)
423
+ return X_train, X_test, y_train, y_test
@@ -0,0 +1,309 @@
1
+ Metadata-Version: 2.4
2
+ Name: benchmake
3
+ Version: 1.0.0
4
+ Summary: A lightweight benchmarking toolkit for Python, helping you measure and compare code performance with ease.
5
+ Author: Prof Dr Amanda S Barnard
6
+ License-Expression: MIT
7
+ Keywords: benchmark,performance,tooling
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Programming Language :: Python :: 3.8
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.6
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy
16
+ Requires-Dist: pandas
17
+ Requires-Dist: joblib
18
+ Requires-Dist: scikit-learn
19
+ Dynamic: license-file
20
+
21
+ ---
22
+ # BenchMake
23
+ ## Turn any Scientific Data Set into a Reproducible Benchmark
24
+
25
+ Version: **1.0.0**
26
+ Date: **19/05/2025**
27
+ Author: **Prof. Amanda S. Barnard, PhD DSc**
28
+
29
+ BenchMake is a Python package that partitions a data set into train/test splits using **archetypal analysis**. It relies on an **NMF-based** approach, performing a multiplicative-update factorization and then computing distances to the discovered “archetypes.” The nearest unique data points become the test set (or optionally just the test **indices**). BenchMake supports **GPU acceleration** via **CuPy** (if available), or automatically falls back to CPU-based NumPy.
30
+
31
+ ## Table of Contents
32
+
33
+ 1. [Features](#features)
34
+ 2. [Installation](#installation)
35
+ 3. [Quick Start](#quick-start)
36
+ 4. [Usage](#usage)
37
+ - [Partitioning Tabular Data](#partitioning-tabular-data)
38
+ - [Partitioning Images](#partitioning-images)
39
+ - [Partitioning Sequential Data](#partitioning-sequential-data)
40
+ - [Partitioning Signal Data](#partitioning-signal-data)
41
+ - [Partitioning Graph Data](#partitioning-graph-data)
42
+ 5. [Implementation](#implementation)
43
+ - [Parallelism & GPU Acceleration](#parallelism--gpu-acceleration)
44
+ - [Algorithmic Details](#algorithmic-details)
45
+ - [Known Limitations](#known-limitations)
46
+ 6. [Acknowledgements](#acknowledgments)
47
+ - [License](#license)
48
+ - [Citation](#citation)
49
+
50
+ ---
51
+
52
+ ## Features
53
+
54
+ - **Archetypal Analysis Partitioning**
55
+ Automatically finds “extreme” points (archetypes) that best approximate the entire data set in a low-dimensional sense, and uses them to form a test set.
56
+
57
+ - **Multi-Domain Support**
58
+ BenchMake handles:
59
+ - **Tabular** structred data (NumPy arrays, Pandas DataFrames)
60
+ - **Image** data (multi-dimensional arrays)
61
+ - **Sequential** data (strings, text)
62
+ - **Signal** data (time-series, audio, sensor arrays)
63
+ - **Graph** data (node-feature matrices)
64
+
65
+ - **Deterministic**
66
+ Fixed random seeds and consistent initialization ensure you get the same splits every time for the same data, whatever split size you select, regardless of data order.
67
+
68
+ - **Automatic Batch Size**
69
+ Dynamically chooses a batch size for distance computations based on the data size and number of CPU jobs available.
70
+
71
+ - **Optional Return of Indices**
72
+ Users can obtain either `(X_train, X_test, y_train, y_test)` **or** `(Train_indices, Test_indices)` for maximum flexibility.
73
+
74
+ ---
75
+
76
+ ## Installation
77
+
78
+ BenchMake requires Python 3.7 or above. To install via pip:
79
+
80
+ ```bash
81
+ pip install benchmake
82
+ ```
83
+
84
+ **Optional**: For GPU support, install [CuPy](https://docs.cupy.dev/en/stable/install.html) appropriate to your CUDA version. Install CuPy separately if you require this capability, making sure it is compatible with your CUDA installation too. If CuPy is not found or no compatible GPU exists, BenchMake reverts to CPU silently (with a warning).
85
+
86
+ ---
87
+
88
+ ## Quick Start
89
+
90
+ ```python
91
+ from benchmake import BenchMake
92
+ import numpy as np
93
+
94
+ # Sample data: 1000 samples, 20 features
95
+ X = np.random.rand(1000, 20)
96
+ y = np.random.randint(0, 5, size=1000)
97
+
98
+ # Instantiate BenchMake with 4 parallel CPU jobs
99
+ bm = BenchMake(n_jobs=4)
100
+
101
+ # Partition the data into train/test using 20% test split
102
+ X_train, X_test, y_train, y_test = bm.partition(
103
+ X,
104
+ y,
105
+ test_size=0.2,
106
+ data_type='tabular',
107
+ return_indices=False
108
+ )
109
+
110
+ print("Train size:", len(X_train), "Test size:", len(X_test))
111
+ ```
112
+
113
+ ---
114
+
115
+ ## Usage
116
+
117
+ ### Partitioning Tabular Data
118
+
119
+ When tabular data is provided (as a NumPy array, Pandas DataFrame, or list), BenchMake first converts it to a consistent NumPy array (if it isn’t already) so that all numerical operations are performed in float32. Next, it reorders the data rows deterministically by computing a stable hash (using the MD5 algorithm) for each row. This guarantees that the same data, regardless of the original row order, produces the same sorted order. BenchMake then applies a min–max scaling to the data before partitioning. BenchMake returns either four splits (`X_train, X_test, y_train, y_test`) in the same data type as the user provided (for example, if you used Pandas DataFrames, you get DataFrames back) or, if requested, just the lists of indices for the training and testing sets.
120
+
121
+ Assume you have `(X, y)` in either a NumPy array or a Pandas DataFrame/Series. Just specify `data_type='tabular'`:
122
+
123
+ ```python
124
+ X_train, X_test, y_train, y_test = bm.partition(
125
+ X,
126
+ y,
127
+ test_size=0.2,
128
+ data_type='tabular',
129
+ return_indices=False
130
+ )
131
+
132
+ Train_indices, Test_indices = bm.partition(
133
+ X,
134
+ y,
135
+ test_size=0.2,
136
+ data_type='tabular',
137
+ return_indices=True
138
+ )
139
+ ```
140
+
141
+ ### Partitioning Images
142
+
143
+ For image data, BenchMake expects input in the form of a multi-dimensional array or DataFrame, where each image is typically structured as (`n_samples`, `height`, `width`, `channels`). It first converts the data to a float32 NumPy array (if it isn’t already) and then flattens each image (`n_samples, height*width*channels`) into a one-dimensional vector so that every image is represented as a row vector. The rows are then reordered deterministically using the stable hashing strategy. The images (now as 1D vectors) are min–max scaled, and the data is partitioned. BenchMake returns either the training and testing subsets in the same format as the original input (e.g., as NumPy arrays or DataFrames) or the corresponding indices if the user has requested that mode.
144
+
145
+ ```python
146
+ # Suppose X is shape (n_samples, height, width, channels)
147
+ X_train, X_test, y_train, y_test = bm.partition(
148
+ X,
149
+ y,
150
+ test_size=0.2,
151
+ data_type='image',
152
+ return_indices=False
153
+ )
154
+
155
+ Train_indices, Test_indices = bm.partition(
156
+ X,
157
+ y,
158
+ test_size=0.2,
159
+ data_type='image',
160
+ return_indices=True
161
+ )
162
+ ```
163
+
164
+ ### Partitioning Sequential Data
165
+
166
+ BenchMake handles sequential data such as text strings, SMILES strings, or DNA sequences by first taking the provided list or Pandas Series and converting each sequence into a numerical (vector) representation using a character-level `CountVectorizer`. This transformation results in a two-dimensional NumPy array (float32) where each row corresponds to the numeric representation of a sequence. The rows of this numeric representation are then deterministically reordered via the stable hash. BenchMake then applies min–max scaling and partitions the data. Finally, the original sequences are re-ordered using the same hash order, and BenchMake returns either the full training and testing splits (in the same type as the original input, e.g., list or Series) or the indices of the splits if that is requested.
167
+
168
+ For sequences or text:
169
+
170
+ ```python
171
+ sequences = ["ACGTG", "GGTTA", "TTACG", ...] # e.g., list of strings
172
+ # sequences can also be SMILEs, e.g., ["CCO", "c1ccccc1", "CC(=O)O", ...]
173
+ y = [label1, label2, ...] # labels
174
+
175
+ X_train, X_test, y_train, y_test = bm.partition(
176
+ sequences,
177
+ y,
178
+ test_size=0.2,
179
+ data_type='sequential',
180
+ return_indices=False
181
+ )
182
+
183
+ Train_indices, Test_indices = bm.partition(
184
+ sequences,
185
+ y,
186
+ test_size=0.2,
187
+ data_type='sequential',
188
+ return_indices=True
189
+ )
190
+ ```
191
+
192
+ ### Partitioning Signal Data
193
+
194
+ For signal data such as time series, audio signals, or sensor outputs BenchMake first ensures that the data is represented as a consistent float32 NumPy array. If the signals are provided in a multi-dimensional format (for example, if each signal has multiple channels or timepoints arranged in a 3D array), they are flattened so that each signal becomes a single row vector. Once in this unified 2D format, the rows are deterministically sorted using a stable hashing method. After min–max scaling BenchMake partitions the data. BenchMake returns either the resulting training and testing data in the same structure as the input (e.g., NumPy arrays or DataFrames) or simply the lists of indices for each split.
195
+
196
+ Signal data (time-series, audio, sensors) can be 2D `(n_signals, n_features)` or 3D `(n_signals, length, channels)`:
197
+
198
+ ```python
199
+ X_train, X_test, y_train, y_test = bm.partition(
200
+ X,
201
+ y,
202
+ test_size=0.2,
203
+ data_type='signal',
204
+ return_indices=False
205
+ )
206
+
207
+ Train_indices, Test_indices = bm.partition(
208
+ X,
209
+ y,
210
+ test_size=0.2,
211
+ data_type='signal',
212
+ return_indices=True
213
+ )
214
+ ```
215
+ ### Partitioning Graph Data
216
+
217
+ When dealing with graph data, BenchMake assumes that the user provides a node-feature matrix where each row represents a node and each column represents a feature (this can be in a Pandas DataFrame, NumPy array, or list format). If necessary, the multi-dimensional input is first converted into a two-dimensional float32 array (by flattening any extra dimensions). Stable hashing is applied to the rows to reorder the data, and following min–max scaling, BenchMake partitions the data based on the nodes. The final output will be either the training and testing splits in the same format as the input data or, if specified by the user, the lists of indices corresponding to these splits.
218
+
219
+ If you have a node-feature matrix `(n_nodes, n_features)`, treat it as `data_type='graph'`:
220
+
221
+ ```python
222
+ X_train, X_test, y_train, y_test = bm.partition(
223
+ X_node_features,
224
+ node_labels,
225
+ test_size=0.2,
226
+ data_type='graph',
227
+ return_indices=False
228
+ )
229
+
230
+ Train_indices, Test_indices = bm.partition(
231
+ X_node_features,
232
+ node_labels,
233
+ test_size=0.2,
234
+ data_type='graph',
235
+ return_indices=True
236
+ )
237
+ ```
238
+
239
+ ## Implementation
240
+
241
+ ### Parallelism & GPU Acceleration
242
+
243
+ CPU Parallelism:
244
+ BenchMake uses Python’s [joblib](https://joblib.readthedocs.io/) for parallelizing the **distance** computations only.
245
+ The main NMF loop is effectively single-threaded from Python’s perspective, though an optimized BLAS library (MKL/OpenBLAS) can provide multi-threaded matrix multiplication.
246
+
247
+ GPU Acceleration:
248
+ If [CuPy](https://docs.cupy.dev/) is installed and you have a CUDA-capable GPU, BenchMake calls GPU code for the NMF factorization and distance calculations.
249
+ If insufficient GPU memory is detected, or if any GPU error occurs, BenchMake warns and reverts to the CPU.
250
+
251
+ Batch Size:
252
+ Automatically chosen to balance memory usage and overhead. You can control the number of CPU jobs via `n_jobs` when creating `BenchMake(n_jobs=4)`. Use `BenchMake(n_jobs=-1)` to access all available processors.
253
+
254
+ Important: Because most of the work is in the NMF loop, you may not see dramatic multi-CPU speedups unless you rely on a multi-threaded NumPy/BLAS or CuPy on GPU.
255
+
256
+
257
+
258
+ ### Algorithmic Details
259
+
260
+ 1. NMF (Multiplicative Update):
261
+ BenchMake performs a basic multiplicative‐update NMF with a fixed random seed for determinism. The number of components is equal to the desired **test set size** (i.e., `ceil(n_samples * test_size)`).
262
+
263
+ 2. Archetype Selection:
264
+ After NMF, the code computes distances from each sample to each of the `k` archetypes, picks the closest sample to each archetype, and forms the test set from those selected indices.
265
+
266
+ 3. Stable Hash Sorting:
267
+ BenchMake reorders all data by a hash of each row’s bytes to ensure that identical data yields identical partitions no matter the input order. This ensures strict determinism.
268
+
269
+
270
+
271
+ ### Known Limitations
272
+
273
+ Scaling:
274
+ Because `k ~ O(n)` (for a constant fraction test size) and factorization and distances (d) each scale approximately as `O(n² d)`, BenchMake can become slow for very large data sets. BenchMake is not a fast alternative to random splits, it is a better alternative; delivering reproducible, and more challenging testing sets.
275
+
276
+ Limited Parallelism:
277
+ The NMF step is effectively single-threaded except for what is inherent in BLAS. Only the distance computations are joblib-parallelized. GPU usage (if available) provides a bigger speedup for NMF and distance steps.
278
+
279
+ Memory Consumption:
280
+ For large `n`, or if `test_size` is large, memory usage can be significant. BenchMake attempts to estimate GPU memory usage and revert to CPU if insufficient.
281
+
282
+ Simplicity Over Customization:
283
+ BenchMake does not expose advanced NMF algorithms (such as HALS or block-coordinate). The code may be extended to accommodate more sophisticated or distributed approaches in the future.
284
+
285
+
286
+ ## Acknowledgments
287
+
288
+ ### License
289
+
290
+ The project is distributed under an MIT License.
291
+
292
+ This software is provided 'as-is', without any express or implied warranty. Use at your own risk.
293
+
294
+ ### Citation
295
+
296
+ Amanda S. Barnard, "BenchMake: Turn any Scientific Data Set into a Reproducible Benchmark" arXiv preprint arXiv:XXXX.YYYY, 2025.
297
+
298
+ ```python
299
+ @misc{barnard2025benchmake,
300
+ author = {Barnard, Amanda S.},
301
+ title = {BenchMake: Turn any Scientific Data Set into a Reproducible Benchmark},
302
+ howpublished = {arXiv preprint arXiv:XXXX.YYYY},
303
+ year = {2025},
304
+ note = {Version 1.0, 10/04/2025}
305
+ }
306
+ ```
307
+
308
+
309
+ Happy BenchMaking!
@@ -0,0 +1,6 @@
1
+ BenchMake.py,sha256=Jajpvey9PwWGNokQYdQzQdkEXHcWigvBJrXhllTh0CA,18421
2
+ benchmake-1.0.0.dist-info/licenses/LICENSE,sha256=zcYjYeAPgBZbzNpmMcgj2yPJ77kNObAk6X8O4uWp3iA,1094
3
+ benchmake-1.0.0.dist-info/METADATA,sha256=9xR4VFnBXS6nW97gHNFkpJr1M8xHkia8W3FKkj7hIcU,13769
4
+ benchmake-1.0.0.dist-info/WHEEL,sha256=Nw36Djuh_5VDukK0H78QzOX-_FQEo6V37m3nkm96gtU,91
5
+ benchmake-1.0.0.dist-info/top_level.txt,sha256=LOtZD8uF5rnH5lLQTo5pu9rFec6N4o5M_fmvO5zIXsI,10
6
+ benchmake-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.7.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) [2025] Amanda S Barnard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ BenchMake