copairs.compute¶
copairs.compute
¶
Functions to compute distances and ranks using numpy operations.
ap_contiguous(rel_k_list, counts)
¶
Compute Average Precision (AP) scores from relevance labels.
This function calculates Average Precision (AP) scores for each profile based on relevance labels and their associated counts. It also returns configurations indicating the number of positive and total pairs for each profile.
Parameters:
-
rel_k_list(ndarray) –Array of relevance labels (1 for positive pairs, 0 for negative pairs), sorted by descending similarity within profiles.
-
counts(ndarray) –Array indicating how many times each profile appears in the rank list.
Returns:
-
ap_scores(ndarray) –Array of Average Precision scores for each profile.
-
null_confs(ndarray) –Array of configurations, where each row corresponds to: - Number of positive pairs (
num_pos). - Total number of pairs (counts).
Source code in src/copairs/compute.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
average_precision(rel_k)
¶
Compute average precision based on binary list indices.
Source code in src/copairs/compute.py
391 392 393 394 395 396 | |
batch_processing(pairwise_op, progress_bar=True)
¶
Add batch processing support to pairwise operations.
This decorator wraps a pairwise operation to process data in batches, enabling efficient computation and multithreading when working with large datasets.
Parameters:
-
pairwise_op(Callable) –A function that computes pairwise operations (e.g., similarity or distance) between two arrays of features.
-
progress_bar(bool, default:True) –Whether or not to show tqdm's progress bar.
Returns:
-
Callable–A wrapped function that processes pairwise operations in batches.
Source code in src/copairs/compute.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | |
concat_ranges(start, end)
¶
Create a 1D array by concatenating multiple integer ranges.
This function generates a single concatenated array from multiple ranges defined
by the start and end arrays. Each range is inclusive of start and exclusive
of end.
Parameters:
-
start(ndarray) –A 1D array of start indices for the ranges.
-
end(ndarray) –A 1D array of end indices for the ranges. Must have the same shape as
start.
Returns:
-
ndarray–A 1D array containing the concatenated ranges.
Source code in src/copairs/compute.py
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 | |
get_null_dists(confs, null_size, seed, cache_dir=None, progress_bar=True)
¶
Generate null distributions for each configuration of positive and total pairs.
Parameters:
-
confs(ndarray) –Array where each row contains the number of positive pairs (
num_pos) and total pairs (total) for a specific configuration. -
null_size(int) –Number of samples to generate in the null distribution.
-
seed(int) –Random seed for reproducibility. Each configuration's null is seeded by
(seed, num_pos, total), so it does not depend on the other configurations. WithNone, nulls are fresh draws and are not cached. -
progress_bar(bool, default:True) –Whether or not to show tqdm's progress bar.
Returns:
-
ndarray–A 2D array where each row corresponds to a null distribution for a specific configuration.
Source code in src/copairs/compute.py
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 | |
get_similarity_fn(distance, progress_bar=True)
¶
Retrieve a similarity function based on a distance string identifier or custom callable.
This function provides flexibility in specifying the distance function to be used for pairwise similarity computations. Users can choose a metrics from a predefined set, scipy.spational.distance submodule, or provide a custom callable.
Parameters:
-
distance(str or callable) –The name of the distance function or a custom callable function. Supported string identifiers for predefined metrics are: - "cosine": Cosine similarity. - "abs_cosine": Absolute cosine similarity. - "correlation": Pearson correlation coefficient. - "euclidean": Inverse Euclidean distance (scaled to range 0-1). - "manhattan": Inverse Manhattan distance (scaled to range 0-1). - "chebyshev": Inverse Chebyshev distance (scaled to range 0-1).
Additionally, any distance metric supported by
scipy.spatial.distance.cdistcan be used by providing the metric name as a string.If a callable is provided, it must accept the paramters associated with each callable function.
-
progress_bar(bool, default:True) –Whether or not to show tqdm's progress bar.
Returns:
-
callable–A function implementing the specified similarity function.
Raises:
-
ValueError:–If the provided
distanceis not a recognized string identifier or a valid callable.
Example:
distance_fn = get_distance_fn("cosine") similarity_scores = distance_fn(x_sample, y_sample)
Source code in src/copairs/compute.py
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
null_dist_cached(num_pos, total, seed, null_size, cache_dir)
¶
Generate or retrieve a cached null distribution for a given configuration.
Each (num_pos, total, seed) triple is cached as an individual .npy file,
so a cached null is exactly the one random_ap would generate. Reads
are lock-free (just np.load), and writes use atomic rename to prevent
corruption from concurrent workers.
Parameters:
-
num_pos(int) –Number of positive pairs in the configuration.
-
total(int) –Total number of pairs (positive + negative) in the configuration.
-
seed(int) –Random seed for reproducibility.
-
null_size(int) –Number of samples to generate in the null distribution.
-
cache_dir(Path) –Directory to store or retrieve cached null distributions.
Returns:
-
ndarray–Null distribution for the specified configuration.
Source code in src/copairs/compute.py
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | |
p_values(ap_scores, null_confs, null_size, seed, progress_bar=True)
¶
Calculate p-values for an array of Average Precision (AP) scores using a null distribution.
Parameters:
-
ap_scores(ndarray) –Array of observed AP scores for which to calculate p-values.
-
null_confs(ndarray) –Configuration array indicating the relevance or context of each AP score. Used to generate corresponding null distributions.
-
null_size(int) –Number of samples to generate in the null distribution for each configuration.
-
seed(int) –Seed for the random number generator to ensure reproducibility of the null distribution.
-
progress_bar(bool, default:True) –Whether or not to show tqdm's progress bar.
Returns:
-
ndarray–An array of p-values corresponding to the input AP scores.
Source code in src/copairs/compute.py
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 | |
pairwise_abs_cosine(x_sample, y_sample)
¶
Compute the absolute cosine similarity for paired rows of two matrices.
Parameters:
-
x_sample(ndarray) –A 2D array where each row represents a profile.
-
y_sample(ndarray) –A 2D array of the same shape as
x_sample.
Returns:
-
ndarray–Absolute values of cosine similarity scores.
Source code in src/copairs/compute.py
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | |
pairwise_chebyshev(x_sample, y_sample)
¶
Compute the inverse Chebyshev distance for paired rows of two matrices.
Parameters:
-
x_sample(ndarray) –A 2D array where each row represents a profile.
-
y_sample(ndarray) –A 2D array of the same shape as
x_sample.
Returns:
-
ndarray–A 1D array of inverse Chebyshev distance scores (scaled to range 0-1).
Source code in src/copairs/compute.py
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
pairwise_corr(x_sample, y_sample)
¶
Compute the Pearson correlation coefficient for paired rows of two matrices.
Parameters:
-
x_sample(ndarray) –A 2D array where each row represents a profile
-
y_sample(ndarray) –A 2D array of the same shape as
x_sample.
Returns:
-
ndarray–A 1D array of Pearson correlation coefficients for each row pair in
x_sampleandy_sample.
Source code in src/copairs/compute.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
pairwise_cosine(x_sample, y_sample)
¶
Compute cosine similarity for paired rows of two matrices.
Parameters:
-
x_sample(ndarray) –A 2D array where each row represents a profile.
-
y_sample(ndarray) –A 2D array of the same shape as
x_sample.
Returns:
-
ndarray–A 1D array of cosine similarity scores for each row pair in
x_sampleandy_sample.
Source code in src/copairs/compute.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | |
pairwise_euclidean(x_sample, y_sample)
¶
Compute the inverse Euclidean distance for paired rows of two matrices.
Parameters:
-
x_sample(ndarray) –A 2D array where each row represents a profile.
-
y_sample(ndarray) –A 2D array of the same shape as
x_sample.
Returns:
-
ndarray–A 1D array of inverse Euclidean distance scores (scaled to range 0-1).
Source code in src/copairs/compute.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
pairwise_manhattan(x_sample, y_sample)
¶
Compute the inverse Manhattan distance for paired rows of two matrices.
Parameters:
-
x_sample(ndarray) –A 2D array where each row represents a profile.
-
y_sample(ndarray) –A 2D array of the same shape as
x_sample.
Returns:
-
ndarray–A 1D array of inverse Manhattan distance scores (scaled to range 0-1).
Source code in src/copairs/compute.py
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | |
pairwise_similarity_fn(distance)
¶
Return the (x_sample, y_sample) -> similarities function of distance.
The unbatched function :func:get_similarity_fn wraps; distance is
as there.
Source code in src/copairs/compute.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
parallel_map(par_func, items, progress_bar=True)
¶
Execute a function in parallel over a list of items.
This function uses a thread pool to process items in parallel, with progress
tracking via tqdm. It is particularly useful for batch operations that benefit
from multithreading.
Parameters:
-
par_func(Callable) –A function to execute for each item. It should accept a single argument (an item index or value).
-
items(ndarray) –An array or list of items to process.
Source code in src/copairs/compute.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
random_ap(num_perm, num_pos, total, seed)
¶
Generate random Average Precision (AP) scores to create a null distribution.
This function computes multiple Average Precision (AP) scores based on randomly generated binary relevance lists. It is useful for generating a null distribution to assess the significance of observed AP scores.
Parameters:
-
num_perm(int) –Number of random permutations (i.e., how many random relevance lists to generate).
-
num_pos(int) –Number of positive samples (1's) in each relevance list.
-
total(int) –Total number of samples (columns) in each relevance list.
-
seed(int) –Seed for the random number generator to ensure reproducibility.
Returns:
-
ndarray–A 1D array containing the Average Precision scores for each randomly generated relevance list.
Source code in src/copairs/compute.py
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 | |
random_binary_matrix(n, m, k, rng)
¶
Generate a indices of k values in 1 per row in a random binary n*m matrix.
Args: n: Number of rows. m: Number of columns. k: Number of 1's per row.
Returns:
-
ndarray–A binary matrix of shape
(n, m)with exactlykones per row.
Source code in src/copairs/compute.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | |
to_cutoffs(counts)
¶
Convert counts into cumulative cutoff indices.
This function generates a 1D array of indices that mark the start of each segment
in a cumulative list. The first index is always 0, and subsequent indices
correspond to the cumulative sum of counts up to the previous entry.
Parameters:
-
counts(ndarray) –A 1D array of counts representing the size of each segment.
Returns:
-
ndarray–A 1D array of cutoff indices where each value indicates the starting index for the corresponding segment.
Source code in src/copairs/compute.py
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 | |