| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
import concurrent.futures |
| 26 |
import itertools |
| 27 |
import os |
| 28 |
import sys |
| 29 |
import time |
| 30 |
|
| 31 |
from joblib import Parallel, delayed |
| 32 |
|
| 33 |
from .Utilities import tqdm |
| 34 |
|
| 35 |
|
| 36 |
def joblibParallelSupportsGenerator(): |
| 37 |
import joblib |
| 38 |
from packaging.version import Version |
| 39 |
|
| 40 |
joblibVer = joblib.__version__ |
| 41 |
return Version(joblibVer) >= Version("1.4.0") |
| 42 |
|
| 43 |
|
| 44 |
def CPUThreadCount(enable=True): |
| 45 |
from .GlobalParameters import globalParameters |
| 46 |
|
| 47 |
if not enable: |
| 48 |
return 1 |
| 49 |
else: |
| 50 |
if os.name == "nt": |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
cpu_count = min(os.cpu_count(), 61) |
| 55 |
else: |
| 56 |
cpu_count = len(os.sched_getaffinity(0)) |
| 57 |
cpuThreads = globalParameters["CpuThreads"] |
| 58 |
if cpuThreads == -1: |
| 59 |
return cpu_count |
| 60 |
|
| 61 |
return min(cpu_count, cpuThreads) |
| 62 |
|
| 63 |
|
| 64 |
def pcallWithGlobalParamsMultiArg(f, args, newGlobalParameters): |
| 65 |
OverwriteGlobalParameters(newGlobalParameters) |
| 66 |
return f(*args) |
| 67 |
|
| 68 |
|
| 69 |
def pcallWithGlobalParamsSingleArg(f, arg, newGlobalParameters): |
| 70 |
OverwriteGlobalParameters(newGlobalParameters) |
| 71 |
return f(arg) |
| 72 |
|
| 73 |
|
| 74 |
def apply_print_exception(item, *args): |
| 75 |
|
| 76 |
try: |
| 77 |
if len(args) > 0: |
| 78 |
func = item |
| 79 |
args = args[0] |
| 80 |
return func(*args) |
| 81 |
else: |
| 82 |
func, item = item |
| 83 |
return func(item) |
| 84 |
except Exception: |
| 85 |
import traceback |
| 86 |
|
| 87 |
traceback.print_exc() |
| 88 |
raise |
| 89 |
finally: |
| 90 |
sys.stdout.flush() |
| 91 |
sys.stderr.flush() |
| 92 |
|
| 93 |
|
| 94 |
def OverwriteGlobalParameters(newGlobalParameters): |
| 95 |
from . import GlobalParameters |
| 96 |
|
| 97 |
GlobalParameters.globalParameters.clear() |
| 98 |
GlobalParameters.globalParameters.update(newGlobalParameters) |
| 99 |
|
| 100 |
|
| 101 |
def ProcessingPool(enable=True, maxTasksPerChild=None): |
| 102 |
import multiprocessing |
| 103 |
import multiprocessing.dummy |
| 104 |
|
| 105 |
threadCount = CPUThreadCount() |
| 106 |
|
| 107 |
if (not enable) or threadCount <= 1: |
| 108 |
return multiprocessing.dummy.Pool(1) |
| 109 |
|
| 110 |
if multiprocessing.get_start_method() == "spawn": |
| 111 |
from . import GlobalParameters |
| 112 |
|
| 113 |
return multiprocessing.Pool( |
| 114 |
threadCount, |
| 115 |
initializer=OverwriteGlobalParameters, |
| 116 |
maxtasksperchild=maxTasksPerChild, |
| 117 |
initargs=(GlobalParameters.globalParameters,), |
| 118 |
) |
| 119 |
else: |
| 120 |
return multiprocessing.Pool(threadCount, maxtasksperchild=maxTasksPerChild) |
| 121 |
|
| 122 |
|
| 123 |
def ParallelMap(function, objects, message="", enable=True, method=None, maxTasksPerChild=None): |
| 124 |
""" |
| 125 |
Generally equivalent to list(map(function, objects)), possibly executing in parallel. |
| 126 |
|
| 127 |
message: A message describing the operation to be performed. |
| 128 |
enable: May be set to false to disable parallelism. |
| 129 |
method: A function which can fetch the mapping function from a processing pool object. |
| 130 |
Leave blank to use .map(), other possiblities: |
| 131 |
- `lambda x: x.starmap` - useful if `function` takes multiple parameters. |
| 132 |
- `lambda x: x.imap` - lazy evaluation |
| 133 |
- `lambda x: x.imap_unordered` - lazy evaluation, does not preserve order of return value. |
| 134 |
""" |
| 135 |
from .GlobalParameters import globalParameters |
| 136 |
|
| 137 |
threadCount = CPUThreadCount(enable) |
| 138 |
pool = ProcessingPool(enable, maxTasksPerChild) |
| 139 |
|
| 140 |
if threadCount <= 1 and globalParameters["ShowProgressBar"]: |
| 141 |
|
| 142 |
|
| 143 |
mapFunc = map |
| 144 |
if method is not None: |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
try: |
| 149 |
mapFunc = method(itertools) |
| 150 |
except NameError: |
| 151 |
mapFunc = None |
| 152 |
|
| 153 |
if mapFunc is not None: |
| 154 |
return list(mapFunc(function, tqdm(objects, message))) |
| 155 |
|
| 156 |
mapFunc = pool.map |
| 157 |
if method: |
| 158 |
mapFunc = method(pool) |
| 159 |
|
| 160 |
objects = zip(itertools.repeat(function), objects) |
| 161 |
function = apply_print_exception |
| 162 |
|
| 163 |
countMessage = "" |
| 164 |
try: |
| 165 |
countMessage = " for {} tasks".format(len(objects)) |
| 166 |
except TypeError: |
| 167 |
pass |
| 168 |
|
| 169 |
if message != "": |
| 170 |
message += ": " |
| 171 |
|
| 172 |
print("{0}Launching {1} threads{2}...".format(message, threadCount, countMessage)) |
| 173 |
sys.stdout.flush() |
| 174 |
currentTime = time.time() |
| 175 |
rv = mapFunc(function, objects) |
| 176 |
totalTime = time.time() - currentTime |
| 177 |
print("{0}Done. ({1:.1f} secs elapsed)".format(message, totalTime)) |
| 178 |
sys.stdout.flush() |
| 179 |
pool.close() |
| 180 |
return rv |
| 181 |
|
| 182 |
|
| 183 |
def ParallelMapReturnAsGenerator(function, objects, message="", enable=True, multiArg=True): |
| 184 |
from .GlobalParameters import globalParameters |
| 185 |
|
| 186 |
threadCount = CPUThreadCount(enable) |
| 187 |
print("{0}Launching {1} threads...".format(message, threadCount)) |
| 188 |
|
| 189 |
if threadCount <= 1 and globalParameters["ShowProgressBar"]: |
| 190 |
|
| 191 |
callFunc = lambda args: function(*args) if multiArg else lambda args: function(args) |
| 192 |
return [callFunc(args) for args in tqdm(objects, message)] |
| 193 |
|
| 194 |
with concurrent.futures.ProcessPoolExecutor(max_workers=threadCount) as executor: |
| 195 |
resultFutures = (executor.submit(function, *arg if multiArg else arg) for arg in objects) |
| 196 |
for result in concurrent.futures.as_completed(resultFutures): |
| 197 |
yield result.result() |
| 198 |
|
| 199 |
|
| 200 |
def ParallelMap2( |
| 201 |
function, objects, message="", enable=True, multiArg=True, return_as="list", procs=None |
| 202 |
): |
| 203 |
""" |
| 204 |
Generally equivalent to list(map(function, objects)), possibly executing in parallel. |
| 205 |
|
| 206 |
message: A message describing the operation to be performed. |
| 207 |
enable: May be set to false to disable parallelism. |
| 208 |
multiArg: True if objects represent multiple arguments |
| 209 |
(differentiates multi args vs single collection arg) |
| 210 |
""" |
| 211 |
if return_as in ("generator", "generator_unordered") and not joblibParallelSupportsGenerator(): |
| 212 |
return ParallelMapReturnAsGenerator(function, objects, message, enable, multiArg) |
| 213 |
|
| 214 |
from .GlobalParameters import globalParameters |
| 215 |
|
| 216 |
threadCount = procs if procs else CPUThreadCount(enable) |
| 217 |
|
| 218 |
threadCount = CPUThreadCount(enable) |
| 219 |
|
| 220 |
if threadCount <= 1 and globalParameters["ShowProgressBar"]: |
| 221 |
|
| 222 |
return [function(*args) if multiArg else function(args) for args in tqdm(objects, message)] |
| 223 |
|
| 224 |
countMessage = "" |
| 225 |
try: |
| 226 |
countMessage = " for {} tasks".format(len(objects)) |
| 227 |
except TypeError: |
| 228 |
pass |
| 229 |
|
| 230 |
if message != "": |
| 231 |
message += ": " |
| 232 |
print("{0}Launching {1} threads{2}...".format(message, threadCount, countMessage)) |
| 233 |
sys.stdout.flush() |
| 234 |
currentTime = time.time() |
| 235 |
|
| 236 |
pcall = pcallWithGlobalParamsMultiArg if multiArg else pcallWithGlobalParamsSingleArg |
| 237 |
pargs = zip(objects, itertools.repeat(globalParameters)) |
| 238 |
|
| 239 |
if joblibParallelSupportsGenerator(): |
| 240 |
rv = Parallel(n_jobs=threadCount, timeout=99999, return_as=return_as)( |
| 241 |
delayed(pcall)(function, a, params) for a, params in pargs |
| 242 |
) |
| 243 |
else: |
| 244 |
rv = Parallel(n_jobs=threadCount, timeout=99999)( |
| 245 |
delayed(pcall)(function, a, params) for a, params in pargs |
| 246 |
) |
| 247 |
|
| 248 |
totalTime = time.time() - currentTime |
| 249 |
print("{0}Done. ({1:.1f} secs elapsed)".format(message, totalTime)) |
| 250 |
sys.stdout.flush() |
| 251 |
return rv |