|
| 1 | +"""Parallel function evaluation at build time via ProcessPoolExecutor.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import os |
| 5 | +from concurrent.futures import ProcessPoolExecutor |
| 6 | + |
| 7 | +import numpy as np |
| 8 | + |
| 9 | + |
| 10 | +def _normalize_n_workers(n_workers): |
| 11 | + """Validate and normalize n_workers ctor arg. |
| 12 | +
|
| 13 | + Returns |
| 14 | + ------- |
| 15 | + int | None |
| 16 | + None for sequential; positive int for parallel pool size. |
| 17 | +
|
| 18 | + Raises |
| 19 | + ------ |
| 20 | + ValueError |
| 21 | + If n_workers is 0, < -1, or not an int. |
| 22 | + """ |
| 23 | + if n_workers is None: |
| 24 | + return None |
| 25 | + if not isinstance(n_workers, int) or isinstance(n_workers, bool): |
| 26 | + raise ValueError(f"n_workers must be int or None, got {type(n_workers).__name__}") |
| 27 | + if n_workers == 0: |
| 28 | + raise ValueError("n_workers must be >= 1, -1 for cpu_count, or None for sequential") |
| 29 | + if n_workers == -1: |
| 30 | + return os.cpu_count() or 1 |
| 31 | + if n_workers < -1: |
| 32 | + raise ValueError(f"n_workers={n_workers} not allowed (use -1, 1, or positive int)") |
| 33 | + return n_workers |
| 34 | + |
| 35 | + |
| 36 | +def _evaluate_in_parallel(function, points, additional_data, n_workers): |
| 37 | + """Evaluate ``function(point, additional_data)`` at every point. |
| 38 | +
|
| 39 | + Parameters |
| 40 | + ---------- |
| 41 | + function : callable |
| 42 | + Picklable callable taking (point, additional_data) -> scalar. |
| 43 | + points : iterable of points |
| 44 | + Iterable of point lists or arrays. |
| 45 | + additional_data : object |
| 46 | + Picklable second-arg context. |
| 47 | + n_workers : int | None |
| 48 | + Effective worker count (already normalized via _normalize_n_workers). |
| 49 | +
|
| 50 | + Returns |
| 51 | + ------- |
| 52 | + np.ndarray |
| 53 | + Shape (N,) float64 array of results. |
| 54 | + """ |
| 55 | + points_list = [list(p) for p in points] |
| 56 | + if n_workers is None or n_workers == 1: |
| 57 | + return np.array( |
| 58 | + [float(function(p, additional_data)) for p in points_list], |
| 59 | + dtype=np.float64, |
| 60 | + ) |
| 61 | + worker = _Worker(function, additional_data) |
| 62 | + with ProcessPoolExecutor(max_workers=n_workers) as pool: |
| 63 | + results = list(pool.map(worker, points_list)) |
| 64 | + return np.array(results, dtype=np.float64) |
| 65 | + |
| 66 | + |
| 67 | +class _Worker: |
| 68 | + """Picklable wrapper that calls ``function(point, additional_data)``.""" |
| 69 | + |
| 70 | + def __init__(self, function, additional_data): |
| 71 | + self.function = function |
| 72 | + self.additional_data = additional_data |
| 73 | + |
| 74 | + def __call__(self, point): |
| 75 | + return float(self.function(point, self.additional_data)) |
0 commit comments